user1707035
user1707035

Reputation:

Set parameter of font color from javascript

I need to show the text <Reg id:> in red color if reg id is null or empty. This is my current implementation but on alert, color is not changed.

<html>
<head>
<script type="text/javascript">
    function ValidateForm() {
        var stu_regid = document.forms["detail"]["regid"].value;

        if ((null == stu_regid) || (stu_regid == "")) {
            alert("Reg is should not be left blank");
                        // here change the color to red
            document.getElementsByName("font_regid").innerHTML = "red";
            return false;
        }
    }
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

</head>
<body>
<%!String font_regid = new String();%>
    <form name="detail" action="ReportGenerator" method="get"
        onsubmit="return ValidateForm()">

        <font color=<%=font_regid%>>Reg id:</font> 
        <input type="text" name="regid"><br>

        // some code here also

         <input type="submit" value="submit">
    </form>

</body>
</html>

Upvotes: 0

Views: 1725

Answers (3)

user1707035
user1707035

Reputation:

After little more research i came up with one very simple solution.

I used

Span

tag with an id and receive that id in javascript. This way it worked for me. I changed font to span, some thing like following

    <span id="id_01120">Reg id:</span> 
    <input type="text" name="regid"><br>

and receive it like following

if ((null == label_id) || (label_id == "")) {
        ShowError(label_id, document.getElementById("id_01120"));
        return false;
    }

and then change the color like following

    function ShowError(errorfield, errorfont) {
    alert(errorfield.concat("should not be left blank"));
    errorfont.style.color = "red";
}

Upvotes: 1

adeneo
adeneo

Reputation: 318232

You really should'nt be using font tags, but to change an elements style, you do:

element.style.color = "#000";

and as getElementsByName returns a nodeList of elements, you need to select one, like :

document.getElementsByName("font_regid")[0].style.color = "#000";

which will select the first in the nodeList (0), or iterate over all of them:

var elems = document.getElementsByName("font_regid");

for (i=0; i<elems.length; i++) {
   elems[i].style.color = "#000";
}

Upvotes: 0

me_digvijay
me_digvijay

Reputation: 5492

Say your element is htmlElement which you get by whatever method you use.

so, the right way to set the font color is htmlElement.style.color='red';

Hope it helps you.

Upvotes: 0

Related Questions