Get multi-field value

1

I'm done with each of a form that contains input and select . The post of this form is done in json with ajax.

My script today gets the values of 2 input like this:

var name = $('#news-nome').val(),
    email = $('#news-email').val();

sendData({email: email, nome: name})

How do I get the value of all fields without having to place one by one the same as the above example? In case my new form is 17 fields if it were to follow the above example would be 17 variables.

    
asked by anonymous 27.09.2016 / 18:11

2 answers

0

How did you respond to the Lucas Queiroz that all fields are of the same type:

var json = {};

$( "#minhaDiv" ).find( "input :text" ) .each(function(){

  json[ $(this).attr('name') ] =  $(this).val();

})

console.log(json);

You may have to implement some checks on these values, as some may be undefined .

    
27.09.2016 / 19:03
0

If the posting parameters are declared in the name element attribute of each field on your form, you can use the $.fn.serialize (commented on by @Zuul). The method will return usable URL text in the "data" property that is inside the $.ajax ( $.post , etc) method option object.

To better understand this method, let's assume that we have a form like this:

<form>
    <select name="Tipo">
        <option>Caixa</option>
        <option selected>Leite</option>
    </select>
</form>

Then we serialize it with $.fn.serialize :

$("form").serialize()

and we get:

"Tipo=Leite"

If the case is otherwise, you can construct an object containing each post parameter as property by assigning the element identifier of its field itself. With this you can go through each property and build a new object with the values of the elements.

* The identifier is equivalent to the value that is declared in the id attribute of an element.

var dataBuffer = {
    "email": "news-email"
  , "nome": "news-nome"
};

var dataToPost = {};

for (var param in dataBuffer)
  dataToPost[param] = $('#'+dataBuffer[param]).val();

sendData(dataToPost);
    
28.09.2016 / 02:44