[英]Set previously selected value in dropdown if return false
我有2個下拉菜單。 一個是最小尺寸,另一個是最大尺寸。 我正在檢查最小選擇框中的選定值是否大於最大選擇框的選定值,反之亦然。 它運作良好。
如果驗證返回false,我會卡在一個我想將前一個值設置為“selected”的地方。 它不允許我這樣做。
演示在這里 - https://jsfiddle.net/squidraj/2fnxw609/1/
JS代碼
$("select[name=size-min],select[name=size-max]").focus(function() {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {
var selname = $(this).attr('name');
var selval = $(this).val();
var e1 = document.getElementById("size-min");
var minval = e1.options[e1.selectedIndex].value;
var e2 = document.getElementById("size-max");
var maxval = e2.options[e2.selectedIndex].value;
alert(previous);
if (selname == "size-min" && parseInt(minval) > parseInt(maxval) && maxval != "") {
$('#size-min').val(previous);
alert("The minimum size needs to be smaller than maximum size.");
return false;
}
if (selname == "size-max" && parseInt(selval) < parseInt(minval)) {
$('#size-max').val(previous);
alert("The maximum size needs to be greater than minimum size.");
return false;
}
});
是不是我想要實現的目標。 任何幫助或建議都非常感謝。
不是一個真正的答案:但是證明你的邏輯是合理的(並且可能更多地利用jQuery功能)
function init() { var previous; $(".minmax").focus(function() { // Store the current value on focus, before it changes previous = this.value; }).change(function(e) { if (parseInt($("#size-max").val()) < parseInt($("#size-min").val())) { $(this).val(previous); console.log($(this).attr('id')=="size-min"?"The minimum size needs to be smaller than maximum size.":"The maximum size needs to be greater than minimum size."); } previous = this.value; // Chrome calls "change" every time the value changes. Firefox only calls it when the element loses focus. This change makes chromes behavior a little more intuitive }); } $(init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <form> <select class="minmax" id="size-min"> <option selected>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <select class="minmax" id="size-max"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option selected>5</option> </select> </form> </body>
似乎在Firefox上。如果輸入已經被聚焦,則不會觸發.focus()
- 例如,當你在同一個組合.focus()
上修改我們的選項時 - previous
不會改變,因為它已經被聚焦了。
您的代碼應該工作的時候.focus()
事件被替換.click()
因此,在選擇新選項之前,無論該特定組合框是否已經聚焦,前一個選項始終都會被保存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.