Binding from Html Dom elements to json objects
I am working on a search panel, where I want to bind the data entered in these input elements to a search parameter json object. This search parameter will then be used for, you guessed it right, searching.
For example, user when searching for another person and he can specify the name, age or sex of the person on the page. I have json object which has, as its members Name, Age and Sex. I want to bind the inputs entered in the corresponding input elements on the page to this JSON object automatically, so when the user clicks on the Search I will just use whatever the json object has as a search param.
This is primarily to avoid having to - first find the corresponding element and then assign the corresponding member of the JSON object to the input in this field.
I could find jquery plugins (Databind) , which do the开发者_运维问答 other way round i.e. transfer the values of a JSON object to the input elements.
Thanks in advance!!
I think you are confusing your terminology: presumably you mean a Javascript object.
Anyway, your object or json string need to be constructed when the user clicks "Search". It will be difficult/fiddly to assign these as the user enters text into the input fields. You could use the onblur
event but you're just making unnecessary work for yourself.
Far easier is just to give each input field an id, and when the user clicks "Search" you build your object, then JSONify it. Here's how you might do it (not tested!):
<input type="text" id="name" />
<input type="text" id="age" />
...
var obj = { };
obj.name = document.getElementById('name').value;
obj.age = document.getElementById('age').value;
...
var json = JSON.stringify(obj);
精彩评论