AXAI
AXAI

Reputation: 706

Alert a message when clicking on a selected radio button

$('form').change(function() {
    if('input[type=radio]:checked') {
        alert('Already Selected');
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='get' action=''>
    <input type="radio" name="radiobutton">
    <input type="radio" name="radiobutton">
    <input type="radio" name="radiobutton">
</form>

In this form here, I'm trying to prevent the user from clicking twice on selected radio button, So i want to alert a message everytime he clicks the selected radio button.

Upvotes: 0

Views: 588

Answers (1)

user4426167
user4426167

Reputation:

So a few things based on your plain english explanation:

  1. You should probably bind to the radio input, instead of the form element.
  2. You should probably use a click event instead of change
  3. You need to track the state of each radio button

$('input[type=radio]').click(function() {
    if($(this).data('previously-checked')) {
        alert('Already Selected');
    }
    // update all as not clicked
    $('input[type=radio]').data('previously-checked', false);
    // mark current one as checked
    $(this).data('previously-checked', true);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='get' action=''>
    <input type="radio" name="radiobutton" value="Y">
    <input type="radio" name="radiobutton" value="Y">
    <input type="radio" name="radiobutton" value="Y">
</form>

Upvotes: 1

Related Questions