我正在尝试使输入框的名称更改为红色,同时当值为“”时在其下方显示一条消息。我正在用JavaScript进行所有这些操作。但是,当我进行测试时,什么也没有发生。我检查了控制台,没有发现任何问题。想知道是否有人可以帮助我,看看我的错误在哪里。
<form id="customer_form" onsubmit="return customerFormValidation(this)" action="">
<h1 style="text-align: center">Billing Address</h1>
<div class="row">
<label for="fname"><i class="fa fa-user"></i> Full Name</label>
<input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
<label for="email"><i class="fa fa-envelope"></i> Email</label>
<input type="text" id="email" name="email" placeholder="john@example.com">
<label for="phone"><i class="fa fa-address-card-o"></i> Phone #</label>
<input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
<label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
<input type="text" id="address" name="address" placeholder="542 W. 15th Street">
<label for="city"><i class="fa fa-institution"></i> City</label>
<input type="text" id="city" name="city" placeholder="New York">
<div class="col-50">
<label for="state">State</label>
<input type="text" id="state" name="state" placeholder="NY">
</div>
<div class="col-50">
<label for="zip">Zip</label>
<input type="text" id="zip" name="zip" placeholder="10001">
</div>
</div>
</form>
<button class="fa orange btn" type="submit" id="customerBtn">Next</button>
<script>
function customerFormValidation() {
reason = "";
reason += validateName(customer_form.firstname);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return false;
}
}
function validateName(firstname) {
var error = "";
if (firstname.value == "") {
document.getElementById("firstname").style.display = "block";
document.getElementById("firstname").innerText = "Please enter your name";
document.getElementById("firstname").style.borderColor = "red";
document.getElementById("firstname").focus();
} else {
firstname.style.background = 'White';
document.getElementById('firstname').innerHTML = "";
}
return error;
}
</script>
The problem is that your
submit
button is outside your form, so it can't trigger the form's submit event.如果将按钮放在表单内,它将起作用。
问候。