How to make "Yes"/"No" code shorter?
I have these dynamic checkboxes each with ID + number +1. Could anyone tell me how to make this code shorter? Probably nothing difficult, but I just started with jquery and javascript, so it's a bit complicated for me :(
if(!$('#g:checked').length){
$("#h").val("No");
} else {
$("#h").val("Yes");
}
if(!$('#g2:checked').length){
$("#h2").val("No");
} else {
$("#h2").val("Yes");
}
if(!$('#g3:checked').length){
$("#h3").val("No");
} else {
$("#h3").val("Yes");
}
if(!$('#g4:checked').length){
$("#h4").val("No");
} else {
$("#h4").val("Yes");
}
if(!$('#g5:checked').length){
$("#h5").val("No");
} else {
$("#h5").val("Yes");
}
if(!$('#g6:checked').length){
$("#h6").val("No");
} else {
$("#h6").val("Yes");
}
if(!$('#g7:checked').length){
$("#h7").val("No");
} else {
$("#h7").val("Yes");
}
if(!$('#g8:checked').length){
$("#h8").val("No");
} else {
$("#h8").val("Yes");
}
if(!$('#g9:checked').length){
$("#h9").val("No");
} else {
$("#h9").val("Yes");
开发者_运维百科}
if(!$('#g10:checked').length){
$("#h10").val("No");
} else {
$("#h10").val("Yes");
}
The best thing to do here is to adjust the markup so that it's friendlier to the needs of your code. Even if you don't do that, however, you can do something like this:
$('input:checkbox').each(function() {
var cb = this;
$('#h' + cb.id.replace(/^g/, '')).val(cb.checked ? 'Yes' : 'No');
});
Personally I dislike doing gymnastics with "id" values; I'd make the relationship between the "g" checkboxes and the "h" fields more explicit, either by using "data-" attributes or else by grouping the elements in some regular way (inside a <span>
with a particular class, or something else meaningful). I don't like polluting the markup either, but there's usually a good balance to be found when what you're doing makes sense overall.
try this one;
function shorter(selecter, selecter1) {
if (!$(selecter + ':checked').length) {
$("#" + selecter1).val("No");
} else {
$("#" + selecter1).val("Yes");
}
}
You can use a simple loop, eg.
var n;
for(n=1; n<10; n++) {
$('#h'+n).val( $('#g'+n).is(':checked') ? 'Yes' : 'No' );
}
And the tertiary operator makes the logic a little more compact as well. You should rename your 'h' and 'g' element ids to 'h1' and 'g1' for consistency.
for (var i = 0; i < 11; i++) {
($("#g"+i+":checked").length) ? $("#h"+i).val("No") : $("#h"+i).val("Yes");
}
That being said, I would also adjust your markup a bit as the poster above suggested. Perhaps give them all a class to easily collect them, then maybe an arbitrary attribute to indicate their number/position like <div class='checkbox' position='3'></div>
or something similar
精彩评论