Javascript输入字段?

时间:2013-11-01 01:53:01

标签: javascript

任何场输入验证解决方案?如果有人选择了第一个选项/ value ="",那就错了。这是我的HTML:

<div class="fieldinput" id="disney">
                <label for="disney">Disney Character</label>
            <select name="disney">
                <option value="">Choose...</option>
                <option value="mickey">Mickey Mouse</option>
                <option value="mini">Mini Mouse</option>
            </select>
            </div>

我的javascript

function validate() {
        var errMsg = "";
    var result = true;


    if (disney == "") { 
    errMsg += "An option must be selected.\n"; 
    }

if (errMsg != "") {
        alert (errMsg);
        result = false;
    } 
    return result;
}
有人可以帮忙吗? 在此先感谢:)

2 个答案:

答案 0 :(得分:0)

使用:

var disney= document.getElementsByName('disney')[0].value;

答案 1 :(得分:0)

试试这个: HTML:

<div class="fieldinput" id="disney">
    <label for="disney">Disney Character</label>
    <select name="disney">
        <option value="">Choose...</option>
        <option value="mickey">Mickey Mouse</option>
        <option value="mini">Mini Mouse</option>
    </select>
</div>
<input type="button" value="submit" id="btnSub" />

JS:

function validate(disney) {
    var result = !!disney;
    if (!result) { 
        alert("An option must be selected.\n"); 
    }
    return result;
}

var btnSub = document.getElementById("btnSub");
btnSub.onclick = function(){
    var disney = document.getElementsByName("disney")[0];
    var disVal = disney.options[disney.selectedIndex].value;
    var ret = validate(disVal);
    //ret is validate result
}

为: http://jsfiddle.net/artwl/XMEwD/1/