从iPhone的多选框中取消选择最后一个选项

Unselect last option from multiselect box in iphone

本文关键字:取消 选择 最后一个 选项 iPhone      更新时间:2023-09-26

我正在使用以下jquery代码来限制多选框中的选择。它在任何安卓设备中都能正常工作,但在iPhone中出现问题。

在 iphone 中,会显示警报消息,但最后一个选定的元素不会按预期取消选择。它应该显示选定的 3 个项目,但它显示在 iPhone 中出现警报消息后选择的 4 个项目。任何提示表示赞赏。提前谢谢。

<select id="mob-industry">
  <option value="1">Web Development</option>
  <option value="2">Architecture</option>
  <option value="3">Software Development</option>
  <option value="4">Hardware</option>
</select>

var last_valid_selection = null;
$('#mob-industry').change(function(event) {
    if ($(this).val().length > 3) {
        sweetAlert("","Only 3 Allowed","info");
          $(this).val(last_valid_selection);
    } else {
          last_valid_selection = $(this).val();
    }
 });

我猜你是从这样的地方得到你的方法的:你如何限制在html选择框中选择的选项?

但我认为这是您真正想要/应该使用的:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<select id="mob-industry" multiple>
    <option value="1">Web Development</option>
    <option value="2">Architecture</option>
    <option value="3">Software Development</option>
    <option value="4">Hardware</option>
</select>
$('#mob-industry').bind("vmousedown", function(event) {
    var num_selected = $(this).find(":selected").length;
    if (num_selected == 3) {
        var last_selected_value = $(event.target).val();
        var select_array = $(this).val();
        if ($.inArray(last_selected_value, select_array) == -1) {
            alert("YOU SHALL NOT PASS!!!");
            event.preventDefault();
            return false;
        }
    }
});

Fiddle(使用mousedown()而不是.bind("vmousedown")与计算机兼容):https://jsfiddle.net/kpm0yLyt/1/

JsDoIt(移动模拟,尽管在选择选项时显示选项时存在一些古怪的错误。忽略它。): http://jsdo.it/Macainian/GKxn

哦,顺便说一句,另一种方法(使用 click() 而不是 .bind("vclick") 以与计算机兼容):https://jsfiddle.net/m49wr4t1/5/