We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Need to use javascript to dynamically color <input> controls based upon criteria...

MitchellVII
MitchellVII asked
on
Medium Priority
195 Views
Last Modified: 2012-05-06
Hi,

I have a web page that uses many input fields for the user to provide me with data.  When the user loads the form, it interacts with a mySQL DB to get what values we have a leaves the other <inputs> blank or zero value.

What I want to do is have some code so that all of the fields which have no value (or 0) will show a light blue background when the user loads the form.  All fields with values will have a white background.

Also, after the user updates the field, if the value is not null (or 0), the field background should turn from light blue to white.

I am just trying to give a better visual cue as to which fields will need to be completed.  We can use JS or ASP to do this :)

Here is a sample of a field and the connection ASP:

M
<%
Dim Conn
Dim strConnect
 
strConnect = "DRIVER={MySQL}; SERVER=mysql103.mysite4now.com; DATABASE=ExecDec_Web; USER=asphaltbananas; PASSWORD=blacktar; OPTION=3;"
 
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open strConnect
 
Set rstGroup_Conn = Server.CreateObject("ADODB.Recordset")
rstGroup_Conn.Open "SELECT * " _
    & "FROM grouptable " _
    & "WHERE ProspectID=" & Request.QueryString("ProspectID") & "", Conn
%>
 
<td width=11 class="table_row_solid">
<p style="text-align:center"><span class="arial_7_gray" style="cursor:hand" onclick="JavaScript:menuActivate('Focus1', 'Focus1Div', 'Focus1Combo');playClick()">1</span></p></td>
<td width=91 class="table_row_solid">
<p class="table_input"><input type="text" name="Focus1" id="Focus1" class="grouptext" value="<%response.write rstGroup_Conn.Fields("Focus1").Value%>" onfocus="playClick()" tabindex="103"></p>
<div id="Focus1Div" style="position:absolute;display:none;top:0px;left:0px;z-index:10000" onmouseover="javascript:oOverMenu='Focus1Div';" onmouseout="javascript:oOverMenu=false">
<select name="Focus1Combo" id="Focus1Combo" size="15" class="group" onclick="JavaScript:textSet('Focus1',this.value);" onkeypress="JavaScript:comboKey('Focus1', this);" onchange="playComboSelect()">
<option value="">Select a FOCUS	
<option value="">or enter your own ...	
<option value="">-	
<!--#include file="include\select\it\strSelect_Focus.inc"-->
</select>
</div>
</td>

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Commented:

<script language="javascript">
function setInputStyleColor(inputObj){
 
  if (inputObj.value == '' || inputObj.value=='0'){
    inputObj.style.backgroundColor='#E1F1F6';
  }else{
    inputObj.style.backgroundColor='#FFFFFF';
  }
}
</script>
<form>
<input  class="inputStyle" name="mobile" onKeyUp="setInputStyleColor(this);" ></td></tr>
</form>

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Thanks fsze,

That works.  How about if i wanted to create some JS that would cycle through all of my inputs on the form OnLoad and color them based upon the same crtieria?

In Visual Basic I would use a For...Until, but I don;t know how to do it in JS.
CERTIFIED EXPERT

Commented:
try to place function updateAllInputStyle(e) in your js file.....
and fire it by onkeyup event on form that you want....
<script language="javascript">
/*
function setInputStyleColor(inputObj){
 
  if (inputObj.value == '' || inputObj.value=='0'){
    inputObj.style.backgroundColor='#E1F1F6';
  }else{
    inputObj.style.backgroundColor='#FFFFFF';
  }
}
*/
function updateAllInputStyle(e){
  if(window.event) // IE
        {
        keynum = e.keyCode;
        ctrlKey  = e.ctrlKey;
        EventObj = e.srcElement;
 
        }
  else if(e.which) // Netscape/Firefox/Opera
        {
        keynum = e.which;
        ctrlKey = e.ctrlKey;
        EventObj = e.target;
 
        }
  if (EventObj.nodeName == 'INPUT' && (EventObj.value == '' || EventObj.value=='0')){
    EventObj.style.backgroundColor='#E1F1F6';
  }else{
    EventObj.style.backgroundColor='#FFFFFF';
  }
}
 
</script>
<form onkeyup="updateAllInputStyle(event);">
<input   name="mobile"  style="background:#E1F1F6"></td></tr> <!--onKeyUp="setInputStyleColor(this);"-->
<input   name="mobile2"  style="background:#E1F1F6" ></td></tr> <!--onKeyUp="setInputStyleColor(this);"-->
</form>

Open in new window

CERTIFIED EXPERT

Commented:
more reference about node
https://developer.mozilla.org/En/DOM/Node

