无法通过JQuery访问选择框

时间:2014-08-09 16:06:26

标签: javascript php jquery html ajax

我有一个div,它的内容会根据div上面的选择框的值而改变(我正在制作和ajax调用php页面来执行此操作并且没有问题)。页面内容发生变化后,div内会有另一个选择框(此选择框出现在第一个ajax响应之后)。我想做的是通过使用此选择框的更改事件进行另一个ajax调用,但我无法通过jquery访问此选择框。这可能是什么原因?这是我的实施:

HTML:

<div id="formTypeSelectionDiv">
    <label>Select the internship type you want to edit:</label></br></br>
    <select id="formTypeSelection">
        <option value="">--select--</option>
        <option value="IENG349">IENG 349 Grades</option>
        <option value="IENG449">IENG 449 Grades</option>
        <option value="IENG349Stage2">IENG 349 Stage 2 Form</option>
        <option value="IENG449Stage2">IENG 449 Stage 2 Form</option> 
    </select>
</div>
<div id="resultDiv">
//The selectbox will be here after first ajax response and it will be like that
    <select id='fieldOfBusinessEditSelectBox'>
        <option value=''>--select--</option>
        <option value='1'>Production</option>
        <option value='2'>Service</option>
    </select> 
</div>

JQuery:

$("#fieldOfBusinessEditSelectBox").change(function(){
    var value = $("select#fieldOfBusinessEditSelectBox option:selected").val();
    alert(value);
});

2 个答案:

答案 0 :(得分:2)

事件处理程序仅绑定到当前选定的元素;它们必须存在于您的代码进行事件绑定调用时的页面上。

委托事件的优势在于它们可以处理来自稍后添加到文档的后代元素的事件。

正在使用AJAX加载。

您需要使用Event Delegation。您必须使用委托事件方法来使用.on()

一般语法

$(document).on(event, selector, eventHandler);

根据您的代码

$(document).on('click', '#fieldOfBusinessEditSelectBox', function(){
    var value = $(this).val();
});

答案 1 :(得分:1)

更改此行:

var value = $("select#fieldOfBusinessEditSelectBox option:selected").val();

要:

var value = $("select#fieldOfBusinessEditSelectBox").val();

或者:

var value = $("select#fieldOfBusinessEditSelectBox option:selected").html();

Coz,.val()用于引用表单控件<select>

由于您使用之前不存在的AJAX获取<select>,因此将事件委托给其父级。

$("#resultDiv").on('change', '#fieldOfBusinessEditSelectBox', function(){
    var value = $(this).val();
});