我有一个名为name的文本区域的表单,我似乎无法验证此字段,即使所有下拉列表都是导航,我尝试了很多不同的组合,但仍然无法正常工作,我错过了什么?
<script type="text/javascript">
function validate_form() {
if ( document.form.title.selectedIndex == 0 )
{
alert ( "Please Select Title." );
return false;
}
if ( document.form.time.selectedIndex == 0 )
{
alert ( "Please Select Time." );
return false;
}
if ( document.form.membership.selectedIndex == 0 )
{
alert ( "Please Select Membership." );
return false;
}
if ( document.form.name.length < 1 )
{
alert ( "Please Enter Name" );
return false;
}
}
</script>
答案 0 :(得分:1)
尝试document.forms[0].title.selectedIndex
答案 1 :(得分:0)
改为使用document.form.name.value.length
。
答案 2 :(得分:0)
通常足以检查是否是textarea或input的值的长度。
if( field.value.length ) {
}
Bellow code,也许你需要它。
<form id="myform" method='post' onsubmit="return validate(this)">
<select name="select1">
<option value="">--</option>
<option value="val11"> Option </option>
<option value="val12"> Option </option>
</select>
<select name="select2">
<option value="">--</option>
<option value="val21"> Option </option>
<option value="val22"> Option </option>
</select>
<select name="select3" >
<option value="">--</option>
<option value="val31"> Option </option>
<option value="val32"> Option </option>
</select>
<textarea name='description'> </textarea>
<input type="submit"/>
</form>
和脚本:
var validate = function( form ) {
// argument is a form from which function was called
// Collect elements to an array which will be validated.
var inputs = [].concat.apply(
[].concat.apply([], form.getElementsByTagName("select")),
form.getElementsByTagName("textarea")
);
for( var i = 0, l = inputs.length, input; input = inputs[i], i < l; i++ ) {
if( !input.value ) {
//In case when some select don't have a value, or empty string is provided alert( input.name);
// Message will be showed
alert( "Field " + input.name + " cannot be empty!");
return false; // return false, form will not submitted
}
};
return true; // if all of selects have a properly value;
};