Author

Commented:
fsze,

Well, the values in my inputs are being loaded from a mySQL DB using ASP.  So when the form loads, it doesn't really know the values of the fields until:

<%
Dim Conn
Dim strConnect

strConnect = "DRIVER={MySQL}; SERVER=mysql103.mysite4now.com; DATABASE=ExecDec_Web; USER=asphaltbananas; PASSWORD=blacktar; OPTION=3;"

Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open strConnect

Set rstGroup_Conn = Server.CreateObject("ADODB.Recordset")
rstGroup_Conn.Open "SELECT * " _
    & "FROM grouptable " _
    & "WHERE ProspectID=" & Request.QueryString("ProspectID") & "", Conn
%>

fires.  So I guess I need something that will color all of the 'empty' controls for me after the db values have loaded.  Will this code you have for me do that?

Author

Commented:
Where do I place updateAllInputStyle(e), within the <body> tag?  Also, what value do I pass to it as the (e) argument?
CERTIFIED EXPERT

Commented:
tested on ie6,ff3
run initAllInputStyle() js function from body onload.. It should works
<script language="javascript">
function initAllInputStyle(){
  cn = document.form1.childNodes;
//  alert(cn.length);
 
  for (var i = 0; i < cn.length; i++){
//    alert(cn[i].nodeName + " " + cn[i].type + " " + cn[i].value);
    if (cn[i].nodeName == 'INPUT' && cn[i].type=="text" ){
      if (cn[i].value =="" || cn[i].value =="0"){
        cn[i].style.backgroundColor='#E1F1F6';
      }else{
        cn[i].style.backgroundColor='#FFFFFF';
      }
    }
  }
 
}
 
function updateAllInputStyle(e){
  if(window.event) // IE
        {
        keynum = e.keyCode;
        ctrlKey  = e.ctrlKey;
        EventObj = e.srcElement;
 
        }
  else if(e.which) // Netscape/Firefox/Opera
        {
        keynum = e.which;
        ctrlKey = e.ctrlKey;
        EventObj = e.target;
 
        }
  if (EventObj.nodeName == 'INPUT' && (EventObj.value == '' || EventObj.value=='0')){
    EventObj.style.backgroundColor='#E1F1F6';
  }else{
    EventObj.style.backgroundColor='#FFFFFF';
  }
}
 
</script>
 
<body onload="initAllInputStyle();">
<form onkeyup="updateAllInputStyle(event);" name="form1">
<input  type="text" name="mobile"  style="background:#E1F1F6" value="100"></td></tr> <!--onKeyUp="setInputStyleColor(this);"-->
<input  type="text" name="mobile2"  style="background:#E1F1F6" ></td></tr> <!--onKeyUp="setInputStyleColor(this);"-->
</form>
</body>

Open in new window

CERTIFIED EXPERT

Commented:
updateAllInputStyle(e)? placed in <form> tag fire on onkeyup event...
what's e? event Object, it will be fired by system..
what value do I pass to it as the (e) argument? nothing, e is predefined event object parameter from system...
more reference
https://developer.mozilla.org/En/DOM/Event
CERTIFIED EXPERT

Commented:
js function initAllInputStyle is setting background color all of input tag with type text depend on the value (body onload event, it should fine and fired after loading data from database)
js function updateAllInputStyle used for update background color for the one of input tag with type text when that tag onkeyup event....
updateAllInputStyle ? may be wrong naming and make you misunderstanding.. may be named updateEventInputStyle is better..

I hope you can understanding ....

Author

Commented:
Ok, as far as I can tell, this is doing nothing.  One of the problems may be that my Input Values are not ' ', but rather Null.  How would we change the code to test for Null Value instead of ' ' Value?

Also, I guess I don't understand how calling something on "onkeyup" is going to change the backgrounds of all the null textboxes when the page loads.  Doesn't onkeyup fire after the user releases a key?
CERTIFIED EXPERT

Commented:
How would we change the code to test for Null Value instead of ' ' Value? add a condition  EventObj.value==null
#23608096 line 34 : if (EventObj.nodeName == 'INPUT' && (EventObj.value == '' || EventObj.value=='0' || EventObj.value==null)){

Doesn't onkeyup fire after the user releases a key? It does..
your can test it by
<form onkeyup="alert('keyup');" name="form1">
instead of
<form onkeyup="updateAllInputStyle(event);" name="form1">

change the backgrounds of all the null textboxes ?  It change the background ONE of input tag only, not all
I may given wrong naming of updateAllInputStyle function, it should be named updateEventInputStyle. It may make you confused.
*updateEventInputStyle function is fired whenever ONE of input tag is keyup*

