Skip to content Skip to sidebar Skip to footer

How Can I Elegantize This Verbose Jquery?

I need to get the value of the checked checkbox (only one is allowed to be checked at a time), and I have this verbose code to do so: if (!checkboxSelected) { return; } if($('

Solution 1:

$(function()
{
...
// IF (these are the only elements that id starts with ckbx_) THEN
    rptval = $('[id^=ckbx_]').filter(':checked').val();
// ELSE// this syntax is more maintainable than $('#ckbx_produceusage, #ckbx_fillrate, ... selectors à la queue');
    rptval = $('#ckbx_produceusage').add('#ckbx_fillrate').add('#ckbx_deliveryperformance').add('#ckbx_pricecompliance').filter(':checked').val();
// FI
...
});

Solution 2:

JQuery collections are filterable, so I'd suggest using the following:

//getvalueoffirst checked checkbox
var rptval = $(
   "#ckbx_produceusage,"+
   "#ckbx_deliveryperformance,"+
   "#ckbx_fillrate,"+
   "#ckbx_pricecompliance"
).filter(':checked').first().val();

Note: The .first() may even be unnecessary since .val() gets the value of the first element in the collection. Left in for legibility's sake.

Solution 3:

Without changing your HTML, you can at least avoid repeating yourself by using a loop:

["#ckbx_produceusage", "#ckbx_deliveryperformance", "#ckbx_fillrate", "#ckbx_pricecompliance"].some(function(sel) {
    var e = $(sel);
    if (e.is(":checked")) {
        rptval = e.val();
        returntrue;
    }
});
setEmailAndGenerateValsForUnitReportPair(unitval, rptval)

You could probably change your HTML such that the initial array could be a query rather than a hardcoded list of ID selectors.

Solution 4:

You also need to account for the situation where none are checked. Never assume something is set.

functiongetValue(checkBoxes)
{
    for ( var i = 0; i < checkBoxes.length; i++ )
    {
        var name = "#ckbx_" + checkBoxes[ i ];

        if ( $( name ).is( "checked" ) ) return $( name ).val();
    }

    //None were checkedreturnnull; //Should throw exception
}

rptval = getValue( [ "produceusage", "deliveryperformance", "fillrate", "pricecompliance" ] );

Solution 5:

Try using .each()

  $("input[type='checkbox']").each(function() {
    var rptval = 0;
    if ($(this).is(":checked")) {
      rptval = 1;
    }
    setEmailAndGenerateValsForUnitReportPair(unitval, rptval);
  });

Post a Comment for "How Can I Elegantize This Verbose Jquery?"