Requirements:
- Click on Radio Button Agree --- Do something
- Click on Radio Button Disagree --- Do something
It's working completely fine for first time.
The problem is occurring when clicking on the 'disagree' radio button and then again clicking 'agree'. It's not calling the functionality defined in 'agree' section (i.e. the submit button still should be in disabled mode) and vice versa. Requesting your suggestion please.
$('input[type=radio][name=choice]').change(function() {
if (this.value == 'Agree') {
$('#submit').click(function(event) {
event.preventDefault();
}
)
} else if (this.value == 'Disagree') {
$('#submit').removeAttr('disabled');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" name="choice" value="Agree" id="agree_radio">Agree</label> label>
<input type="radio" name="choice" value="Disagree" id="disagree_radio">Disagree</label>
<button type="submit" class="btn btn-success" name="btn" value="resp_form" disabled="disabled" id="submit">Submit</button>
The issue is because you're nesting event handlers. To fix the problem separate the logic so that you enable the button based on the chosen radio in the
changeevent handler. Then have a separate handler on form submission which checks that the 'Agree' radio is checked, and prevents the event if not. Try this:In theory the form should never be submit when 'Disagree' is checked as the button is disabled, but people can still mess with the DOM inspector, or hit return on the inputs to submit the form, so it's best to cover the eventuality.