Allen Skelton
Allen Skelton

Reputation: 15

Can you call a CSS style sheet to an HTML document in an if statement

I am trying to bring in an external style sheet from a css file in an if statement. I have several textboxes and I need for if on the click of a button a pop up come up and it say the entire form should be filled and the background color change to red. I have this in my HTML file:

<style type="text/css">

@import url("mysheet.css");

</style>

<script type="text/javascript">
function validateform()
{
var x=document.forms["CustInfo"]["Fname"].value;
if (x == null || x == "")
{
    alert("The entire form must be filled out");
    return false;
}
</script>

In my CSS file I simply have:

.formalert{
    background-color: Red;
}

How can I change that "alert" to call my formalert?

Upvotes: 0

Views: 966

Answers (1)

Umbrella
Umbrella

Reputation: 4788

The simple way to do this is to always include the style, but only set your form to have that className if it fails validation.

<style type="text/css">
.formalert{
    background-color: Red;
}
</style>

<script type="text/javascript">
function validateform(oForm)
{
    var x=document.forms["CustInfo"]["Fname"].value;
    if (x == null || x == "")
    {
        alert("The entire form must be filled out");
        oForm.className += ' formalert';
        return false;
    }
    return true;
}
</script>        

<form action="" method="post" onsubmit="return validateform(this);">
...
</form>

Upvotes: 2

Related Questions