0

I need to change the required value from a input base on a check box selection, here is what I have so far.... thanks

<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>

UPDATE WITH A WORKING CODE

1
  • I went ahead and created a jsfiddle for this. Hope it helps: jsfiddle.net/o75d3Lso Commented Jan 4, 2016 at 19:30

2 Answers 2

3

required is not a javascript property.

Change

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

to

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

Here's the entire script code :

$(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);
                }
    });
});

Working example : https://jsfiddle.net/23rdtjwq/4/

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Dinomyte, when I check the checkbox it removes the required from the #land_line but is no adding required to #cellphone
I've added a fiddle link for reference. check that.
1

Following your use of javascript:

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

2 Comments

thank you it work this way,, I update the code on this question to the working code
No problem :-) Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.