У меня есть страница jsp с некоторыми текстовыми полями. Теперь я хочу заполнить их некоторой информацией и нажать кнопку «Отправить». Но мне нужно проверить, пуст ли этот TextBox или нет.
Как я могу это сделать?
Канонический без использования фреймворков с добавленным прототипом обрезки для старых браузеров
<html>
<head>
<script type="text/javascript">
// add trim to older IEs
if (!String.trim) {
String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};
}
window.onload=function() { // onobtrusively adding the submit handler
document.getElementById("form1").onsubmit=function() { // needs an ID
var val = this.textField1.value; // 'this' is the form
if (val==null || val.trim()=="") {
alert('Please enter something');
this.textField1.focus();
return false; // cancel submission
}
return true; // allow submit
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" name="textField1" value="" /><br/>
<input type="submit" />
</form>
</body>
</html>
Вот встроенная версия, хотя я не рекомендую показывать ее здесь на случай, если вам нужно добавить проверку без возможности рефакторинга код
function validate(theForm) { // passing the form object
var val = theForm.textField1.value;
if (val==null || val.trim()=="") {
alert('Please enter something');
theForm.textField1.focus();
return false; // cancel submission
}
return true; // allow submit
}
передача объекта формы в (this)
<form onsubmit="return validate(this)">
<input type="text" name="textField1" value="" /><br/>
<input type="submit" />
</form>
Использование этого JavaScript очень поможет вам. Некоторые пояснения даются внутри кода.
<script type="text/javascript">
<!--
function Blank_TextField_Validator()
{
// Check whether the value of the element
// text_name from the form named text_form is null
if (!text_form.text_name.value)
{
// If it is display and alert box
alert("Please fill in the text field.");
// Place the cursor on the field for revision
text_form.text_name.focus();
// return false to stop further processing
return (false);
}
// If text_name is not null continue processing
return (true);
}
-->
</script>
<form name="text_form" method="get" action="#"
onsubmit="return Blank_TextField_Validator()">
<input type="text" name="text_name" >
<input type="submit" value="Submit">
</form>