Inchara Raveendra
Inchara Raveendra

Reputation: 1667

How to disallow adding of existing options to select?

How to not allow values that already exist in select options? (using jQuery)

$(document).on('click', '#add', function() {
  if ($('#new-option').val() != '') {
    var val = $('#new-option').val();
    $('#foo option:last').html(val);
    var opt = '<option>Other</option>';
    $('#foo').append(opt);
    $('#foo').val(val);
    $('#new-option').val('');
    console.log($("#foo option").each(function() {
      $(this).val();
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<select id="foo">
  <option>Notification</option>
  <option>Other</option>
</select>

<input type="text" id="new-option" required>
<button type="button" id="add">Add Option</button>

Upvotes: 0

Views: 75

Answers (6)

This will work:

$(document).on('click', '#add', function(){
var val = $('#new-option').val();
if(val != ''){
    var arr = $('#foo').children('option').map(function(i,el){return $(el).text()});
    if($.makeArray(arr).indexOf(val) != -1){
        alert("this option exists...")
    }else{
        $('#foo').append('<option>'+val+'</option>');
        $('#new-option').val('');
    }
}
});

Upvotes: 1

Mayur Patel
Mayur Patel

Reputation: 1751

You can loop through each select option and check if it exists or not. Use jQuery. Use jQuery .trim() to remove space in comparison.

$(document).on('click', '#add', function(){
    if($('#new-option').val() != '')
    {
        var val = $('#new-option').val();
        var flag_add = true;
    	  $("#foo").find("option").each(function() {
            console.log($(this).val());
            if($(this).val().trim()==val.trim()){
                flag_add = false;
                alert("Option already added...")
                return;
            }    
        });
        if(flag_add)
        {
            $('#foo option:last').html(val);
            var opt = '<option>Other</option>';
            $('#foo').append(opt);
            $('#foo').val(val);
            $('#new-option').val('');
        }
    }    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<select id="foo">
  <option>Notification</option>
  <option>Other</option>
</select>

<input type="text" id="new-option" required>
<button type="button" id="add">Add Option</button>

Upvotes: 2

Scott Marcus
Scott Marcus

Reputation: 65853

Loop over the current values and only append if not already present. See inline comments for details:

$(document).on('click', '#add', function() {

  var found = false;  // Track if new value was found in list
  
  // Loop through list options
  $("#foo > option").each(function(idx, el){
    // Compare (case-insensitive) new value against list values
    if($("#new-option").val().toLowerCase() === el.textContent.toLowerCase()){
      found = true;  // Set flag if value exists
    }
  });

  // If not found
  if(!found){
    // Create new option and append to list
    var opt = '<option>' + $("#new-option").val()  + '</option>';
    $('#foo').append(opt);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<select id="foo">
  <option>Notification</option>
  <option>Other</option>
</select>

<input type="text" id="new-option" required>
<button type="button" id="add">Add Option</button>

Upvotes: 1

Niraj patel
Niraj patel

Reputation: 525

Solved your issue please replace your script by this i have code

<script> 
$(document).ready(function() { 
    $(document).on('click', '#add', function() {
      if ($('#new-option').val() != '') {
        var val = $('#new-option').val();
        if($("#foo option[value='"+val+"']").length > 0){
         alert('already present');
        }else{
          var opt = '<option value="'+val+'">'+val+'</option>';
          $('#foo').append(opt);
        }
        $('#new-option').val(''); 
      }

    });
}); 

</script>

Upvotes: 1

Riaz Laskar
Riaz Laskar

Reputation: 1322

This should do it : Two more things need to take care: 1. more then one whitespace in text field .trim() should fix it. 2. checking case as Other and other will be treated as different.

$(document).on('click', '#add', function(){
 var option_to_add = $("#new-option").val();
 var options = [];
 $("#foo option").each(function(){
      options.push($(this).text())
 });

 if(option_to_add != '')
 {

   if($.inArray(option_to_add,options) === -1)
   {
      $("#foo").append("<option>"+option_to_add+"</option>");
   }
   else
   {
      alert("Option already exists");
   }
 }
 else
 {
  alert("Empty value");
 }

});

Upvotes: 1

ADreNaLiNe-DJ
ADreNaLiNe-DJ

Reputation: 4919

Using the lodash library, you can use the some function which can "find" if there's at least 1 item, in the given array, matches the condition (here the equality between the text of each option and the new option).

$(document).on("click", "#add", function() {
  var newoption = $("#new-option").val();
  var options = $("#foo option");
  if (newoption != "") {
    if(!_.some(options, function(opt) { return $(opt).text() == newoption; })) {
      $("#foo").append("<option>" + newoption + "</option>");
      console.log(newoption + " added");
    } else {
      console.log(newoption + " not added");
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<select id="foo">
  <option>Notification</option>
  <option>Other</option>
</select>

<input type="text" id="new-option" required>
<button type="button" id="add">Add Option</button>

Upvotes: 0

Related Questions