How to make the Yes / No code shorter?

I have these dynamic flags with id + number +1. Can someone tell me how to make this code shorter? Probably nothing complicated, but I just started with jquery and javascript, so this is 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"); } 
+4
source share
4 answers

You can use a simple loop, for example.

 var n; for(n=1; n<10; n++) { $('#h'+n).val( $('#g'+n).is(':checked') ? 'Yes' : 'No' ); } 

And the tertiary operator makes the logic even more compact. You should rename your element identifiers "h" and "g" to "h1" and "g1" for consistency.

-1
source

The best thing to do is set up the markup to be more friendly to the needs of your code. However, if you do not, 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 don't like doing gymnastics with id values; I would establish the relationship between the β€œg” and β€œh” fields more explicit, using the β€œdata-” attributes or otherwise, grouping the elements in a specific way (inside a <span> with a specific class, or something else meaningful). I also don't like to pollute the markup, but usually a good balance can be found when what you do makes sense in general.

+10
source

try this one

 function shorter(selecter, selecter1) { if (!$(selecter + ':checked').length) { $("#" + selecter1).val("No"); } else { $("#" + selecter1).val("Yes"); } } 
0
source
 for (var i = 0; i < 11; i++) { ($("#g"+i+":checked").length) ? $("#h"+i).val("No") : $("#h"+i).val("Yes"); } 

Having said that, I will also slightly correct your markup, as suggested above. Perhaps give them all the classes to make them easy to assemble, and then perhaps an arbitrary attribute to indicate their number / position as <div class='checkbox' position='3'></div> or something like that

-1
source

All Articles