0

I have a form and want to verify it with javascript/jquery.

One of the fields in the form is the Gender with has two radio buttons (Male and Female)

<input type="radio" name="gender" id="genderMale" onblur="verifyGender()">
<label for="genderMale">Male</label>
<input type="radio" name="gender" id="genderFemale" onblur="verifyGender()">
<label for="genderFemale">Female</label>

I want to verify the gender by leaving them (using onblur).

function verifyGender()
{
    if(document.getElementById("genderMale").checked==true || document.getElementById("genderFemale").checked==true)
    {
        // success
    }
    else
    {
        // display error message
    }
}

I got a little bug if the user uses his/her keyboard to access the <input> fields. When the user is female, she could press tab key to go to the gender.

While the user keeps on pressing tab until it reaches to gender, the Male radio button is focused first. Since she is not male, she presses tab again and press space or just pressing the right arrow key to select "Female" but the error is already displayed.

So, I decided to execute only the function after the user leaves the gender field but I don't know how. How should I do it?

The error message must not displayed when the user is still on the gender radio buttons and he/she doesn't select one yet.

Mai
  • 363
  • 3
  • 16
  • possible duplicate of http://stackoverflow.com/questions/1525718/event-bubbling-and-the-onblur-event (look at Crescent Fresh answer) – smnbbrv Feb 22 '15 at 11:52
  • @simon I don't have any idea on what is event bubbling. – Mai Feb 22 '15 at 11:55
  • Why don't you wrap your radio inputs into a div or something and define the onblur for that? – Lajos Arpad Feb 22 '15 at 13:21
  • I don't know if onblur event is available for `
    `.
    – Mai Feb 22 '15 at 13:32
  • Read this and let me know if it is helpful: http://stackoverflow.com/questions/18504139/div-onblur-function – Lajos Arpad Feb 22 '15 at 13:35
  • It could take pressing extra tab before accessing the radio buttons. It only works before the user focuses the radio button. – Mai Feb 22 '15 at 13:52

1 Answers1

0
<input type="radio" name="gender" id="genderMale" value="male" />
<label for="genderMale">Male</label>
<input type="radio" name="gender" id="genderFemale" value="female" />
<label for="genderFemale">Female</label>

        $('input:radio[name=gender]').change(function () {
            var _gender = $(this).val();
            if (_gender === 'male') {
                console.log('male');
            } else {
                console.log('female');
            }
        });

Why not use change event on the radio selector rather than using onblur event alongside radio element.

shrawan_lakhe
  • 358
  • 2
  • 5
  • 22
  • It doesn't work all the time. Onchange event occurs for the first time when the user selects the radio button (not when the user skips it). – Mai Feb 23 '15 at 07:29