简体   繁体   English

如何使用JavaScript使用相同的功能对多个输入字段进行数据验证?

[英]How can I use the same function for data validation of multiple input fields using JavaScript?

I have a form that the user can use to enter 5 numbers. 我有一个表格,用户可以用来输入5个数字。 I have given all five input boxes the same id and a different name. 我给了所有五个输入框相同的ID和不同的名称。 I want to perform a validation of each input box. 我想对每个输入框进行验证。 I want to be able to change background color of the input boxes based on the number they enter. 我希望能够根据输入框的输入数量来更改其背景颜色。 For example, every input box with number in range 0-5 should change its background color to red and those between 6-10 should be green. 例如,每个数字范围为0-5的输入框应将其背景颜色更改为红色,而6-10之间的数字应为绿色。

I have been able to write a code that would cause the color to change for one input box, however I cannot think of a way to optimize my code and avoid having to write the same code five times. 我已经能够编写代码,从而使一个输入框的颜色发生变化,但是我想不出一种优化代码的方法,并且不必重复编写相同的代码五次。 Here is what I have got so far: 这是到目前为止我得到的:

Form: 形成:

<form id="numbers">
    Number1: <input  id ="color" name="num1" type="number"  onchange="check();">
    <br><br>
    Number2: <input   id ="color" name="num2" type="number" onchange="check();">
    <br><br>
    Number3: <input   id ="color" name="num3" type="number" onchange="check();">
    <br><br>
</form>

Function: 功能:

function check() {
    var inputVal = document.getElementById("color").value;

    if (inputVal=="" || inputVal ==null) {
        document.getElementById("color").style.backgroundColor = "white";
    }
    else if (inputVal >= 0 && inputVal <= 5) {
        document.getElementById("color").style.backgroundColor = "red";
    }
    else if (inputVal >= 6 && inputVal <= 10) {
        document.getElementById("color").style.backgroundColor = "green";
    }
}

If I change inputVal to an array and use a for loop to save values of document.getElementById("color").value, it will save the first number entered by the user five times and will only update the color of the first box. 如果我将inputVal更改为数组,并使用for循环保存document.getElementById(“ color”)。value的值,它将保存用户输入的第一个数字五次,并且只会更新第一个框的颜色。

Here is what I tried: 这是我尝试过的:

var inputVal = new Array();
for(var i=0; i<5; i++) {
    inputVal[i]= document.getElementById("color").value;
}

You can have the clicked element as a parameter 您可以将clicked元素作为参数

function check(element) {
    var inputVal = element.value;

    if (inputVal=="" || inputVal ==null) {
        element.style.backgroundColor = "white";
    }

    else if (inputVal >= 0 && inputVal <= 5) {
     element.style.backgroundColor = "red";
    }

    else if (inputVal >= 6 && inputVal <= 10) {
     element.style.backgroundColor = "green";
    }
}

and pass the argument for each input 并为每个输入传递参数

<form id="numbers">
    Number1: <input  id ="color1" name="num1" type="number"  onchange="check(this);" />
    <br/><br/>
    Number2: <input   id ="color2" name="num2" type="number" onchange="check(this);" />
    <br/><br/>
    Number3: <input   id ="color3" name="num3" type="number" onchange="check(this);" />
    <br/><br/>
</form>

But ID's must be unique. 但是ID必须是唯一的。 Here is a FIDDLE 这里是一个FIDDLE

You can use jquery to achieve this. 您可以使用jquery实现此目的。 First remove all the id value, they should not be same. 首先删除所有id值,它们不应相同。 Then use $('input').on('change', function (){ $(this).css("background-color","red")})... This way you can change colors based on values. 然后使用$('input')。on('change',function(){$(this).css(“ background-color”,“ red”)})...这样,您可以根据值更改颜色。

First, you can simplify your JavaScript by designating it to target this , since you're executing the function onchange . 首先,你可以通过指定它的目标简化您的JavaScript this ,因为你在执行功能onchange

Second, you should never leave an open-ended IF...THEN...ELSE, just bad habit for when they can result in BIG changes. 其次,永远不要留下开放式的IF ... THEN ... ELSE,这是一个坏习惯,因为它们可能导致BIG改变。

Third, as noted by others, id must be unique across the page. 第三,正如其他人指出的那样, id在整个页面上必须是唯一的。

Give this a try: 试试看:

 function check(tar) { var inputVal = tar.value; if(inputVal == '' || inputVal == null) { tar.style.backgroundColor = 'white'; } else if(inputVal >= 0 && inputVal <= 5) { tar.style.backgroundColor = 'red'; } else if(inputVal >= 6 && inputVal <= 10) { tar.style.backgroundColor = 'green'; } else { tar.style.backgroundColor = 'yellow'; } } 
 <form id="numbers"> Number1: <input class ="color" name="num1" type="number" onchange="check(this);" /> <br><br> Number2: <input class ="color" name="num2" type="number" onchange="check(this);" /> <br><br> Number3: <input class ="color" name="num3" type="number" onchange="check(this);" /> </form> 

