Issue
I have form:
<form onchange="allvaluestostring()">
<select name="status">
<option value="*">All</option>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
<select name="size">
<option value="*">All</option>
<option value="small">Small</option>
<option value="big">Big</option>
</select>
</form>
And the onchange action of any input in form I need to get a JavaScript string, for example "status=1&size=big
" for using in httprequest.
Does there exist something in JavaScript that will take all form values when one of form inputs will be changed?
I used <select name="status" onchange="showExporteditems(this.name,this.value)">
, but this will take only one input value for using only "status=1
", but I need on each onchage all values from all inputs for string like "status=1&size=big&...etc....
".
Without using jQuery.
Solution
Here is a working fiddle in vanilla JavaScript, but you need to add a serialize utility function. This works exactly like $('form').serialize()
in jQuery.
JavaScript:
var data;
function serialize(form) {
if (!form || form.nodeName !== "FORM") {
return;
}
var i, j, q = [];
for (i = form.elements.length - 1; i >= 0; i = i - 1) {
if (form.elements[i].name === "") {
continue;
}
switch (form.elements[i].nodeName) {
case 'INPUT':
switch (form.elements[i].type) {
case 'text':
case 'hidden':
case 'password':
case 'button':
case 'reset':
case 'submit':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'checkbox':
case 'radio':
if (form.elements[i].checked) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
}
break;
}
break;
case 'file':
break;
case 'TEXTAREA':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'SELECT':
switch (form.elements[i].type) {
case 'select-one':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'select-multiple':
for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
if (form.elements[i].options[j].selected) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
}
}
break;
}
break;
case 'BUTTON':
switch (form.elements[i].type) {
case 'reset':
case 'submit':
case 'button':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
}
break;
}
}
data = q.join("&");
}
And change your form onchange
to
<form onchange="serialize(this)">
I tested it and am getting "size=small&status=0"
in the console.
Answered By - Seth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.