0

Let's say I have an object with keys and values like

{
  input_1: 'value_of_input_1',
  input_2: 1,
  input_3: 'two'
}

Then some input fields:

   <input type="text" name="input_1">
   <input type="checkbox" name="input_2">
   <select name="input_3">
     <option value="one"> One </option>
     <option value="two"> Two </option>
     <option value="three"> Three </option>
   </select>

Is there some jQuery function that is able to copy the values from the object variable to the actual input fields? I mean set the correct values, check or uncheck checkboxes, select correct option etc...

I know about $.val() but it only works for text fields?

Alex
  • 66,732
  • 177
  • 439
  • 641

1 Answers1

0

I know it's frowned upon to respond to a question about library A with a "Just use library B!"-type answer. So take this as an option to think about, not more. Maybe it's just the right idea for your situation.

You are looking for a data-binding library (keyword MVVM) like Knockout.

Most trivial example:

function ViewModel(data) {
    ko.mapping.fromJS(data, {}, this);
}

var data = {
    input_1: 'value_of_input_1',
    input_2: 1,
    input_3: 'two'
};

ko.applyBindings(new ViewModel(data));

and

<input type="text" name="input_1" data-bind="value: input_1">
<input type="checkbox" name="input_2" data-bind="checked: input_2">
<select name="input_3" data-bind="value: input_3">
  <option value="one"> One </option>
  <option value="two"> Two </option>
  <option value="three"> Three </option>
</select>

See this fiddle: http://jsfiddle.net/t2QhU/2/

Tomalak
  • 332,285
  • 67
  • 532
  • 628