使用javascript格式

时间:2015-07-23 13:14:49

标签: javascript forms getelementbyid

我必须使用javascript创建一个表单,如果该字段为空,则返回内联显示的消息错误。 在下面的代码中,只有第一个运行,我无法设置邮政编码。 (我不允许使用Jquery) 谢谢你的时间

function checkForm() {
    document.getElementById("frm1").onsubmit = function() {
        if (document.getElementById("lastname").value === "") {
            showError();
            return false;
        } else {
            return true;
        }
    }
}

function checkForm() {
    document.getElementById("frm1").onsubmit = function() {
        if (document.getElementById("postCod").value === "") {
            showError();
            return false;
        } else {
            return true;
        }
    }
}

function showError() {
    document.getElementById("error").style.display = "inline";
}
window.onload = checkForm;

3 个答案:

答案 0 :(得分:0)

我会将这两个函数合并为一个:

CREATE TABLE t2 (id INT, level INT, someDate datetime, mostRecent int)
GO
INSERT INTO t2
SELECT 1, 1, '1/1/2010', 1 UNION ALL
SELECT 2, 1, '2/2/2010', 1 UNION ALL
SELECT 3, 2, '3/3/2010', 1 UNION ALL
SELECT 4, 3, '4/4/2010', 1 UNION ALL
SELECT 5, 3, '5/5/2010', 1 UNION ALL
SELECT 6, 3, '6/6/2010', 1 UNION ALL
SELECT 7, 4, '7/7/2010', 1 UNION ALL
SELECT 8, 5, '8/8/2010', 1 UNION ALL
SELECT 9, 6, '9/9/2010', 1 UNION ALL
SELECT 10, 6, '10/10/2010', 1 UNION ALL
SELECT 11, 8, '11/11/2012', 1
GO
-- this doesn't work
UPDATE t2 SET mostRecent = 0
FROM t2
WHERE NOT EXISTS
    (SELECT * FROM t2
    JOIN
        (SELECT level, max(someDate) as someDate FROM t2 group by level) as maxrows
    ON t2.someDate = maxrows.someDate)
GO
-- this works
UPDATE t2 SET mostRecent = 0
FROM t2
WHERE id NOT IN
    (SELECT t2.id FROM t2
    JOIN
        (SELECT level, max(someDate) as someDate FROM t2 group by level) as maxrows
    ON t2.someDate = maxrows.someDate)

答案 1 :(得分:0)

您需要将其从onsubmit更改为addEventListener。这是因为当你将.onsubmit设置为覆盖值时,使用addEventListener就像是一个对象属性。使用var form = document.getElementById("frm1") form.addEventListener("submit", function () { // do something }) 可以让多个函数绑定到同一个事件。

$("body").trigger("click");

答案 2 :(得分:0)

实际上,只有一个函数可以使用多个if-else语句。

   function checkForm() {
    document.getElementById("frm1").onsubmit = function() {
        if (document.getElementById("lastname").value === "") {
            showError();
            return false;
        } else  if (document.getElementById("postCod").value === "") {
            showError();
            return false;
        } else {
            return true;
        }
    }
 }

function showError() {
    document.getElementById("error").style.display = "inline";
}
window.onload = checkForm;