在设置表单验证功能时遇到问题

时间:2014-11-28 17:31:41

标签: javascript html forms validation

<td> <label> Gender: </label> </td>
<td> <select> id="gender" name = "gender">
                        <option>Select a gender</option>
                        <option>Male</option>
                        <option>Female</option>
                     </select>
                </td>

这就是我正在尝试验证的表单,这是我的javascript,但我看不到让它工作:

function validateGender(){
                if("" == document.getElementsByID('gender')[0].selectedIndex){
                    alert("Please select a gender")
                    return;
}
            }

2 个答案:

答案 0 :(得分:0)

尝试:

    <script>
        function validateGender(){
            if( document.getElementById('gender').selectedIndex == 0 ){
                alert("Please select a gender");
            }
        }
    </script>

    <form>
        <table>
            <tr>
                <td> <label> Gender: </label> </td>
                <td> <select id="gender" name = "gender">
                    <option>Select a gender</option>
                    <option>Male</option>
                    <option>Female</option>
                </select>
                </td>
            </tr>
        </table>
        <input type="button" onclick="validateGender()" value="Submit">
    </form>

小提琴:http://jsfiddle.net/55v9mboa/1/

答案 1 :(得分:0)

&#13;
&#13;
function validateGender(){
                if(document.getElementById("gender").selectedIndex==0){
                    alert("Please select a gender");
                    return;
}

            }
&#13;
<select id="gender" name = "gender">
                        <option>Select a gender</option>
                        <option value="male">Male</option>
                        <option value="female">Female</option>
                     </select>
                     <button onclick="validateGender()">validate</button>
&#13;
&#13;
&#13;

检查一下。