Home > Software engineering >  Make a TextBox required if a certain Radio button is selected
Make a TextBox required if a certain Radio button is selected

Time:06-20

I want to attain that a textbox will be changed to required="true" if a certain radio value is selected as Cash

this is my html form:

<label > <input type="radio" name="payment" value="Cash" id="cashpayment" checked><span><img width="30" src="images/icons8-cash-in-hand-48.png"/></span></label>
<label > <input type="radio" name="payment" value="SD" id="sdpayment"><span><img width="30" src="images/icons8-budget-48.png"/></span></label>
<label > <input type="radio" name="payment" value="Budget" id="budgetpayment"><span><img width="30" src="images/icons8-office-48.png"/></span></label>

here is my jQuery code (jQuery v3.3.1)

$(document).ready(function(){
    $("input[name='type']:radio").change(function(){
        if($(this).val() == 'Cash')
        {
          $('#cashtender').attr('required');
        }
        else if($(this).val() == 'SD')
        {
          $('#cashtender').removeAttr('required');
        }
        else if($(this).val() == 'Budget')
        {
          $('#cashtender').removeAttr('required');
        }
    });
});

it's not working. please help

CodePudding user response:

I can see a couple of mistakes:

  1. Selector for the radio buttons is incorrect: $("input[name='type']:radio") should be $("input[name='payment']:radio")

  2. When you set an attribute, you should provide value in the second argument or use prop: $('#cashtender').attr('required'); should be $('#cashtender').attr('required', 'required'); or $('#cashtender').prop('required', true);

Complete code (removed unnecessary else if condition):

$(document).ready(function(){
    $("input[name='payment']:radio").change(function(){
        if($(this).val() == 'Cash')
        {
          $('#cashtender').prop('required', true);
        }
        else
        {
          $('#cashtender').removeAttr('required');
        }        
    });
});
  • Related