[英]Issues changing border color in javascript
I am submitting a form, and it has validation to make sure my text box has a value. 我正在提交一个表单,它具有验证功能以确保我的文本框具有值。 If
false
, the alert displays fine, however I can't get the border to change color. 如果为
false
,则警报显示正常,但是我无法更改颜色。 I can't seem to find out what I am doing wrong. 我似乎无法找出我做错了什么。
<script>
function validate(){
var dob = document.forms["ppm"]["dob"].value;
if(dob == ""){
document.getElementById("dob").style.border="red";
alert("Error");
return false;
}
}
</script>
<form onsubmit="return validate()" name="ppm" id="ppm" action="index.php" method="post">
<p>What is your DOB<br />
<input type="text" name="dob" id="dob" value="" />
<input type="submit" name="Continue" value="Continue"/>
</form>
You have to give the border the some width before it will be visible. 您必须先给边框加上一定的宽度,然后才能看到边框。 You can use the individual
border*
properties for that: 您可以为此使用单个
border*
属性:
document.getElementById("dob").style.borderColor ="red";
document.getElementById("dob").style.borderWidth ="2px";
Or, stick with border
but supply a full border value (width, style, and color): 或者,坚持使用
border
但要提供完整的边框值(宽度,样式和颜色):
document.getElementById("dob").style.border = "2px solid red";
Here's a working example slightly modified from your original: 这是一个与原始示例稍作修改的工作示例:
function validate() { var dob = document.getElementById('dob').value; if (dob == null || dob == '') { document.getElementById("dob").style.border = "2px solid red"; alert("Error"); return false; } }
<p>What is your DOB <br /> <input type="text" name="dob" id="dob" value="" /> <input type="button" onclick="validate()" name="Continue" value="Continue" />
I'm tempted to rewrite your validate
function into something like this: 我很想将您的
validate
函数重写为如下形式:
function validate() {
var dobEl = document.getElementById('dob'); // only get it once
if (!(dobEl.value || '').length)) { // if null or empty
dobEl.style.border = "2px solid red"; // set the style
alert("Error");
return false; // don't submit the form
} else {
// set the border back to normal
}
return true; // do submit the form
}
You are missing an end tag on your paragraph ( </p>
). 您在段落(
</p>
)上缺少结束标记。 You also need to set all parts of the border property when using style.border
. 使用
style.border
时,还需要设置border属性的所有部分。 Below is a working example. 下面是一个工作示例。
var isValid = function () { var dob = document.forms["ppm"]["dob"].value; if (dob === "") { document.getElementById("dob").style.border = "solid 1px red"; alert("Error"); return false; } return true; };
<form onsubmit="return isValid();" name="ppm" id="ppm" action="index.php" method="post"> <p>What is your DOB</p> <br /> <input type="text" name="dob" id="dob" value="" /> <input type="submit" name="Continue" value="Continue" /> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.