I have a form that submits values to database via Ajax and works fine but I also need to give option to user to reset the form to its default values in case they make a mistake.
The default values are stored in a javascript variable as json object
{"field_name1":"2","field_name3":"3","field_name3":"1000"...
problem I have is that the form has multiple input types , textarea , select , radio
and I need to figure out what they are based on the object key , look for name and return type , so I could do something like if radio set checked checked and so on
I tried
Object.each(dafaultValues, function(value, key){
var filed_name = MyForm.elements[''+key+''];
console.log(filed_name.type);
});
problem with this is that radio type have same name but different id’s
<input type="radio" name="field_name5" id="field_name51" value="1">
<input type="radio" name="field_name5" id="field_name52" value="1" checked="checked">
and I endup with js error
Uncaught TypeError: Cannot read property ‘type’ of undefined
so what would be the best way to find out what the input type is before I can do
if(field.type ='radio'){
//set checked checked..
}
Take a look at this example. I just put it together very dirty, but you will get the idea 😉
HTML:
JS: