0

I have a drop down list in an MVC application. When an item in the drop down list is selected (including the same one), I want to trigger a function. However, the first item in the list can't trigger the function and it should be disabled. I have some code below which works initially but after clicking a valid option and then clicking --Select-- again, it still fires the code. How do I fix this?

MVC Control

@Html.DropDownList("ddlCountries", (IEnumerable<SelectListItem>)ViewBag.Countries, "--Select--", new { @class = "form-control" })

jQuery to trigger the DDL click event

$('#ddlCountries option:not(:first)').click(function () {
            runCode()
});

jQuery to disable the first option

jQuery('#ddlCountries option:contains("--Select--")').attr('disabled', 'disabled');
cooper
  • 417
  • 1
  • 10
  • 20
  • When you select for the first time your option and fire the event, do you not want it to fire again if the user clicks the select again? – Lixus May 09 '17 at 14:23
  • 1
    personally instead of doing something fancy I would just put a check in the function. if ($('ddlCountries').val() == "") return; something like that – Matt Bodily May 09 '17 at 14:31
  • I never want select to fire anything. Ideally clicking it would do nothing (disabled). But I want any other item in the DLL when selected to always fire something. – cooper May 09 '17 at 14:39
  • I don't want to check the value because items get dynamically added so I think checking the value each time wouldn't be ideal – cooper May 09 '17 at 14:40

2 Answers2

0

Get the index of the selected option and check to see if it's greater than 0 on event fire. Indexes are 0 based.

$('#ddlcountries').on('change', function() {
  var index = $(this).find('option:selected').index();
  if (index > 0) {
    alert('yay');
    runCode();
  } else {
    alert('nay');
    return;
  }
})
Rob Scott
  • 7,921
  • 5
  • 38
  • 63
0

I deleted the code to disable the first option because I couldn't get it to stay disabled after the first change. I modified the jQuery to trigger the event to:

jQuery('#ddlCountries').find('option:gt(0)').click(function () {
    runCode()
});

Then I added styling to the --Select-- box to make it gray. You can still click on it but it won't do anything. Not exactly what I was trying to do but close enough

cooper
  • 417
  • 1
  • 10
  • 20
  • Use `on` event instead. `$('#ddlCountries').on('click','option:gt(0)', function() { .. })` http://stackoverflow.com/questions/10082031/why-use-jquery-on-instead-of-click – Rob Scott May 09 '17 at 21:30