e.g. if you keyup at ONE of input tag named mobile, this event fire updateEventInputStyle function and change and background of input tag named mobile only... NOT effected on input tag mobile2
if you keyup at ONE of input tag named mobile2, this event fire updateEventInputStyle function and change and background of input tag named mobile only... NOT effected on input tag mobile

at <form onkeyup="updateAllInputStyle(event);" name="form1">
It will fire js function updateAllInputStyle (should be named updateEventInputStyle) from any ONE elements  from the form1 after keyup
EventObj = e.target;EventObj = e.srcElement; depended on IE/FF get the element(ONE of input tag) is firing this event.
again, EventObj is ONE of element from form1 and change that element background to be '#E1F1F6' by
EventObj.style.backgroundColor='#E1F1F6';

1) initAllInputStyle() function is initial function will change all the input tag background depend on the value of each element (input tag) when body onload ONLY

2) each of input tag is changing background by an event updateAllInputStyle as stated above....
keep a times to understood...

Author

Commented:
fsze,

Maybe I wasn't clear intially.  I need some code that will go through all of the textboxes on my form (over 50 of them) and set the style=background of them to light blue if the mySQL value of the field is null.  So when the user opens the form, the fields that need to be updated are highlighted and the ones that have data already are just white.

Maybe a For... clause would work better?
CERTIFIED EXPERT

Commented:
it should does by initAllInputStyle() function in body tag onload event

Author

Commented:
But won;t I have to change some of the coding in  initAllInputStyle()  if I am going to call it from the onload event in the <body> tag?
CERTIFIED EXPERT

Commented:
But won;t I have to change some of the coding in  initAllInputStyle()  ?
change it back to orginal one (I posted #23608096)
Also did you try code snippet from #23608096, it works everythings fine.
I already given an example what you needs and fully explained how it works

If you needs to run another javascript from body tag onload event. please create another function to handle it.
If any other question please open a new question...

Author

Commented:
fsze,

I could never get your overall solution to work for me; however, the solution for use when typing in individual fields works a charm so I'll award points for that.

i did come up with a whole form solution on my own that I will post here for the benefit of future viewers:

ANOTHER BETTER SOLUTION:
As is often the case, while researching this solution, I discovered a better way to do it anyway - i.e., just to have some JS which cycles through the whole form OnLoad and assigns background colors to all the NULL fields.  Same effect, MUCH less coding.

Here is the function I cobled together to do that:

function elmLoop(){
var theForm = document.forms[0]

for(i=0; i<theForm.elements.length; i++)
      {
            if(theForm.elements[i].type == "text" && theForm.elements[i].value.length == 0)
            {
                  theForm.elements[i].style.backgroundColor='#EBEBF5';
            }
            else if(theForm.elements[i].type == "select-one" && theForm.elements[i].value == 0)
            {
                  theForm.elements[i].style.backgroundColor='#EBEBF5';
            }
      }
}      

and you call it with an OnLoad element within the <body> tag, like so:

<body lang=EN-US style="margin:4pt;margin-top:3pt;background-color:#F7F7F7" onload="elmLoop()">

Anyway, works like a charm and I don't have top screw with the ASP for every input.
CERTIFIED EXPERT

Commented:
MitchellVII,
did you seem the function of initAllInputStyle()?
Actually, it is extremely similar to your's one....
I am happy to received grade A from you....
BUT, I hope really solved your problem.....
Also did you tried run initAllInputStyle() on body tag onload event?
I am surprising and heartfelt you really solved your problem already... hopeful by my initAllInputStyle() function.....
hum..... nothing to say.... hum..... hope you satisfied
Good lucks

function initAllInputStyle(){
  cn = document.form1.childNodes;
//  alert(cn.length);
 
  for (var i = 0; i < cn.length; i++){
//    alert(cn[i].nodeName + " " + cn[i].type + " " + cn[i].value);
    if (cn[i].nodeName == 'INPUT' && cn[i].type=="text" ){
      if (cn[i].value =="" || cn[i].value =="0"){
        cn[i].style.backgroundColor='#E1F1F6';
      }else{
        cn[i].style.backgroundColor='#FFFFFF';
      }
    }
  }
 
}

Open in new window

Author

Commented:
fsze,

I couldn't get your function to work for me as far as changing all controls on the page.  that's not to say it wasn't a good solution - I may have just been using it wrong since i am quite new too all this stuff.

However, your solution works perfectly when it comes to making changes on individual controls, so that's why I gave the points ;)

Thanks again!
CERTIFIED EXPERT

Commented:
okey...
may be cause of the form name is different. I am using the name *form1*
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.