简体   繁体   中英

get Input values dynamically in jquery

I am devolping a web application using symfony framework. I have aproblem in forms. Here is my code:

$('#bookCleaningForm').submit(function() {
    // get the array of all the inputs 
    var $inputs = $('#bookCleaningForm :input[type=text]');

    // get an associative array of the values
    var values = {};
    var allVAlues='';
    $inputs.each(function() {
        values[this.name] = $(this).val();
            allVAlues = values[this.name];

    });
    alert(allValues);//console.log(allValues);
    saveBoookCleaning(allVAlues);

});

In the loop i got all data in allValues variable.But when I access outside the loop i got only one value.

Please help

Each time in the each loop you are assigning the variable allValues to the value of the current input. If you want to store the values as an array you could do this:

$('#bookCleaningForm').submit(function() {
  // get the array of all the inputs 
  var $inputs = $('#bookCleaningForm :input[type=text]');

  // get an associative array of the values
  var values = {};
  var allVAlues=[];
  $inputs.each(function() {
    values[this.name] = $(this).val();
        allVAlues.push(values[this.name]);

  });
  alert(allVAlues);//console.log(allValues);
  saveBoookCleaning(allVAlues);

});

Or, if you want them as a string:

$('#bookCleaningForm').submit(function() {
  // get the array of all the inputs 
  var $inputs = $('#bookCleaningForm :input[type=text]');

  // get an associative array of the values
  var values = {};
  var allVAlues='';
  $inputs.each(function() {
    values[this.name] = $(this).val();
        allVAlues += values[this.name];

  });
  alert(allVAlues);//console.log(allValues);
  saveBoookCleaning(allVAlues);

});

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