Here's a JSFiddle: http://jsfiddle.net/v1daq6sx/ 这是一个JSFiddle: http : //jsfiddle.net/v1daq6sx/

I hope this helps. 我希望这有帮助。 ^^ ^^

When the user changes their value it fires the function giveInputColor . 当用户更改其值时,将触发功能giveInputColor You can use this one function to check infinitely many inputs with the class hello . 您可以使用此功能检查带有hello类的无限多个输入。

Working Example: http://codepen.io/anon/pen/bNqraN 工作示例: http : //codepen.io/anon/pen/bNqraN

HTML 的HTML

<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>

jQuery jQuery的

$('input.hello').keyup(function(event) {
    /* Act on the event */
    var value = $(this).val();
    $(this).css('backgroundColor', giveInputColor(value));
});

function giveInputColor(value) {
    // Give Input a color based on value parameter
    if (value >= 0 && value <= 5) return 'Red';
    else if (value >= 6 && value <= 10) return 'Green';
    else return 'White';
}

Without going into any major redesign of your logic (you could make it more efficient, but I focused on just getting the behavior that you are looking for), you can simply add the function to each element with an event listner, and then use e.target to determine which element is the one that changed and triggered the function call. 无需对逻辑进行任何重大的重新设计(您可以使其更高效,但我专注于获得所需的行为),只需将事件添加到带有事件列表器的每个元素中,然后使用e.target确定哪个元素是更改并触发了函数调用的元素。 Note - the aproach is a little more streamlined in jQuery, but I will stick with native JS here. 注意 -该方法在jQuery中略为简化,但我将在此处坚持使用本机JS。

First off, lets give all of these inputs a common class ("number-field"), to make them easier to find: 首先,让所有这些输入都具有一个公共类(“数字字段”),以使它们更易于查找:

<form id="numbers">
    Number1: <input id="num1" name="num1" type="number" class="number-field">
    <br><br>
    Number2: <input id="num2" name="num2" type="number" class="number-field">
    <br><br>
    Number3: <input id="num3" name="num3" type="number" class="number-field">
    <br><br>
</form>

I also made the id attributes unique and remover the onchange attributes, since we whill add the event listener dynamically. 我还使id属性成为唯一属性,使remover成为onchange属性,因为我们将动态添加事件侦听器。

Then we needed updated the check() function to accept the change event as a parameter ( e ) which is used in the first line of the function to determine the element that triggered the change event, using e.target (note - e.srcElement is to support older versions of IE). 然后,我们需要更新check()函数以将change事件作为参数( e )接受,该函数在函数的第一行中使用e.targete.srcElement来确定触发更改事件的元素)是为了支持IE的较早版本)。

function check(e) {
    var inputEl = e.target || e.srcElement;
    var inputVal = inputEl.value;

    if (inputVal == "" || inputVal == null) {
        this.style.backgroundColor = "white";
    }
    else if (inputVal >= 0 && inputVal <= 5) {
        this.style.backgroundColor = "red";
    }
    else if (inputVal >= 6 && inputVal <= 10) {
        this.style.backgroundColor = "green";
    }
}

The rest of the code is simply updated to point to the variable that was determined in the first line. 其余代码将简单地更新为指向第一行中确定的变量。

Finally, the function needed to be bound to the number inputs, so, using the class attribute that I added earlier, you can find all of those inputs, cycle through them, and add event listeners to each one. 最后,该函数需要绑定到数字输入,因此,使用我之前添加的class属性,您可以找到所有这些输入,在它们之间循环,并为每个输入添加事件侦听器。

var numInputs = document.getElementsByClassName("number-field");
for (i = 0; i < numInputs.length; i++) {
    numInputs[i].addEventListener('change', check);
}

I checked it out locally and it is behaving the way that I believe that you were wanting it to. 我在本地检查了一下,它的运行方式使我相信您想要它。

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

相关问题 如何将javascript函数应用于多个同名输入字段 - How to apply javascript function into multiple same name input fields 如何使此 Javascript 验证适用于多个数字字段? - How can I make this Javascript validation apply to multiple numeric fields? 如何在javascript中使用输入字段作为函数的参数? - How can i use input fields as parameters to functions in javascript? 如何使用Javascript动态生成输入字段,然后使用它们的值? - How can I dynamically generate input fields with Javascript and then use their values? 如何使用此BootStrap屏幕键盘输入多个字段? - How can I use this BootStrap onscreen keyboard for multiple input fields? 我可以在多个 Div 上使用相同的 JavaScript 函数吗? - Can I use the same JavaScript Function on multiple Div's? 如何使用多个具有相同名称的类使用相同的JS函数? - How can I use same JS function using multiple classes of same name? 如何使用JavaScript验证表单中的多个字段? - How can I validate multiple fields in a form using Javascript? 如何在使用JavaScript的表单验证中提醒用户纠正输入字段? - How to alert user to correct input fields in form validation using javascript? 我们可以使用一个Java脚本函数对多个输入进行验证吗? - Can we use one java script function to multiple input validation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM