巧用jQuery选择器提高写表单效率的方法

2020-05-24 21:34:34易采站长站整理

}
});
$("input[type='checkbox']").each(function () {
if($(this).attr('name') != checkboxName){
checkboxName = $(this).attr('name');
model[checkboxName] = getCheckboxValue(checkboxName);
}
});
console.log(model);
}

处理radio和checkbox的一些方法

这里我对radio和checkbox的显示和获取结果写了几个方法。


function showRadioValue(name, value) {
$('input[name=' + name + ']').each(function () {
if(value == $(this).val()){
$(this).attr('checked', 'true');
}
});
}

function getRadioValue(name) {
var value = 0;
var i = 0;
$('input[name=' + name + ']' ).each(function () {
if ($('input[name=' + name + ']').eq(i).is( ':checked')) {
value = $('input[name=' + name + ']').eq(i).val();
return;
}
i++;
});
return value;
}

function showCheckBoxValue (name, value) {
var values = value.split(',' );
var row = 1;
$('input[name="' + name + '"]').each( function () {
if (values[row] == 1) {
$(this).attr("checked" , 'true');
}
row++;
});
}

function getCheckboxValue (name) {
var text = "" ;
$('input[name="' + name + '"]').each( function () {
var t = '' ;
if ($(this ).is(':checked')) {
t = "1";
} else {
t = "0";
}
text += "," + t;
});
return text;
}

代码


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-2.2.3.js"></script>
</head>
<body>
<div>
<div>
<label><input type="radio" name="param01" value="1">1</label>
<label><input type="radio" name="param01" value="2">2</label>
<label><input type="radio" name="param01" value="3">3</label>
</div>
<div>
<label><input type="radio" name="param02" value="1">1</label>
<label><input type="radio" name="param02" value="2">2</label>
<label><input type="radio" name="param02" value="3">3</label>
</div>
<div>
<label><input type="radio" name="param03" value="1">1</label>
<label><input type="radio" name="param03" value="2">2</label>
<label><input type="radio" name="param03" value="3">3</label>