简体   繁体   English

在同一表单上具有多个文本字段的多个按钮的HTML“必需”属性

[英]HTML “required” attribute for multiple button with multiple text field on same form

I have HTML form which has multiple button and multiple text fields on same form some thing like below. 我有HTML表单,在同一表单上有多个按钮和多个文本字段,如下所示。

Form: #myform 形式:#myform

TextField1 ---> Button1
TextField2 ---> Button2
.. so on like more number of fields

I want to apply "required" attribute only specific button to specific textfield (Button1 for TextField1 ) 我想仅将“必需”属性的特定按钮应用于特定的文本字段(TextField1的Button1)

It will be grateful if someone provide solution in javascript by passing some parameter to perform this validation 如果有人通过传递一些参数来执行此验证来提供JavaScript解决方案,将不胜感激

According to mozilla "required" is not included. 根据mozilla, “必需”不包括在内。 So "required" is not allowed on element "button". 因此,元素“按钮”上不允许使用“必需”。 You can add, but it will not add validation. 您可以添加,但不会添加验证。 For button and i would use validation with javascript. 对于按钮,我将使用JavaScript进行验证。

I found solution to suit my requirement which I asked in automated fashion, I am posting the code so that might be useful if someone searching solution like me 我找到了适合我以自动化方式提出的要求的解决方案,我正在发布代码,以便在有人像我这样搜索解决方案时使用该代码

Calling function on button click 单击按钮即可调用功能

    <input type="text" id="txtfield1" class="texttype0" th:field="*{txtfield1}" placeholder="Enter txtfield1"> 
    <button type="submit" id="bt1" onclick="btn('txtfield1')" name="action" >Update</button>

And below is my javascript function 以下是我的javascript函数

function btn(txtid) {
        document.getElementById(txtid).setAttribute("required", true);
    $('form#myform').find(
                'input[type=text],input[type=date],select').each(
                function() {
                    var name = $(this).attr('id');
                    if (txtid == name) {
                        $(name).prop("required", true);
                    } else {
                        $(name).prop("required", false);
                        document.getElementById(name).required = false;
                    }
                });
    }

This will search all element from a form and remove require attribute except the one which you passed in parameter. 这将从表单中搜索所有元素,并删除require属性,但您传入参数的属性除外。

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

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