I have开发者_开发问答 a long form and trying to get the loop done. but i am not sure how to check for options (dropdown) and radio type's, if exist, select the checked or selected and put it in the array.
Is there a better way to construct it? and when the loop is done, to pass the var for sending it in ajax?
var parameters = "";
var form = document.getElementById("someForm");
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].value) {
if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "hidden")
parameters = parameters + '&' + form.elements[i].name+'='+escape(form.elements[i].value);
if((form.elements[i].type == "radio" || form.elements[i].type == "checkbox") && form.elements[i].checked)
parameters = parameters + '&' + form.elements[i].name+'='+form.elements[i].value;
}
}
I generally use something like this, if I need to ajax a form. Simply append parameters to the end of your ajax request.
I would take a look at the way jQuery does it. Specifically you will want to look at the serialize
(line 6260), serializeArray
(line 6264) and param
(line 6784) methods.
According to this comparison of form serialization in different JavaScript libraries, jQuery's implementation adheres to the W3C specification better than the competition.
I agree in looking at jQuery, but maybe try implementing something yourself. You could get all inputs / textareas / selects within the form quite easily using jQuery:
// get all input fields, except buttons
var inputs = $("form input:not(:button)");
// get all dropdowns
var dropdowns = $("form select");
// get all text areas (i.e. "big" textboxes)
var textareas = $("form textarea");
I used something like this (I edited line 2 of Sheldon's solution):
var parameters = "";
var form = document.someForm;
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].value) {
if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "hidden")
parameters = parameters + '&' + form.elements[i].name+'='+escape(form.elements[i].value);
if((form.elements[i].type == "radio" || form.elements[i].type == "checkbox") && form.elements[i].checked)
parameters = parameters + '&' + form.elements[i].name+'='+form.elements[i].value;
}
}
精彩评论