验证并显示窗口警报

时间:2015-12-07 16:50:04

标签: javascript

如何确认总计或orderForm的值已经填满,如果不是它会在点击“提交”按钮时显示窗口警报?

以下似乎根本不起作用。

Pure JS:

function va(){
                 var result = false;
                                var w = document.forms["orderForm"]["companyName"].value;
                                var x = document.forms["orderForm"]["forename"].value;
                                var y = document.forms["orderForm"]["surname"].value;
                                var z = document.forms["orderForm"]["total"].value;
                                if (x == null || x == "") && (y == null || y == "") && (w == null || w == ""){
                                     window.alert('Name must be Filled out');
                                        result = false;
                               // } else if (z = < 5){
                                  //      window.alert('Please Select A CD');
                                //        return false;
                                // }else {
                                 //       return true;
                                    }
                                    return result;
                        }

HTML:

        <section id="checkCost">
            <h3>Total cost</h3>
            Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
        </section>

        <section id="placeOrder">
            <h3>Place order</h3>
            Your details
                        Customer Type: <select id="show" name="customerType" onchange="change(this)">      
                <option value="">Customer Type?</option>     
                <option value="ret">Customer</option>
                <option value="trd">Trade</option>
            </select>

            <div id="retCustDetails" class="custDetails" style="display:none">
                Forename <input type="text" name="forename" id="forename" />
                Surname <input type="text" name="surname" id="surname" />
            </div>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>

2 个答案:

答案 0 :(得分:0)

尝试:

if ((x == null || x == "") || (y == null || y == "") || (w == null || w == ""))

编辑:

当然,原来的一行:

if (x == null || x == "") && (y == null || y == "") && (w == null || w == "")

我做了两件事。关掉&amp;&amp;为||并将if条件包含在一个包含的括号中(这可能不是必需的,但我是为了整洁)。原始if语句读作“如果条件和条件和条件”意味着所有条件必须返回true(即为空白)才能继续。我相信每个值都需要验证表单。如果任何值为空,我建议的if语句将读取“如果条件或条件或条件”显示警告框。

答案 1 :(得分:0)

试试这个:

if (x == null || x == "") {
    window.alert('forename must be Filled out');
    result = false;
} else if (y == null || y == "") {
    window.alert('surname must be Filled out');
    result = false;
} else if (w == null || w == "") {
    window.alert('companyName must be Filled out');
    result = false;
}

return result;