简体   繁体   English

带有弹出窗口的javascript表单

[英]javascript form with a popup

Really basic, I'm just trying to understand how to test a form using simple JavaScript without jQuery etc. Tried W3Schools but didn't work. 真的很基础,我只是想了解如何在不使用jQuery等的情况下使用简单的JavaScript测试表单。尝试了W3Schools,但没有用。 So I'm trying just a simple form instead with one field to get how it all works. 因此,我正在尝试仅使用一种简单的表单而不是一个字段来获取其工作原理。 Below I put a single field in a form, and thought I could test the fname variable against the firstName field. 下面,我在表单中放置了一个字段,并认为可以针对firstName字段测试fname变量。

But what happens is that the alert is never hit in the if statement. 但是发生的是,警报永远不会在if语句中命中。 How to test the field firstName? 如何测试字段firstName?

Any tips would be helpful. 任何提示都会有所帮助。

 function validateForm() { var fname = document.getElementById("firstName"); if (fname == "") { alert("first name is a mandatory field"); } else { document.getElementById("formMessage").innerHTML = fname + " entered."; } } 
 <h2>Question 1 validate with alert popups</h2> <p>Please enter the following mandatory information</p> <form name="identification"> <p>First Name:<input type="text" id="firstName" /></p> <p> <button type="button" onclick="validateForm()">Submit</button> </p> </form> <p id="formMessage"></p> 

You're comparing the element itself. 您正在比较元素本身。 You should instead check the value of the element. 您应该改为检查元素的value

eg 例如

var fname = document.getElementById("firstName").value;

fname is the element when you do document.getElementById, so you have to do: fname是执行document.getElementById时的元素,因此您必须执行以下操作:

function validateForm() {
            var fname = document.getElementById("firstName");
                if (fname.value == "") {
                    alert("first name is a mandatory field");
                } else {
                    document.getElementById("formMessage").innerHTML = fname.value + " entered.";
                }
            } 

You might also want to trim fname.value in case the user inputs bunch of empty spaces. 您可能还需要修剪fname.value,以防用户输入一堆空白。

Use document.getElementById("firstName").value to get the value. 使用document.getElementById("firstName").value获取值。 if you don't add .value it means it didn't read the specified value. 如果不添加.value则表示未读取指定值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM