2

As every developer wants, I wanted to make my code short and simple. but makes sense.

I have this edit profile field that have several fields, about 10 text box and 2 radio buttons.

In a simple login form, i could just get the values of username and password like this:

$("#username") and $("#password") and assign them into a variable username password respectively,

That will become like this: (in ajax)

$.ajax({
    url : some_url,
    data: {
        username : username,
        password : password
    success : something
    }
});

but what if i have several fields, i don't want my code to be super messy, having all those assignments.

so i come up with an idea of having a key-value pairs that will be based on their input-id

var object;
$("#formUpdate:input").each(function(){
      var key = $(this).attr('id');
      var value = $(this).val();
      object.key = value;
});

question, what am i missing out, i can't make it work though, are there better ways to do it. Do you think hard-coding it is much better.

Thanks much guys! It's my birthday today btw.

1
  • You should be able to just use $(form).serializeArray() though that's based on the input's name, not it's id.
    – Kevin B
    Oct 29, 2012 at 17:43

2 Answers 2

3

You are using the wrong syntax to add a dynamic key to an object. You need bracket notation ["string"]

var obj = {};
$("#formUpdate :input").each(function(){ 
    var key = $(this).attr('id'); 
    var val = $(this).val(); 
    obj[key] = val; 
});

though you should be able to just do:

var obj = $("#formUpdate").serialzeArray();

assuming your inputs also have name attributes.

Edit: you were also missing a space in your input selector.

1
  • didn't know there is a serializeArray function. But anyway it's always nice to do things like what i did, then ask later. hehehehe. thank you so much kevin!! Oct 29, 2012 at 18:11
1

You need to pass them as key: value : pairs .. Try this

If you want to store as Array of Objects ..

var arr = [];
$("#formUpdate :input").each(function() {
    arr.push( { $(this).attr('id') : $(this).val() }) ;
});​

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.