Get an array of values ​​from multiple inputs using jQuery

Can someone please let me know how to get values ​​from multiple input fields?

I have a list with several inputs like this:

<li> <label>Additional Title: </label><input type='text' name='additionaltitlename' ... /> </li> <li> <label>Additional Title: </label><input type='text' name='additionaltitlename' ... /> </li> 

I have a solution in Javascript (on the submit form):

 ... var extratitles = document.getElementsByName('additionaltitlename'); var str = ''; for (var i = 0; i < extratitles.length; i++) { str = str + '|' + extratitles.item(i).value; } } 

How do I do the same in jQuery?

+6
source share
4 answers

It is not valid to have two entries with the same name. If you want to do this, you can use <input name="titles[]">

You can try the following:

 <input name="titles[]"> <input name="titles[]"> ​<button>submit</button>​​​​​​​​​​​​​​​​​​​​​​​ 

Using this jQuery

 // click handler function onClick(event) { var titles = $('input[name^=titles]').map(function(idx, elem) { return $(elem).val(); }).get(); console.log(titles); event.preventDefault(); } // attach button click listener on dom ready $(function() { $('button').click(onClick); }); 

See how it works here on jsFiddle

EDIT

This answer gives you headers in an array instead of a string, using a separator | . Personally, I think this is much more convenient.

If you just submit the form and want to support multiple values, use the .serialize method as described in another answer

+16
source

Use the built-in jQuery serialize function:

 var data = $('input[name="additionaltitlename"]').serialize(); 

docs

The .serialize () method creates a text string in standard encoding with URL encoding. It works with a jQuery object representing a set of form elements.

+2
source

Facilities:

 str = ''; $("input[type='text']").each(function() { str = str + '|' + $(this).val(); }); 

or

 str = ''; $("input[name='additionaltitlename']").each(function() { str = str + '|' + $(this).val(); }); 

?

0
source

In addition to the @gdoron or @macek answers that probably fit, I would like to add that all that is wrong with the code you posted is that you have one } too many. This works (although it still has room for improvement):

 $('#getpreviewbutton').click(function(){ var extratitles = document.getElementsByName('additionaltitlename'); var str = ''; for (var i = 0; i < extratitles.length; i++) { str = str + '|' + extratitles.item(i).value; } });​ 

See: http://jsfiddle.net/8XJcc/

I don’t know which browser you are using, but using sth like Firebug or Chrome Dev Tools, it can be very convenient to detect such simple errors. See this link for Chrome or this one for Firefox. Even IE has one - just hit F12.

0
source

Source: https://habr.com/ru/post/911596/


All Articles