How to prevent duplicate entries in java script when adding data to #div

PFB java script code ..

the thing is getting a duplicate record alert. how to avoid duplicate data?

Var   activityconunt =0;     
  if (activityconunt !== data.iRoundId) {
        alert("duplicate");
        $("#selectRound_Type").append("<option name='round' id=" + data.iRoundId + ">" + data.strRoundName + "</option>");             
        }

      

my output my conclusion

+3


source to share


3 answers


Decision:

Take your data and create a clean array earlier. Using http://api.jquery.com/jquery.inarray/

Solution two:

Check existing parameters for storing values



if($("option:contains('" + data.strRoundName + "')").length == 0)
    $("#selectRound_Type").append("<option name='round' id=" + data.iRoundId + ">" + data.strRoundName + "</option>");

      

this should do this too and this is shorter code

also see the fiddle

+1


source


Use an array to store data and check the new value with it:



$(function () {
  var items = [];
  var $select = $('select');
  var $input = $('input');
  var $button = $('button');

  // fetch current data
  $select.find('option').each(function () {
    items.push($(this).text());
  });

  $button.on('click', function () {
    var value = $input.val();
    var exists = ($.inArray(value, items) != -1);

    if (! exists) {
      items.push(value);
      $('<option></option').text(value).prependTo($select);
    }
  });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<button>Add</button>
<br />
<select style="width: 300px;">    
    <option>Hello</option>
</select>
      

Run codeHide result


+1


source


Solution to avoid duplicate values ​​and undefined values ​​in a list

  if ($("option:contains('" + data.strRoundName + "')").length == 0 
   && data.strRoundName != null 
   && typeof data.strRoundName != "undefined")
    $("#selectRound_Type").append("<option name='round' id=" 
         + data.iRoundId + ">" 
         + data.strRoundName + "</option>");

      

+1


source







All Articles