简体   繁体   中英

Javascript getting the values of an array of input boxes

I have an input field that has a button to dynamically add another input field and I am trying to get it so that when I click plot i am able to grab the content inside the input fields gps[]

html

<div id="marker">
    <input type="text" name="gps[]" id="gps">
    <input type="text" name="gps[]">
</div>

Plot

javascript

var counter = 1;
var limit = 3;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "<input type='text' name='gps[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}
$('body').on('click','.plot', function(){
    var y = $('input[name="gps[]"]').val();
    console.log(y);
});

You have to use .map to get the value of all the elements in the collection :

var y = $('input[name="gps[]"]').map(function() {return this.value;}).get();

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM