使用jquery或javascript从输入更改requiered值

时间:2016-01-04 18:59:02

标签: javascript jquery

我需要在选中复选框的基础上更改所需的值,这是我到目前为止所做的....谢谢

<input type="checkbox" id="no_land_line" name="no_land_line" value="”/> // if no land line check here


    <script>
$(document).ready(function () {
    $('#no_land_line').change(function () {
        if (!this.checked) 
        {
          $('#no_land_line_div').fadeOut('slow');
          document.getElementById("land_line").setAttribute("required", true);
          document.getElementById("cellphone").setAttribute("required", false);

        }
        else {
         document.getElementById("land_line").setAttribute("required", false);
         document.getElementById("cellphone").setAttribute("required", true);
         $('#no_land_line_div').fadeIn('slow');

                }
    });
});
</script>


<input type="text" name="land_line" id="land_line" required="true"/>  // landline number
<input type="tel" name="cellphone" id="cellphone" required="false"/> // cellphone number

<div id="no_land_line_div”>some text</div>

使用工作代码更新

2 个答案:

答案 0 :(得分:3)

必需不是javascript属性。

更改

getElementById("land_line").required = false,
getElementById("cellphone").required = true;

$("#land_line").attr("required",false);
    $("#cellphone").attr("required",true);

这是整个脚本代码:

$(document).ready(function () {
    $('#no_land_line').change(function () {
        if (!this.checked) 
        {
          $('#no_land_line_div').fadeOut('slow'),
          $("#land_line").attr("required",false);
          $("#cellphone").attr("required",true);
        }
        else {
          $('#no_land_line_div').fadeIn('slow'),
           $("#land_line").attr("required",true);
          $("#cellphone").attr("required",false);
                }
    });
});

工作示例:https://jsfiddle.net/23rdtjwq/4/

答案 1 :(得分:1)

使用javascript:

document.getElementById("land_line").setAttribute("required", false);
document.getElementById("cellphone").setAttribute("required", true);