java148
1
I am trying to write a generic javascript tool to get form field name, id and its value with JQuery.
<div id="StudentForm">
<div><input id='name' name='name' value='John' /></div>
</div>
For example, I want to get all fields inside ‘StudentForm’ div, output its id, name and its value. how to write a generic toolkit or API ?
I like JQuery, so I prefer JQuery solution.
Thanks
Hi there,
First off, if it’s a form, use form tags, not div tags 
Secondly, be aware of the .serialize() method which does some of this for you.
This method encodes a set of form elements as a string for submission.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Serialize example</title>
</head>
<body>
<form id="studentForm">
<input id='name1' value='John' />
<input id='name2' value='Connie' />
<input id='name3' value='Bill' />
<input id='name4' value='Mary' />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
console.log($("form").serialize());
</script>
</body>
</html>
Apart from that, if you want to do it yourself, here’s some code to get you started:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Serialize example</title>
</head>
<body>
<form id="studentForm">
<input id='name1' value='John' />
<input id='name2' value='Connie' />
<input id='name3' value='Bill' />
<input id='name4' value='Mary' />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.fn.mySerialize = function() {
var inputs = $(this).find("input");
inputs.each(function(){
console.log("Id is: " + this.id + ", value is: " + this.value);
});
return this; // enables chaining
};
$("form").mySerialize();
</script>
</body>
</html>
If anything’s unclear, just let me know.
java148
3
my problem is this, my form is inside of another form, then I found everything doesn’t work. that is reason I want to create my own.
Hi there,
The code I posted should work with any element containing child input elements: $("#myDiv").mySerialize();
But I’m curious. Why would you need to nest forms?