您還可以使用serializeArray
方法jQuery中還有:https://api.jquery.com/serializeArray/
示例:
$(document).ready(function() {
var oParams = {
'invalid_msgs' : {
'title' : 'Kindly provide the title',
'body' : 'Kindly provide the body',
'type' : 'Kindly provide the type'
},
};
$('#frm-add-content').submit(function(event) {
event.preventDefault();
var oFormData = $(this).serializeArray();
// console.log(oFormData);
for (var iIndex in oFormData) {
if (oFormData.hasOwnProperty(iIndex) === true) {
var sInputKeys = oFormData[iIndex].name; // (e.g title)
var sInputValues = oFormData[iIndex].value; // (e.g Title 1)
/* If in case there are [input] fields that
* are not required in this case, You can set
* condition like this
* In this case, The input that had the [author]
* name attribute will be 'exempted' for validation
*/
var aNotRequiredInputKeys = ['author'];
if ($.inArray(sInputKeys, aNotRequiredInputKeys) < 0) {
if ($.trim(sInputValues) === '') {
alert(oParams.invalid_msgs[sInputKeys]);
return false;
}
}
}
}
});
});
這裏是一個jsfiddle供參考:https://jsfiddle.net/xdp70kt3/2/
希望這會引導你好。
另一方面,您還可以添加required
html屬性,以及如果您只想檢查是否輸入了值,則爲 。
由於沒有其他意見,添加。 –