Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
});
like image 278
Tim Long Avatar asked Oct 04 '22 21:10

Tim Long


1 Answers

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();
    }
});
like image 54
p e p Avatar answered Oct 06 '22 12:10

p e p