1

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 don't 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.

$( this ) is getting undefined values for the class, also input.class is geting undefined values. The only attributes I can reach with this approach, are name and value (like shown above)

I also tried to approach 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>");
            }
        });
    });
0

2 Answers 2

3

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;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

It seems that the serialized array is not catching anything with this. I am trying instead with input.class, that I know that I can access to it without problem.
better if you make a fiddle.
1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.