JavaScript表单验证查询

I've just wrote some validation code so as to check if either of my radio buttons from my web form have been selected before they are submitted. I've just starting learning php as I want to be able to store the value of each radio button in a .csv file.

Because I have my action attribute set to trigger a php script, I get my alert box, but as soon as I click OK after pressing submit the browser goes straight to the php script (inevitably).

Is there a way I can return to my initial index.html after the alert message?

I have not actually written any php as yet, so would this go in the php script or the javascript?

Heres my code so far:

$("#submit").on("click", function() {

    var radio = $("input[type=radio][name=emotion]")[0].checked;
    var radio2 = $("input[type=radio][name=emotion]")[1].checked;
    var radio3 = $("input[type=radio][name=emotion]")[2].checked;

    if(!radio && !radio2 && !radio3) {
        alert("You must select at least one word!");
    }
    else {
        alert("Please rate the next item!")
    }
});

In Jquery you should use .submit() function to validate a form. Then to avoid to submit the form you can use the function event.preventDefault() And if you want to go to the index you can use window.location = "yourURL"

You must use form.onsubmit(). For example, if your form's name is myForm:

document.forms['myForm'].onsubmit = function()
{
    if (this.elements['emotion'].value)
    {
        alert("Please rate the next item!");
    }
    else
    {
        alert("You must enter at least one word!");
        return false;
    }
}

And after alert "Please rate the next item!" form will be send.

Actually you can use jquery $.post() , an easy solution is just to post your php page without leaving index page.

http://api.jquery.com/jquery.post/

$.post( "yourpage.php" );

You probably have the input type of the submit button as submit? Set this to button, so the action doesn't take place and only jQuery is executed.

But then you have to submit the form by jQuery when validation was successful:

document.myFormId.submit();