重复相同的代码以使所有输入框显示错误。

huangapple go评论63阅读模式
英文:

Repeating the same code for all the input boxes so that they show the error

问题

我在页面上有几个输入框。以下是其中两个。我想限制用户只能在输入框中输入数字。

               <input id="address1"  class="work" />Address1
               <input id="address2"  class="work" />Address2
               <input style="float: right; margin-bottom:20px" type="submit" id="myBtn" 
                value="Submit" class="btn btn-primary"  />
               <alert13></alert13>

这是限制用户只能输入数字的代码。

    <script>
    
          $(document).ready(function () {
             
        
                    $('#myBtn1').click(function (event) {
        			
        			     var txtValue = document.getElementById("address1");
                    if (/^[a-zA-Z0-9]+$/i.test(txtValue.value)) {
                        if ((!/^[a-zA-Z]+$/i.test(txtValue.value)) && (/^[0-9]+$/i.test(txtValue.value))) {
                            $('alert13').html("value need to be alphanumeric").css('color', 'red');
                            event.preventDefault();
                        }
                        else {
                            $('alert13').html("");
                        }
                    }
        			}
        			}

    </script>

我不想为每个输入框重复上述代码。有没有更快的方法,让我根据它们的类名为所有文本框应用相同的代码,并在任何输入框中输入所有数字时显示单独的错误弹出。类名对于所有文本框都是相同的。

英文:

I have several input boxes on my page. These are two of them. I want to restrict the user to enter only digits in the input box.

           <input id="address1"  class="work" />Address1
           <input id="address2"  class="work" />Address2
           <input style="float: right; margin-bottom:20px" type="submit" id="myBtn" 
            value="Submit" class="btn btn-primary"  />
           <alert13></alert13>

This is the code that restricts the user to enter only digits.

<script>

       
        

      $(document).ready(function () {
         
    
                $('#myBtn1').click(function (event) {
    			
    			     var txtValue = document.getElementById("address1");
                if (/^[a-zA-Z0-9]+$/i.test(txtValue.value)) {
                    if ((!/^[a-zA-Z]+$/i.test(txtValue.value)) && (/^[0-9]+$/i.test(txtValue.value))) {
                        $('alert13').html("value need to be alphanumeric").css('color', 'red');
                        event.preventDefault();
                    }
                    else {
                        $('alert13').html("");
                    }
                }
    			}
    			}

</script>

I dont want to repeat the above code for every input box. Is their any quicker way so that I can apply the same code for all text boxes based on their class name and the separate error pops up if all digits are entered in any of the input box. The class name is same for all of them.

答案1

得分: 3

以下是您要翻译的内容:

是的,您可以通过使用类选择器并遍历具有该类的每个元素来重构您的代码,以避免重复。以下是如何修改您的代码以实现这一目标的示例:

<input id="address1" class="work" />地址1
<input id="address2" class="work" />地址2
<input style="float: right; margin-bottom:20px" type="submit" id="myBtn" value="提交" class="btn btn-primary" />
<alert13></alert13>
$(document).ready(function () {
    $('#myBtn').click(function (event) {
        let valid = true;

        $('.work').each(function (index, element) {
            const txtValue = $(element).val();
            const alertElement = $('alert13');

            if (/^[a-zA-Z0-9]+$/i.test(txtValue)) {
                if ((!/^[a-zA-Z]+$/i.test(txtValue)) && (/^[0-9]+$/i.test(txtValue))) {
                    alertElement.html("输入 #" + (index + 1) + " 需要是字母和数字的组合").css('color', 'red');
                    valid = false;
                    return false; // 打断循环
                } else {
                    alertElement.html("");
                }
            }
        });

        if (!valid) {
            event.preventDefault();
        }
    });
});

在此示例中,我们使用类选择器 $('.work') 获取具有类名 work 的所有元素,然后使用 each 函数遍历它们。我们还使用 valid 变量跟踪验证状态。如果任何输入框包含无效数据,我们将 valid 设置为 false 并打断循环。最后,如果 valid 变量为 false,则阻止表单提交。

英文:

Yes, you can refactor your code to avoid duplication by using a class selector and iterating through each element with that class. Here's an example of how you can modify your code to achieve this:

<input id="address1" class="work" />Address1
<input id="address2" class="work" />Address2
<input style="float: right; margin-bottom:20px" type="submit" id="myBtn" value="Submit" class="btn btn-primary" />
<alert13></alert13>
$(document).ready(function () {
    $('#myBtn').click(function (event) {
        let valid = true;

        $('.work').each(function (index, element) {
            const txtValue = $(element).val();
            const alertElement = $('alert13');

            if (/^[a-zA-Z0-9]+$/i.test(txtValue)) {
                if ((!/^[a-zA-Z]+$/i.test(txtValue)) && (/^[0-9]+$/i.test(txtValue))) {
                    alertElement.html("Value needs to be alphanumeric for input #" + (index + 1)).css('color', 'red');
                    valid = false;
                    return false; // Breaks the loop
                } else {
                    alertElement.html("");
                }
            }
        });

        if (!valid) {
            event.preventDefault();
        }
    });
});

In this example, we are using the class selector $('.work') to get all the elements with the class work and then iterating through each of them using the each function. We also keep track of the validation status using the valid variable. If any of the input boxes contain invalid data, we set valid to false and break the loop. Finally, we prevent the form submission if the valid variable is false.

huangapple
  • 本文由 发表于 2023年4月19日 22:35:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定