简体   繁体   中英

Add object property from input.value

Say I have an object with states as properties and an html input text field.

<input id="input" type="text">

var foo = {
    "Wisconsin" : "Madison",
    "Illinois" : "Springfield"

}

How can I add properties to foo using the input text field ? I tried this :

 foo[input.value] = input.value;

but of course it didn't work...

Thanks for your help

foo.newValue = input.value

You are dealing with an object not an array.

So this will result in

{ "Wisconsin" : "Madison", "Illinois" : "Springfield", "newValue" : VALUE-OF-INPUT-FIELD

}

Here is a working fiddle

To use normal javascript functions you can use:

foo.input = document.getElementById('input').value;

Or you can use jQuery:

foo.input = $('#input').val();

Input Box Value Property: http://www.w3schools.com/jsref/prop_text_value.asp

jQuery .val(): http://api.jquery.com/val/

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