Get multiple field values

Asked

Viewed 149 times

1

How do I in each of a form containing input and select. The post of this form is in json with ajax.

My script today takes the values of 2 input thus:

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

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

How do I get the value you all fields without having to put one by one equal to the above example? In the case of my new form are 17 fields if I were to follow the example above would be 17 variables.

  • 2

    Take a look at: http://api.jquery.com/serialize/.

  • They’re all the same kind ? you can use $( "#minhaDiv" ).find( "input :text" )

  • Yes, I get them all with the class . input however my doubt is to take the value of each and put in order in my json that I will send.

2 answers

0

How did you respond to 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.

0

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

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 serialized him with $.fn.serialize:

$("form").serialize()

and we get:

"Tipo=Leite"

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

*The identifier is the value that is declared in the attribute id of a single element.

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

var dataToPost = {};

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

sendData(dataToPost);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.