如何限制 HTML

发布于 2024-08-17 16:37:25 字数 109 浏览 5 评论 0原文

我正在制作的表单中使用

I'm using a <select> element in a form I'm making that allows multiple selections, but I want to limit the maximum amount of selections to 10. Is this possible using JavaScript or jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

人生百味 2024-08-24 16:37:25

这是一些完整的代码供您使用:

$(document).ready(function() {

  var last_valid_selection = null;

  $('#testbox').change(function(event) {
    if ($(this).val().length > 5) {
      alert('You can only choose 5!');
      $(this).val(last_valid_selection);
    } else {
      last_valid_selection = $(this).val();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select multiple id="testbox" size="10">
  <option value='1'>First Option</option>
  <option value='2'>Second Option</option>
  <option value='3'>Third Option</option>
  <option value='4'>Fourth Option</option>
  <option value='5'>Fifth Option</option>
  <option value='6'>Sixth Option</option>
  <option value='7'>Seventh Option</option>
  <option value='8'>Eighth Option</option>
  <option value='9'>Ninth Option</option>
  <option value='10'>Tenth Option</option>
</select>

Here is some full code for you to use:

$(document).ready(function() {

  var last_valid_selection = null;

  $('#testbox').change(function(event) {
    if ($(this).val().length > 5) {
      alert('You can only choose 5!');
      $(this).val(last_valid_selection);
    } else {
      last_valid_selection = $(this).val();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select multiple id="testbox" size="10">
  <option value='1'>First Option</option>
  <option value='2'>Second Option</option>
  <option value='3'>Third Option</option>
  <option value='4'>Fourth Option</option>
  <option value='5'>Fifth Option</option>
  <option value='6'>Sixth Option</option>
  <option value='7'>Seventh Option</option>
  <option value='8'>Eighth Option</option>
  <option value='9'>Ninth Option</option>
  <option value='10'>Tenth Option</option>
</select>

梦途 2024-08-24 16:37:25

这会将用户限制为 3 个选项:

$("select").on("click", "option", function () {
    if ( 3 <= $(this).siblings(":selected").length ) {
        $(this).removeAttr("selected");
    }
});​​​​​​​​​​

小提琴:http://jsfiddle.net/2GrYk/

This would limit the user to 3 options:

$("select").on("click", "option", function () {
    if ( 3 <= $(this).siblings(":selected").length ) {
        $(this).removeAttr("selected");
    }
});​​​​​​​​​​

Fiddle: http://jsfiddle.net/2GrYk/

灼痛 2024-08-24 16:37:25

这个答案适用于这些情况:

  • 正常单击
  • 仅 mousedown (鼠标在 mouseup 之前移出)
  • 键盘
  • 如果有具有相同值的不同选项

代码:

$('#mySelect').on('change', function() {
    if (this.selectedOptions.length < 4) {
        $(this).find(':selected').addClass('selected');
        $(this).find(':not(:selected)').removeClass('selected');
    }else
        $(this)
        .find(':selected:not(.selected)')
        .prop('selected', false);
});

演示

或者,对于不支持 selectedOptions 的旧浏览器,

$('#mySelect').on('change', function() {
    var $sel = $(this).find(':selected');
    if ($sel.length < 4) {
        $sel.addClass('selected');
        $(this).find(':not(:selected)').removeClass('selected');
    }else
        $(this)
        .find(':selected:not(.selected)')
        .prop('selected', false);
});

演示

This answer works in those cases:

  • Normal click
  • Only mousedown (mouse is moved outside before mouseup)
  • Keyboard
  • If there are different options with the same value

Code:

$('#mySelect').on('change', function() {
    if (this.selectedOptions.length < 4) {
        $(this).find(':selected').addClass('selected');
        $(this).find(':not(:selected)').removeClass('selected');
    }else
        $(this)
        .find(':selected:not(.selected)')
        .prop('selected', false);
});

Demo

Or, for old browsers that don't support selectedOptions,

$('#mySelect').on('change', function() {
    var $sel = $(this).find(':selected');
    if ($sel.length < 4) {
        $sel.addClass('selected');
        $(this).find(':not(:selected)').removeClass('selected');
    }else
        $(this)
        .find(':selected:not(.selected)')
        .prop('selected', false);
});

Demo

ㄖ落Θ余辉 2024-08-24 16:37:25

使用 jQuery,您可以将一个函数附加到更改事件,并且由于它是多重选择,因此 val() 将是一个数组。您始终可以检查数组的长度,如果其大小是预定义的,则执行某些操作。以下代码演示了如何知道选择了多少个项目。

  $("#select").change(function(){
        alert($(this).val().length);
  });   

Using jQuery you can attach a function to the change event and since it is a multiple select the val() will be an array. You can always check the length of the array and do something if its a predefined size. The following code demonstrates how you will know how many items are selected.

  $("#select").change(function(){
        alert($(this).val().length);
  });   
纸伞微斜 2024-08-24 16:37:25

想通了!这是生成的代码:

$(document).ready(function(){

var last_valid_selection = null;
var selected = "";

$("#recipient_userid").change(function(event){

    if ($(this).val().length > 10) {

        alert('You can only choose 10!');
        $(this).val(last_valid_selection);

    } else {

        last_valid_selection = $("#recipient_userid").val();

        $("#recipient_userid option:selected").each(function () {
            selected += "<li>" + $(this).text() + "</li>";
        });

        $("#currentlySelected").html(selected);
        selected = "";
    }

}).change();
});

感谢大家的帮助!

figured it out! here's the resulting code:

$(document).ready(function(){

var last_valid_selection = null;
var selected = "";

$("#recipient_userid").change(function(event){

    if ($(this).val().length > 10) {

        alert('You can only choose 10!');
        $(this).val(last_valid_selection);

    } else {

        last_valid_selection = $("#recipient_userid").val();

        $("#recipient_userid option:selected").each(function () {
            selected += "<li>" + $(this).text() + "</li>";
        });

        $("#currentlySelected").html(selected);
        selected = "";
    }

}).change();
});

Thanks for all your help guys!

埖埖迣鎅 2024-08-24 16:37:25

我基本上合并了几个提供的答案,以制作特定于特定 ID 的内容:

$("#mySelect").on("click", "option", function(){
    var max = 3;
    if ( max <= $(this).siblings(":selected").length ) {
        alert("Only " + max + " selections allowed.");
        $(this).removeAttr("selected");
    }
});

Rob

I basically merged a couple of the provided answers to make something specific to a particular ID:

$("#mySelect").on("click", "option", function(){
    var max = 3;
    if ( max <= $(this).siblings(":selected").length ) {
        alert("Only " + max + " selections allowed.");
        $(this).removeAttr("selected");
    }
});

Rob

尾戒 2024-08-24 16:37:25

你可以使用 jQuery

  $("select").change(function () {
      if($("select option:selected").length > 3) {
          //your code here
      }
  });

You can use jQuery

  $("select").change(function () {
      if($("select option:selected").length > 3) {
          //your code here
      }
  });
凉城 2024-08-24 16:37:25

这是一个纯粹的 JavaScript 示例,基于 jilu 的示例。

const selectEls = document.querySelectorAll('select[multiple]');

selectEls.forEach((selectEl) => {
    selectEl.addEventListener('change', (e) => {

        const currentEl = e.currentTarget;

        let is = 0;
        for (let i = 0; i < currentEl.length; i++) {
            if (currentEl.options[i].selected) {
                is++;
            }
            if (is > 3) { // if you want more than 3 selected options, change the number here
                currentEl.options[i].selected = false;
            }
        }

    })
});

Here a pure vanilla JavaScript example, based on jilu's example.

const selectEls = document.querySelectorAll('select[multiple]');

selectEls.forEach((selectEl) => {
    selectEl.addEventListener('change', (e) => {

        const currentEl = e.currentTarget;

        let is = 0;
        for (let i = 0; i < currentEl.length; i++) {
            if (currentEl.options[i].selected) {
                is++;
            }
            if (is > 3) { // if you want more than 3 selected options, change the number here
                currentEl.options[i].selected = false;
            }
        }

    })
});
凶凌 2024-08-24 16:37:25

瞧!
不需要 Jquery。

    var is = 0;
    for (var i = 0; i < selectCountryCode.length; i++) {
        if (selectCountryCode.options[i].selected) {
            is++;
        }
        if (is > 3) {
            selectCountryCode.options[i].selected = false;              
        }
    }

吉鲁山

Voila!
No Jquery necessary.

    var is = 0;
    for (var i = 0; i < selectCountryCode.length; i++) {
        if (selectCountryCode.options[i].selected) {
            is++;
        }
        if (is > 3) {
            selectCountryCode.options[i].selected = false;              
        }
    }

Jilusan

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文