【问题标题】:Confirm msg before submitting a form提交表单前确认消息
【发布时间】:2015-10-09 09:00:57
【问题描述】:

我正在验证一个表单,然后通过 javascript 请求确认... 所以在提交时我调用了两个函数名 validate() & make_confirm()..

onsubmit="return(validate() && show_alert(this));"

通过这个,我可以部分调用这两个函数,但确认部分无法正常工作,我必须在按下 OK 时将其重定向到另一个页面,但它不会去,请帮帮我

validate & make_sure() 函数如下:

function validate() {
           if(document.getElementById('cname').value == '')
            {
                alert('Please enter your name');
                document.getElementById('cname').focus();
                return false;
            }
            else if(document.getElementById('address').value == '')
            {
                alert('Please enter your address');
                document.getElementById('address').focus();
                return false;
            }
            else if(document.getElementById('city').value == '')
            {
                alert('Please choose your city');
                document.getElementById('city').focus();
                return false;
            }
            else if(document.getElementById('state').value == '')
            {
                alert('Please enter your state');
                document.getElementById('state').focus();
                return false;
            }
function make_sure() {
          if(confirm("Do you really want to do this?"))
            document.forms[0].submit();
          else
            return false;
        }

【问题讨论】:

  • 问题是什么?
  • 验证字段后我无法调用确认消息

标签: javascript onsubmit


【解决方案1】:

使用一个函数进行验证和确认,并设置表单的action 将表单当前页面重定向到另一个页面。

function validateAndConfirm() {
    if( isEmpty(id('cname').value) ) {
        alert('Please enter your name');
        id('cname').focus();
        return false;
    }
    else if( isEmpty(id('address').value) ) {
        alert('Please enter your address');
        id('address').focus();
        return false;
    }
    else if( isEmpty(id('city').value) ) {
        alert('Please choose your city');
        document.getElementById('city').focus();
        return false;
    }
    else if( isEmpty(id('state').value) ) {
        alert('Please enter your state');
        id('state').focus();
        return false;
    } else {
        if(confirm("Do you really want to do this?")) {
            document.forms[0].submit();
        }
        else {
            return false;
        }
    }
}

function isEmpty(val){
    return (typeof val == 'undefined' || val === undefined || val == null || val.length <= 0) ? true : false;
}

// this function help to simplify you writing : document.getElementById to just id
function id(sid){
   return document.getElementById(sid);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多