Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

html - 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($("#ckbx_produceusage").is(':checked')) {
    rptval = $('#ckbx_produceusage').val();
}
else if($("#ckbx_deliveryperformance").is(':checked')) {
    rptval = $('#ckbx_deliveryperformance').val();
}
else if($("#ckbx_fillrate").is(':checked')) {
    rptval = $('#ckbx_fillrate').val();
}
else if($("#ckbx_pricecompliance").is(':checked')) {
    rptval = $('#ckbx_pricecompliance').val();
}
setEmailAndGenerateValsForUnitReportPair(unitval, rptval);

Is there a way I can make this code less verbose without making it ungrokkable? I thought of dynamically adding a class to the checkbox that is checked, and then removing it from any that previously had that class added, and then getting the rptval based on which one is currently decorated with that class. That seems a bit smelly or Rubegoldbergesque, though, so am looking for a better solution.

UPDATE

For T.J. Crowder, here is the HTML (Razor/ASP.NET MVC style):

@foreach (var rpt in reports)
{
    @* convert id to lowercase and no spaces *@
    var morphedRptName = @rpt.report.Replace(" ", string.Empty).ToLower();
    <input class="ckbx leftmargin8" id="ckbx_@(morphedRptName)" type="checkbox" value="@rpt.report" />@rpt.report
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$(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
...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...