简体   繁体   中英

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. I really need the count so if it's greater than 1 selected. 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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