简体   繁体   English

验证是否使用jquery选择了多个项目

[英]Validate if more than one item was selected using jquery

This code allows the user to select one or more models of cars graphically on a web page. 此代码允许用户在网页上以图形方式选择一种或多种汽车模型。 I am in need to check if more than one was selected. 我需要检查是否选择了多个。 How can I get this to count the number of selected items and if it's great than one alert("something")?? 我如何获得此信息以计算所选项目的数量,以及是否比一个警报(“某物”)好呢? In short, I need to know if both Lexus and Inifiti were chosen in the example code here. 简而言之,我需要知道在示例代码中是否同时选择了雷克萨斯和Inifiti。 I really need the count so if it's greater than 1 selected. 我真的需要计数,所以如果它大于1则被选择。 Any help is great appreciated, not sure what I am doing wrong . 非常感谢您的帮助,不确定我做错了什么。

  <div class="options-item-wrapper clearfix">
    <?php
    $modelOptions = array(
        0 => array('title' => 'Lexus'),
        1 => array('title' => 'Infiniti')
    );

    foreach ($modelOptions as $modelOption) {
        $selected = '';
          $optionValue = '';

        if(in_array($modelOption['title'], $modelArray)) {
            $selected = 'selected';
            $optionValue = '<input class="vehicle-option"  
            type="hidden" name="model[]"       
            value="'.$modelOption['title'].'">';
        }

        echo '<div class="options-item '.$selected.'" data-vehicle="'.
        $modelOption['title'].'">
        <div>'.$modelOption['title'].'</div>
        '.$optionValue.'    </div>';
    }
    ?>
  </div>

I have tried this but no luck thus far : 我已经尝试过了,但是到目前为止还没有运气:

    var checkedNum = $('input[name="model[]"]:selected').length;
    alert(checkedNum);
    if (checkedNum > 1) {
        alert('Validating the form2');
        // User didn't check any checkboxes
    } else {
        die();
    }

Your code doesn't work because hidden input elements don't have a selected state. 您的代码不起作用,因为隐藏的输入元素没有处于选定状态。

If I understand your code correctly, you add the class 'selected' to your options items if they're selected. 如果我正确理解您的代码,则将“选择的”类添加到您的选择项(如果已选择)。 Wouldn't you just need to count the number of options items with the selected class? 您是否只需要计算所选类别的选项项目数?

var checkedNum = $('.options-item.selected').length;
alert(checkedNum);
if (checkedNum > 1) {
    alert('Validating the form2');
    // User didn't check any checkboxes
} else {
    die();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM