Craig
Craig

Reputation: 1225

Determine if data is already in select list

I have a select defined as -

<div class="form-group">
  <div class="col-md-10">
    <select name="selected-attendees" id="selected-attendees" class="form-control" multiple size="5">
      @foreach (Customer attendee in Model.AttendeeList)
      {
           var attendeeName = String.Format("{0}, {1}", attendee.FullName, attendee.Email);
           <option class="selectable-option" value="@attendee.Id">@attendeeName</option>
      }
    </select>
  </div>
</div>

When the user clicks an add button, this is the action -

$('#attendees-btn-add').click(function () {
  if ($('#selectedAttendee').val() == '') {
    alert("Select a customer to be added to the attendee list.");
   } else {
     $('#selected-attendees').append($('<option>', {
        class: 'selectable-option',
        value: $('#attendeeId').val(),
        text: $('#selectedAttendee').val()
      }));
      $('#selectedAttendee').val("");
      $('#attendeeId').val("");
     }
  });

I need to determine if the user has already been added to the select and display a message.

Upvotes: 1

Views: 30

Answers (2)

Giannis Grivas
Giannis Grivas

Reputation: 3412

Try this condition to .click function:

var exists = $("#selected-attendees").find('option[value=' + $('#attendeeId').val() + ']').length >0;

    if(exists)
    {
    //do if exists
    }
    else
    {
    //do because not exists
    }

demo here: http://jsfiddle.net/csdtesting/q9L59gmc/

Upvotes: 0

robobot3000
robobot3000

Reputation: 589

You can query for <option> with a specific value, and show the message if there are any results:

if ($('#selected-attendees option[value="' + $('#attendeeId').val() + '"]').length) {
    //display message about duplicate
}

Upvotes: 1

Related Questions