我想在JavaScript中验证我的必填字段不是空白 [英] I want to verify in JavaScript that my required fields are not blank

查看:75
本文介绍了我想在JavaScript中验证我的必填字段不是空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这是基本的JavaScript,答案很简单,因为我是新手。我只想确保在用户继续操作之前所有必填字段都不是空白。在我的< form> 操作 = payment.php 并且提交按钮包含 onclick =insert();当child_name留空时,它只会进入下一页而不是提醒。以下是代码:

Hopefully this is basic JavaScript and the answer is easy since I am new at this. I just want to make sure all required fields are not blank before the user can proceed. In my <form> action = payment.php and the submit button contains onclick="insert();" When child_name is left blank, it just proceeds to the next page rather than alerting. Here is the code:

    <script type="text/javascript">
    function insert() {
        if (window.XMLHttpRequest) {
            xmlhttp = new XLMHttpRequest();
        } else {
            xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
        }



        cn1 = 'child_name'+document.getElementById('child_name').value;
        ag2 = 'age'+document.getElementById('age').value;
        hm3 = 'hometown'+document.getElementById('hometown').value;
        bg4 = 'boy_girl'+document.getElementById('boy_girl').value;
        fn5 = 'first_name'+document.getElementById('first_name').value;
        ln6 = 'last_name'+document.getElementById('last_name').value;
        email = 'email'+document.getElementById('email').value;
        ad8 = 'address1'+document.getElementById('address1').value;
        ad9 = 'address2'+document.getElementById('address2').value;
        ct10 = 'city'+document.getElementById('city').value;
        st11 = 'state'+document.getElementById('state').value;
        zp12 = 'zip'+document.getElementById('zip').value;

        if (cn1.equals("")) {


        xmlhttp.open('POST', 'payment.php', true);
        xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xmlhttp.send(cn1&ag2&hm3&bg4&fn5&ln6&email$ad8&ad9&ct10&st11&zp12); 
        } else {
        alert ("Please enter all required fields.");
        }
    }
</script>


推荐答案

这里有几个问题:

cn1 = 'child_name'+document.getElementById('child_name').value;

在这种情况下,您将cn1分配给字符串'child_name' +你的child_name文本框的值...它永远不会等于空字符串。

In this case you are assigning cn1 to the String 'child_name' + the value of your child_name textbox... it will never equal an empty String.

其次,你需要你的 insert()返回 false 的方法,以便停止按钮的预期操作。

Secondly, you'll want your insert() method to return false on error in order to stop the button's intended action.

这篇关于我想在JavaScript中验证我的必填字段不是空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