epsilones
epsilones

Reputation: 11609

Retrieving inputs' values using Jquery

I'd like to retrieve some input box' value of my page to proceed to an ajax request, so I wrote :

    var account_data = ['firstname', 'lastname', 'e-mail'];
    $.each(account_data, function(index,value){
       var tmp = '[name='+value+']';
       data.value = $(tmp).val();
    });

But it doesn't work when I alert the values in my console (it returns undefined)

Upvotes: 0

Views: 71

Answers (2)

bipen
bipen

Reputation: 36531

use input selector with name attributes

try this

data={};  //create new object
var account_data = ['firstname', 'lastname', 'e-mail'];
$.each(account_data, function(index,value){
   var tmp = 'input[name="'+value+'"]'; //here
   //alert($(tmp).val());
   data[value] = $(tmp).val();  //push the value to the data object
});

now you can proceed the data with the ajax request

Upvotes: 1

adeneo
adeneo

Reputation: 318162

If it's all the inputs you could do:

var account_data = $.map( $('input'), function() { return this.value; });

otherwise:

var account_data = ['firstname', 'lastname', 'e-mail'],
    data = {};

$.each(account_data, function(index,vals){
   data[vals] = $('[name="'+vals+'"]').val(); //you're overwriting data.value
});

console.log(data);

Upvotes: 1

Related Questions