0

When radio button value is 1 or 2 or 3, I would like to run validation for first and last name.

<form action="index.php" method="post" name="index">

<input type="radio" name="hello" value="abc">
<input type="radio" name="hello" value="def">
<input type="radio" name="hello" value="ghi">
<input type="radio" name="hello" value="jkl">
<input type="radio" name="hello" value="mno">

<input type="text" id="first-name" name="first-name">
<input type="text" id="last-name" name="last-name">

</form>

<script>

if ( $('input:radio[name=hello]:checked').val() == "abc" || $('input:radio[name=hello]:checked').val() ==  "def" || $('input:radio[name=hello]:checked').val() == "ghi" )
{

    if( ($('input[name=first-name]').val().length<1 ))
    {
        $('#first-name').focus();
        return false;
    }


    if( ($('input[name=last-name]').val().length<1 ))
    {
        $('#last-name').focus();
        return false;
    }
}

</script>

I wrote something like this but it doesn't work. Even I choose value for "mno", the first-name validation work. Also this function won't validate the last-name.

any idea what i did wrong?

1
  • 1
    your script seems ok and i tested on fiddle and working fine Commented Feb 23, 2014 at 20:28

1 Answer 1

0

You are using javascript for validation but you should use this javascript in a function and call that function from your form, until it will not work because you are not calling this javascript that mean it is not working. Here is the simple code for validation by which you can see how to validate a form. hope this code will help you.

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
 if (x==null || x=="")
{
 alert("First name must be filled out");
 return false;
}
}
</script>
 </head>

 <body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>

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.