简体   繁体   English

从input.value添加对象属性

[英]Add object property from input.value

Say I have an object with states as properties and an html input text field. 假设我有一个状态为属性的对象和一个html输入文本字段。

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

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

}

How can I add properties to foo using the input text field ? 如何使用输入文本字段向foo添加属性? 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 {“Wisconsin”:“Madison”,“Illinois”:“Springfield”,“newValue”:输入值的字段

} }

Here is a working fiddle 这是一个工作小提琴

To use normal javascript functions you can use: 要使用普通的javascript函数,您可以使用:

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

Or you can use jQuery: 或者你可以使用jQuery:

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

Input Box Value Property: http://www.w3schools.com/jsref/prop_text_value.asp 输入框值属性: http//www.w3schools.com/jsref/prop_text_value.asp

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM