简体   繁体   中英

using an if to detect a class using jQuery

I am trying to get a form into a serializedArray to be introduced into an API, but i need to detect all the elements with class "image", and instead of do it in the same way as the other elements, put them into a single array. The thing is I dont know exactly how to build that if condition.

What I currently have is:

add.serializeArray().forEach(function(input) {
    if(input.class === "images"){
        data[images].push(input.value);
    }
    else{
        data[input.name] = input.value;
    }
});

So I go through all the input elements, and if they are not of this class, I add them as usual.

I modified this question, because with the solution proposed, $( this ) is getting undefined values for the class, also input.class is geting undefined values. The only atributes I can reach with this aproach, are name and value (like shown above)

Sorry if something is not clear, this is my first time using stack overflow, and thanks in advanced.

Edit: I also tried to aproach it with the example I found on w3schools for serializeArray, but it seems that it doesn't work neither

$(document).ready(function(){
    $("button").click(function(){
        var x = $("form").serializeArray();
        $.each(x, function(i, field){
            if($(this).hasClass("images")){
                $("#results").append("if is sentence is true "+field.name + ":" + field.value + " </br>");
            }
            else{
                $("#results").append("if sentence is false "+field.name + ":" + field.value + " </br>");
            }
        });
    });

You can do like this,

you can see the info here

add.serializeArray().forEach(function(input) {
    if($( this ).hasClass( "image" )){
        data[images].push(input.value);
    }
    else{
        data[input.name] = input.value;
    }
});

Finally, I managed to get this working, with something similar to "contains" in java. We access to the input.name string (other properties were not reachable for me), and if it contained the string "images", i added them to the array:

var data = { };
data["images"] = [];
add.serializeArray().forEach(function(input) {
    if(input.name.indexOf("images") > -1){
        data["images"].push(input.value);
    }
    else{            
        data[input.name] = input.value;
    }
});

So, this is how I fixed it, as the problem resided in the element input not having any class property. I leave it here in case someone needs it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM