简体   繁体   中英

how to convert variable name into index string of object jquery

when I make a looping based on the content in the form of an input form I'll take the attribute name to be used as a selector element and object index array of data , but the index is the variable name

how to convert from a variable name to string index on an object array of data?

it aims to make input in the form can be filled automatically from the object array of data

 var data = { id: "4", Model: "804", Description: "AXIAL SETTER,100MM, MAGNETIC BASE" }; var names = []; if ($('#form').length == 1) { $('#form :input').each(function() { names.push($(this).attr('name')); }); $.each(names, function(key, value) { $('[name="' + value + '"]').val(data.value); //value should be change with name, //for example : // $('name="Description"').val(data.Description); }); } 
 <form action="#" id="form" class="form-horizontal"> <input type="hidden" name="id" /> <br/> <input type="text" name="Model" placeholder="Model Of product" /> <br/> <input type="text" name="Description" placeholder="Description Of product" /> <br/> <button type="submit" class="btn-save">save</button> </form> 

No need to run twice over the same data. You could simply do this to fill your form:

var data = {
  id: "4",
  Model: "804",
  Description: "AXIAL SETTER,100MM, MAGNETIC BASE"
};

if ($('#form').length == 1) {
  $('#form :input').each(function() {
    if (typeof data[$(this).attr('name')] != 'undefined'){
        $(this).val(data[$(this).attr('name')]);
    }
  });

}

Have a look at https://jsfiddle.net/nfq22d9r/1/

The code runs through all the forms input fields, checks if a fields name is existent as a key in the data object and sets the fields value to the one in the data object, if the key was found

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