JavaScript表单验证查询

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!")
    }
});

我刚刚编写了一些验证码,以便检查我的 radio code> 我们的网络表单中的按钮在提交之前已被选中。 我刚刚开始学习 php code>,因为我希望能够在 .csv radio code>按钮的 value code> / code>文件。 p>

因为我将 action code>属性设置为触发 php code>脚本,所以我得到 alert code>框 ,但只要在按 submit code>后点击 OK code>,浏览器就会直接进入 php code>脚本(不可避免)。 p>

有没有办法可以在 alert code>消息后返回我的初始 index.html code>? p>

我还没有编写任何 php code>,所以这会在 php code>脚本或 javascript ? p>

到目前为止我的代码: p>

  $(“#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(“你必须至少选择一个单词!”); 
} 
其他{
 alert(“请评价下一个项目!”)
} 
}  ); 
  code>  pre> 
  div>

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();