最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add object property from input.value - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited Sep 12, 2016 at 18:18 Lau asked Sep 12, 2016 at 18:14 LauLau 1792 gold badges4 silver badges13 bronze badges 1
  • Try to add a button or at least a change listener to monitor change in input and then update foo by getting new value entered in text box. – Harry Joy Commented Sep 12, 2016 at 18:17
Add a ment  | 

2 Answers 2

Reset to default 1

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./jsref/prop_text_value.asp

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

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

发布评论

评论列表(0)

  1. 暂无评论