开发者

Checking the form field values before submitting that page

开发者 https://www.devze.com 2023-01-07 16:46 出处:网络
I have written following function which checks whether start_date field is not empty and displays proper message when submit button is clicked. But then it takes the control to the previous page. So u

I have written following function which checks whether start_date field is not empty and displays proper message when submit button is clicked. But then it takes the control to the previous page. So user has to write again all other fields on that form. Is there any way to stay on that page even after prompting the error message, with all other fields value.

//JavaScript
function checkform() {
    if(document.frmMr.start_date.value == "") {
        alert("please enter start_date");
        return false;
    } else {
        document.frmMr.submit();
    }
}

// HTML
<html>
    <for开发者_JS百科m name=frmMr action="page1.jsp">
        Enter Start date:
        <input type="text" size="15" name="start_date" id="start_date">
        <input type="submit" name="continue" value="submit" onClick="checkform();">
    </form>
</html>

Thanks in advance


While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()" instead.

You may want to considering replacing this method with onsubmit="return checkform()" in the form tag instead, though both will work for clicking the button.


You can simply make the start_date required using

<input type="submit" value="Submit" required />

You don't even need the checkform() then.

Thanks


use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,

this is a code:

input type="submit" name="continue" value="submit" onClick="**return** checkform();"


Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):

<input type="submit" value="Submit" onclick="checkform()">

to a button:

<input type="button" value="Submit" onclick="checkform()">

That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.

There are other, perhaps better, ways of handling it but this works in the mean time.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号