0

当SelectBox Val == 0时,我需要删除现有的HTML。这是我的HTML,

<div class="info-cont">
    <ul class="map-list">
        <li>
            <span class="left">
                <label>Name 1</label>
            </span>
            <span class="right">
                <select class="combo">
                    <option selected="selected" value="0"></option>
                    <option value="1">F name</option>
                    <option value="2">M name</option>
                    <option value="3">L name</option>
                </select>
            </span>
        </li>
    </ul>
</div>

注意:我的页面中大约有 10 个选择框,如上,

上面的jquery是,

$(document).ready(function () {
    $('#save').click(function () {
        var comboLength = $('.combo').length;
        var selectedLength = $('.combo option:selected[value!=0]').length;
        if (comboLength == selectedLength) {
            alert('Thanks all the fields are selected');
            return false;
        }
        if ($('.combo option:selected[value==0]')) {
            $("div.info-cont ul.map-list li span.right").append("<br>Please select an appropriate value").addClass('validerror');
        } else {
            $("div.info-cont ul.map-list li span.right").html("");
            $("div.info-cont ul.map-list li span.right").removeClass('validerror');
        }
        return false;
    })
});

在 else 条件下我需要做什么?(我的 else 部分没有功能)。此外,当我第二次单击提交按钮时,我不应该附加我在第一次单击时已经收到的 html。有什么帮助吗?谢谢...

4

1 回答 1

0

更改if

if($('.combo option:selected').val() === '0'){

所有问题都可以通过

$(document).ready(function(){
    $('#save').click(function(){
        var combo = $('.combo'), // get all combo elements
            selected = $('.combo').filter(function(){
                return $(this).find('option[value!="0"]:selected').length;
            }), // get all valid combo elements
           unselected = combo.not(selected); // get all non-valid combo elements

        // clear previous error messages
        combo
            .closest('.right') // find containing .right element
            .removeClass('validerror') // remove error class
            .find('.errormessage') // find error message
            .remove(); // remove error message

        // chech if all combos are valid
        if (combo.length === selected.length) {
            alert('Thanks all the fields are selected');
            return false;
        }

        // highlight non-valid elements
        unselected
            .closest('.right')
            .addClass('validerror')
            .append('<div class="errormessage">Please select an appropriate value</div>');

        return false;
    });
});

演示在http://jsfiddle.net/gaby/Y3RrH/

于 2012-04-19T10:39:10.073 回答