简体   繁体   中英

Optimize the repetitive code for adding new option to select jquery

Here is my fiddle : DEMO

I have repeated codes for adding new options to rule and event category select. How do I optimize the same to eliminate the repeated code?

//Adding new category for event
$(document).on('click', '.addevent', function() {

  var found = false; // Track if new value was found in list        
  // Loop through list options
  $("#categoryevent > option").each(function(idx, el) {
    // Compare (case-insensitive) new value against list values
    if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
      alert("Category already exists!")
      found = true; // Set flag if value exists
      $('#new-option-event').val('');
    }
  });
  // If not found
  if ($('#new-option-event').val().trim() != '') {
    if (!found) {
      // Create new option and append to list
      var val = $("#new-option-event").val().trim();
      var opt = '<option>' + val + '</option>';
      $('#categoryevent').append(opt);
      $('#categoryevent').val(val);
      $('#new-option-event').val('');
      $("#categoryevent").click();
    }
  }

});

Here you go with some optimised code https://jsfiddle.net/3tLx884e/2/

 //Adding new category for rule $(document).on('click', '.addrule', function() { var found = false; // Track if new value was found in list // Loop through list options var text = $("#new-option-rule").val().trim(); $("#categoryrule > option").each(function(idx, el) { // Compare (case-insensitive) new value against list values if (text.toLowerCase() === el.textContent.toLowerCase()) { alert("Category already exists!"); found = true; // Set flag if value exists } if((idx + 1) === $('#categoryrule > option').length){ if ( !found && (text != '')) { // Create new option and append to list $('#categoryrule') .append('<option>' + text + '</option>') .val(text); } $('#new-option-rule').val(''); } }); // If not found }); //Adding new category for event $(document).on('click', '.addevent', function() { var found = false; // Track if new value was found in list // Loop through list options $("#categoryevent > option").each(function(idx, el) { // Compare (case-insensitive) new value against list values if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) { alert("Category already exists!") found = true; // Set flag if value exists $('#new-option-event').val(''); } }); // If not found if ($('#new-option-event').val().trim() != '') { if (!found) { // Create new option and append to list var val = $("#new-option-event").val().trim(); var opt = '<option>' + val + '</option>'; $('#categoryevent').append(opt); $('#categoryevent').val(val); $('#new-option-event').val(''); $("#categoryevent").click(); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label class="control-label col-sm-2" for="category">Rule Category:</label> <div class="col-sm-8"> <select class="form-control" id="categoryrule" name="category"> <option>Humidity</option> <option>Temperature</option> <option>Rule Type3</option> <option>Rule Type4</option> <option>Rule Miscellaneous</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"></label> <div class="col-sm-8"> <div class="col-sm-8" style="padding-left:0px;"> <input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule"> </div> <div class="col-sm-2" style="padding-left:0px;"> <button class="btn btn-md addrule">Add Category</button> </div> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="category">Event Category:</label> <div class="col-sm-8"> <select class="form-control" id="categoryevent" name="category"> <option>SMS</option> <option>Email</option> <option>Invoke API</option> <option>Event Type4</option> <option>Event Miscellaneous</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"></label> <div class="col-sm-8"> <div class="col-sm-8" style="padding-left:0px;"> <input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent"> </div> <div class="col-sm-2" style="padding-left:0px;"> <button class="btn btn-md addevent">Add Category</button> </div> </div> </div> <div class="actionConfig"> </div> 

Hope this will help you.

Here you go - a common function helps a lot:

 //Adding new category for rule $(document).on('click', '.addrule', function() { AddElement("categoryrule", "new-option-rule"); }); //Adding new category for event $(document).on('click', '.addevent', function() { AddElement("categoryevent", "new-option-event"); }); function AddElement(selectId, newElementId){ var found = false; // Track if new value was found in list // Loop through list options $( "#" + selectId + " > option").each(function(idx, el) { // Compare (case-insensitive) new value against list values if ($("#" + newElementId).val().trim().toLowerCase() === el.textContent.toLowerCase()) { alert("Category already exists!") found = true; // Set flag if value exists $('#' + newElementId).val(''); } }); // If not found if ($('#' + newElementId).val().trim() != '') { if (!found) { // Create new option and append to list var val = $("#" + newElementId).val().trim(); var opt = '<option>' + val + '</option>'; $('#' + selectId).append(opt); $('#' + selectId).val(val); $('#' + newElementId).val(''); $("#" + selectId).click(); } } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label class="control-label col-sm-2" for="category">Rule Category:</label> <div class="col-sm-8"> <select class="form-control" id="categoryrule" name="category"> <option>Humidity</option> <option>Temperature</option> <option>Rule Type3</option> <option>Rule Type4</option> <option>Rule Miscellaneous</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"></label> <div class="col-sm-8"> <div class="col-sm-8" style="padding-left:0px;"> <input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule"> </div> <div class="col-sm-2" style="padding-left:0px;"> <button class="btn btn-md addrule">Add Category</button> </div> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="category">Event Category:</label> <div class="col-sm-8"> <select class="form-control" id="categoryevent" name="category"> <option>SMS</option> <option>Email</option> <option>Invoke API</option> <option>Event Type4</option> <option>Event Miscellaneous</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"></label> <div class="col-sm-8"> <div class="col-sm-8" style="padding-left:0px;"> <input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent"> </div> <div class="col-sm-2" style="padding-left:0px;"> <button class="btn btn-md addevent">Add Category</button> </div> </div> </div> <div class="actionConfig"> </div> 

This is my take on the problem, following jquery's slogan: "write less, do more" ...

I reduced the code further by working on local context. I. e. I only need to define one click event for everything. The click function itself figures out, what to change. It does not need any id s to do its job:

 //Adding new category for rule and event $('.form-group').on('click', 'button', addElement); function addElement(){ var $grp=$(this).closest('.form-group'), ival=$('input:text',$grp).val().trim(), // new input value $sel=$('select',$grp.prev()), // select element opts=$.makeArray($('option',$sel).map(function(i,op){ return op.textContent.toLowerCase(); })); if ($.inArray(ival.toLowerCase(),opts)===-1){ // check existing option values $sel.append('<option value="'+ival+'" selected>'+ival+'</option>'); } else {alert(ival+' exists already in '+$sel[0].id);} } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label class="control-label col-sm-2" for="category">Rule Category:</label> <div class="col-sm-8"> <select class="form-control" id="categoryrule" name="category"> <option>Humidity</option> <option>Temperature</option> <option>Rule Type3</option> <option>Rule Type4</option> <option>Rule Miscellaneous</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"></label> <div class="col-sm-8"> <div class="col-sm-8" style="padding-left:0px;"> <input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule"> </div> <div class="col-sm-2" style="padding-left:0px;"> <button class="btn btn-md addrule">Add Category</button> </div> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="category">Event Category:</label> <div class="col-sm-8"> <select class="form-control" id="categoryevent" name="category"> <option>SMS</option> <option>Email</option> <option>Invoke API</option> <option>Event Type4</option> <option>Event Miscellaneous</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"></label> <div class="col-sm-8"> <div class="col-sm-8" style="padding-left:0px;"> <input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent"> </div> <div class="col-sm-2" style="padding-left:0px;"> <button class="btn btn-md addevent">Add Category</button> </div> </div> </div> <div class="actionConfig"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM