1252748
1252748

Reputation: 15379

put html input values into javascript object

Why isn't this code giving me an object with the keys as the ids of the text inputs, and the values as the values of the text inputs?

JS

$(document).ready(function () {
    $('body').on('click', '#btn', function () {
        var address = {};
        $('input[type="text"].address').each(function (index, element) {
            address[element.id] = $(element).val();
        });
        console.log(address);
    });
});

HTML

  <input class="address" id="attn" value="john doe">
  <input class="address" id="address_1" value="1234 sample st">
  <input class="address" id="address_2" value="Suite 1">
  <input class="address" id="city" value="chicago">
  <input class="address" id="state" value="IL">
  <input class="address" id="zip" value="12345">
  <input class="address" id="country" value="US">
  <input type="button" id="btn" value="btn" />

jsbin

Upvotes: 0

Views: 2687

Answers (5)

Aditya Singh
Aditya Singh

Reputation: 9612

Try out this one http://jsfiddle.net/adiioo7/TPYtg/

$(document).ready(function () {
    $('#btn').on('click', function () {
        var address = {};
        $('.address').each(function (index, element) {
            address[element.id] = $(element).val();
        });
        console.log(address);
    });
});

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191819

The jQuery attribute selector (as well as browser query selectors) work with the DOM elements rather than their properties. If you do not explicitly have the type attribute declaration on your the input elements, $("[type]") and document.querySelector("[type]") will not find the element even if its type property is text (http://jsfiddle.net/g76UC/).

The simplest solution is to add type=text to the input elements in your HTML. Another is to use a different selector that does not require this attribute definition. The final (and least desirable) would be to create a separate selector such as :prop that checks the element's type property instead. However this already exists in the form of jQuery's :text.

Upvotes: 1

Anton
Anton

Reputation: 32591

Use this

 $('input.address').each(function () {      
        address[this.id]= $(this).val();
 });

Demo http://jsbin.com/osufok/12/edit

Upvotes: 0

Bergi
Bergi

Reputation: 665564

Your inputs do not have the [type=text] attribute, so your selector matches none of them. Simply remove it, or use the :text selector:

var address = {};
$(':text.address').each(function (index, element) {
    address[element.id] = element.value;
});
console.log(address);

(updated demo)

Upvotes: 2

Joseph
Joseph

Reputation: 119887

It's because your inputs don't have type="text" thus $('input[type="text"].address') is not returning anything.

It's better to add them to signify that the inputs are of type text.

Upvotes: 2

Related Questions