Arul Sidthan
Arul Sidthan

Reputation: 176

How can i prevent duplicate entry in java script while appending data into #div

PFB java script code..

the thing is im getting alert for duplicate entry. how can avoid the repeated 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 output

Upvotes: 3

Views: 2520

Answers (3)

Arul Sidthan
Arul Sidthan

Reputation: 176

Solution for preventing duplicate values and undefined value in the 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>");

Upvotes: 1

Dwza
Dwza

Reputation: 6565

Solution one:

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

Solution two:

Check your existing options for containing values

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

this should do it as well and is a shorter code

also see Fiddle

Upvotes: 1

dashtinejad
dashtinejad

Reputation: 6253

Use an array to store the 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>

Upvotes: 1

Related Questions