Issue
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>");
}
});
});
Solution
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!
Answered By - melvazquez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.