点击按钮并!=提交后,如何实时知道在输入字段中输入的内容?

时间:2018-08-20 19:31:53

标签: javascript jquery

我在考虑做标题建议的最佳方法是什么?我只是在学习JS / JQ,不确定什么是最好的方法。

我在表单中有一个前往下一个按钮,如果某些输入字段不符合条件,该按钮将不起作用。最好的事情是什么?我需要向这些字段添加常量侦听器以更新值吗?

如果您只是指出正确的方向,我会从那里接走。

我当前的代码如下:

$(document).ready(function(){
    $("#button").click(function(){
        if(selectedSlots.length < 2 ||
        $("#field1").length < 1 ||
        $("#field2").length < 1){
            var origMsg = $(this).get(0).parentNode.innerHTML;
            var errorMsg = "<p style=\"text-align:center;padding:0;margin:0;\">Please ";
                if(selectedSlots.length < 1)errorMsg += "select at least one availability slot";
                if($("#field1").length < 1){errorMsg += "enter the position you wish to apply for"};
                if($("#field2").length < 1){errorMsg += "enter the amount of hours you would like to work"};
                errorMsg += " before continuing.</p>";

            $(this).get(0).parentNode.innerHTML = origMsg + errorMsg;

            return;

        }
        $("#currentDiv").slideUp();
        $("#nextDiv").slideDown();

    });
});

2 个答案:

答案 0 :(得分:0)

当用户单击“提交”按钮以外的任何其他位置时,请尝试onBlur事件来验证并设置输入错误。

答案 1 :(得分:0)

缺少的只是元素.get(0).value.之后的这个小片段!谢谢您的时间!

$(document).ready(function(){
    $("#button").click(function(){
        if(selectedSlots.length < 2 ||
        $("#field1").length < 1 ||
        $("#field2").length < 1){
            var origMsg = $(this).get(0).parentNode.innerHTML;
            var errorMsg = "<p style=\"text-align:center;padding:0;margin:0;\">Please ";
                if(selectedSlots.length < 1)errorMsg += "select at least one availability slot";
                if($("#field1").get(0).value.length < 1){errorMsg += "enter the position you wish to apply for"};
                if($("#field2").get(0).value.length < 1){errorMsg += "enter the amount of hours you would like to work"};
                errorMsg += " before continuing.</p>";

            $(this).get(0).parentNode.innerHTML = origMsg + errorMsg;

            return;

        }
        $("#currentDiv").slideUp();
        $("#nextDiv").slideDown();

    });
});