Tim Long
Tim Long

Reputation: 397

jquery: Select items in a listbox and trigger change

I can't seem to be able to trigger a change on my listbox after I have changed the selected value in code. Change function works great if the listbox is actually clicked. I have searched the forums and none of the solutions seem to work for me. Example code is below. I have also set up a jsfiddle here. I want it to go into the change function when the code is run.

<form>
  <select class="selectOneListBox" id="CompanyId" multiple="multiple" name="CompanyId">        
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test</option>
  </select>
<form>
$(function () {
  id = 3
  if (id > 0) {
    alert(id)
    $('#CompanyId').val(id).change();
  }
}); 

$("#CompanyId").change(function () {
  alert("change");
});

Upvotes: 6

Views: 19043

Answers (1)

p e p
p e p

Reputation: 6674

You need to move your .change bind into the document ready block. I changed this in your jsfiddle, and it alerted 'change' when the code triggered it, as opposed to just when clicking. http://jsfiddle.net/65wHW/2/

$(function () {
    $("#ScriptId").change(function () {

       alert("change");
    });

    id = 8
    if (id > 0) {
       alert(id)
       $('#ScriptId').val(id).change();
    }
});

Upvotes: 5

Related Questions