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. 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:
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):
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:
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>
). You also need to set all parts of the border property when using style.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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.