简体   繁体   English

在Javascript中,如何更改警报窗口以在输入框旁边显示该警报

[英]In Javascript how can I change an alert window to display that alert next to an input box

My friend and I are making a data validation program. 我和我的朋友正在制作一个数据验证程序。 If you enter in data that the program will not accept (example such as putting numbers in a name field) you get a windows alert telling you that is not valid. 如果输入程序不接受的数据(例如,在名称字段中输入数字),则会显示Windows警报,提示您无效。 We decided we want to change this so that instead of a windows alert there will be an empty table cell to the right of each of the form elements that displays that your data is not valid. 我们决定要更改此设置,以便代替Windows警报,在每个表单元素右侧将显示一个空表单元格,以显示您的数据无效。 How could I change this? 我该如何更改? Attaching code below. 下面附上代码。

function fNameValidation()
{
if (document.forms[0].fName.value.length==0)                //First name data validation
{                                                           //check for any entry
alert('Please enter your first name.');
document.forms[0].fName.focus();
return;
}

在具有唯一ID的输入字段旁边放置一个span元素,然后可以将Text插入该特定字段:

document.getElementById('firstNameError').innerHTML = "Please enter your first name.";

Easiest aproach is to set id of this cell: 最简单的方法是设置此单元格的ID:

<td id="nameErrorCell">
    (...)
</td>

and than in your javascript: 并且比您的javascript:

var cell = document.getElementById('nameErrorCell');
cell.innerHTML="error message";

You can also traverse DOM tree up one level to <td> element, then to its sibling and alter its innerHTML with your error message. 您还可以将DOM树向上移动到<td>元素,然后到其同级,并使用错误消息更改其innerHTML

document.forms[0].fName.parentNode.nextSibling.innerHTML = 'Please enter your first name.');

If there are elements between <input> and <td> , add more .parentNode . 如果<input><td>之间有元素,请添加更多.parentNode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM