Home > Enterprise >  Setting Multiple Label Values -Looking For a Better Way
Setting Multiple Label Values -Looking For a Better Way

Time:05-23

I'm using this code to set some asp.net label values. They get updated every time a label value changes. There are 25 labels and this code is very repetitive and seems pretty inefficient to me. Is there a way to loop over all 25 labels and set the Q#_Score_Possible and Q#_Score variables for each either in jQuery or standard javascript?

 let Q1_Score_Possible;
 let Q1_Score;

 Q1_Score_Possible = $('#MainContent_grdScoring_lblPoints_Possible_0').val();
 $('#MainContent_grdScoring_hiddenPoints_Possible_0').val(Q1_Score_Possible); //hidden field for database scoring

 Q1_Score = $('#MainContent_grdScoring_lblScore_0').val();
 $('#MainContent_grdScoring_hiddenScore_0').val(Q1_Score); //hidden field for database scoring

 let Q2_Score_Possible;
 let Q2_Score;

 Q2_Score_Possible = $('#MainContent_grdScoring_lblPoints_Possible_1').val();
 $('#MainContent_grdScoring_hiddenPoints_Possible_1').val(Q2_Score_Possible); //hidden field for database scoring

 Q2_Score = $('#MainContent_grdScoring_lblScore_1').val();
 $('#MainContent_grdScoring_hiddenScore_1').val(Q2_Score); //hidden field for database scoring

 let Q3_Score_Possible;
 let Q3_Score;

 Q3_Score_Possible = $('#MainContent_grdScoring_lblPoints_Possible_2').val();
 $('#MainContent_grdScoring_hiddenPoints_Possible_2').val(Q3_Score_Possible); //hidden field for database scoring

 Q3_Score = $('#MainContent_grdScoring_lblScore_2').val();
 $('#MainContent_grdScoring_hiddenScore_2').val(Q3_Score); //hidden field for database scoring

CodePudding user response:

Consider the following.

$("input[id^='MainContent_grdScoring_lblPoints_Possible_']").each(function(i, el){
  $("#MainContent_grdScoring_hiddenPoints_Possible_"   i).val($(el).val())
});

This loops over each element in the selector. See More: https://api.jquery.com/each/

Using the Index, we can target the corresponding hidden element.

  • Related