Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make "Yes"/"No" code shorter?

Tags:

jquery

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");
}
like image 889
elvis Avatar asked Feb 25 '23 02:02

elvis


1 Answers

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.

like image 88
Pointy Avatar answered Feb 26 '23 21:02

Pointy