0

I have 3 options for an onchange event to open and hide radio button values. I am not sure how I can set the first one (value == 2) to already be opened on the page by default. Any help with this would be greatly appreciated. Below is the code I currently have.

$('input[name="type"]').on('change', function () {
    $('.opening-fields').toggle(+this.value === 1 && this.checked);
    $('.qualify-fields').toggle(+this.value === 2 && this.checked);
    $('.verify-fields').toggle(+this.value === 3 && this.checked);
    $('.datasheet-fields').toggle(+this.value === 4 && this.checked);
}).change();
3
  • 1
    There is no reason why you need to bind the change event 3 separate times. You can combine the logic into one. To what kind of input elements are you binding the change event listener to? A select element? A text/numeric input? Commented Oct 9, 2017 at 15:23
  • You can set the default value in the html, did you try that? Commented Oct 9, 2017 at 15:24
  • 1
    We need to see your HTML to help you although it sounds like you just need to add a checked attribute on the relevant input. Commented Oct 9, 2017 at 15:28

1 Answer 1

1

You can use the switch statement to determine the value of the checked radio input... Then .show() the relevant element.

The one to be checked onload should have the checked attribute in the HTML.

I assumed all elements are hidden by default.... So I used the hidden class. This may be different in your code... That is just for the example.

$('input[name="type"]').on('change', function () {
  
  // Only for the checked input
  if(this.checked){
    // Hide them all
    $(".hidden").hide();

    // determine which to show
    switch(this.value){
      case "1":
        $('.opening-fields').show();
        break;
      case "2":
        $('.qualify-fields').show();
        break;
      case "3":
        $('.verify-fields').show();
        break;
      case "4":
        $('.datasheet-fields').show();
        break;
     }
  }
}).trigger("change"); // Trigger a change event Onload
.hidden{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1:<input type="radio" name="type" value="1"><br>
2:<input type="radio" name="type" value="2" checked><br> <!-- checked onload -->
3:<input type="radio" name="type" value="3"><br>
4:<input type="radio" name="type" value="4"><br>
<br>
<br>
<div class="opening-fields hidden">opening-fields</div>
<div class="qualify-fields hidden">qualify-fields</div>
<div class="verify-fields hidden">verify-fields</div>
<div class="datasheet-fields hidden">datasheet-fields</div>

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

Comments

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.