I'm trying to dynamically create objects out of forms, but I want some reduntant elements to be ommitted, such as the submit.
The only problem is that my function won't omit these fields.
function form_to_json(formname) {
var obj = new Object();
var identity = "#" + formname + " input";
// Create JSON strings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~开发者_C百科~~~~~~~~~
$(identity).each(function() {
if ($(this).val() != "Submit" || $(this).attr('name') != "password2") {
var propertyName = $(this).attr('name');
var propertyValue = $(this).val();
eval("obj." + propertyName + "='" + propertyValue + "'");
}
});
var jsonObj = JSON.stringify(obj);
return jsonObj;
}
The output spits out a nice little json object the only problem is it doesn't omit the form elements I'm asking it to.
Is it something to do with the selectors?
OK I just had a brainstorm and tried splitting up the if statement into two...
if ($(this).val() != "Submit") {
if ($(this).attr('name') != "password2") {
var propertyName = $(this).attr('name');
var propertyValue = $(this).val();
eval("obj." + propertyName + "='" + propertyValue + "'");
}
}
This did work.
You can do it in single if condition also. You just have to change OR condition to AND
if ($(this).val() != "Submit" && $(this).attr('name') != "password2") {
精彩评论