I would like to create a nested object like below base on input forms. First key would be the name attribute, inside it would get required: true if the onput contains reqiuder attribute etc. I assume I need a nested foreach for that, I'm not sure. I added the code what I tried so far.
This is the object I like to create:
var obj = {
'email.address': {
required: true,
email: true
},
'first.name': {
required: false
},
'last.name': {
required: true
}
};
This is the code I have at the moment:
var formInputs = $('input'), obj = {}; $.each(formInputs, function(key, value) { obj[this.name] = value.name; }); console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="email" name="email.address" placeholder="Email address" required /> <input type="text" name="first.name" placeholder="First name" /> <input type="text" name="last.name" placeholder="Last name" required /> </form>
for (var i = 0, v; v = formInputs[i]; i++) {
for (var o of Object.keys(obj)) {
if (o !== v.name) {
continue;
}
for (var n of Object.keys(obj[o])) {
v[n] = obj[o][n];
}
}
}
The issue is that you aren't waiting for your document to load before parsing.
jquery lets you wait until the document is ready with $(document).ready()
here is an example you can replace your js with
$(document).ready(function(){
var formInputs = $('input'),
obj = {};
$.each(formInputs, function(key, value) {
obj[this.name] = {required: value.required}
});
console.log(obj)
})
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.