检测JSP中的下拉更改

Detect dropdown change in JSP?

本文关键字:JSP 检测      更新时间:2023-09-26

在jsp中,是否有任何属性可以提供下拉列表中的值发生更改的信息?

举个例子:

我有下拉列表国家-在页面加载中,下拉列表中有"美国",我将更改为"英国",然后再次更改为"美国"。在这种情况下,我没有做任何更改,所以我没有什么要保存的,但如果我点击保存按钮,我的页面将被提交。是否有任何方法可以避免此页面提交。?

是的。但是你必须使用javascript,而不是jsp。示例代码

html:

<form class="checked">
    <input type="hidden" id="countrySelectInitial" value="UK" /> <!-- we need this element to store initial value --> 
    <select name="country" class="checkedInput" id="countrySelect">
        <option value="US">US</option>
        <option value="UK" selected>UK</option>
    </select>
    <input type="submit" class="submitButton" disabled />
</form>

js:

$(".checkedInput").change(function() {
    var newValue = $(this).val();
    var idValue = $(this).attr('id'); // we need id to retrieve initial value. Initial value is stored in element with id <id>Initial
    var oldValue = $("#" + idValue + "Initial").val();
    if(newValue === oldValue) {
            // if value don't changed - disable button. user have no possibility to submit form
        $(this).parents("form.checked").find(".submitButton").attr("disabled", true);
    } else {
            // if value changed - remove "disabled" attribute. User can click button and submit form
        $(this).parents("form".checked).find(".submitButton").removeAttr("disabled");
    }
});