检查字段值是否已随jquery更改

时间:2015-06-26 11:06:00

标签: javascript jquery html forms

我想要彻底检查值是否发生变化..所以如果用户在输入表单中选择一个新值,我想运行一些js代码..

<div class="select2-container country_to_state country_select" id="s2id_billing_country" style="width: 100%;">
    <a href="javascript:void(0)" class="select2-choice" tabindex="-1">
        <span class="select2-chosen" id="select2-chosen-1">Schweiz</span>
        <abbr class="select2-search-choice-close" />
        <span class="select2-arrow" role="presentation">
    <b role="presentation"/>
    </span>
    </a>
    <label for="s2id_autogen1" class="select2-offscreen">Land *</label>
    <input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-1" id="s2id_autogen1" />
</div>
<select name="billing_country" id="billing_country" class="country_to_state country_select " tabindex="-1" title="Land *" style="display: none;">
    <option value="">Land auswählen…</option>
    <option value="DE" selected="selected">Deutschland</option>
    <option value="CH">Schweiz</option>
    <option value="AT">Österreich</option>
</select>

到目前为止我已尝试过这种方法(不起作用)

$('#select2-chosen-1').change(function() {
    alert("change");
});

2 个答案:

答案 0 :(得分:1)

首先,您不应该在页面上拥有2个具有相同ID的元素。而是使用类

<span class="select2-chosen">Value 1</span>
<span class="select2-chosen">Value 2</span>

$('input').on('change', '.select2-chosen', (function() 
{
     alert("change");
 });

这里我们必须为页面实例化后由select2动态生成的输入实现委托事件监听器。然后我们会听取change事件和alert

或者,为您的<input class="select2-focusser select2-offscreen"<select name="billing_country"..提供一类someClass并听取更改

$('.someClass').change(function() 
{
    alert("change");
});

答案 1 :(得分:0)

尝试在其中指定所有输入:

$('.select2-chosen').find(':input').change(function() 
{
 alert("change");
 });

希望这会有所帮助

相关问题