Search code examples
javajavascriptcssjspstruts

Use Javascript to change text box back colour if wrong, before posting


I want to carry out some validation in javascript before posting, so basically I want to:

  1. Alter textbox value
  2. use Onchange attached to the textbox to fire off a Javascript script.
  3. the script will check that a colon is at the right place in the value.
  4. if that isnt the case, change the textbox back colour to red.
  5. all this is done before secondary validation in the struts form and action.

first problem is I cannot seem to pass the textbox value to the script, is this prevented under struts? second problem is the changing of the back colour of the textbox on error.

<html:text property="date1_1" maxlength="8" value="<%=WeekOne.get(1)%>" size="15" onchange="validateBox(this.value)"/>
<script type="text/javascript">
        function validateBox(textBox)
        {
            alert("here");
            var p = textBox.value();
            alert(p);               
        }
</script>

Solution

  • To solve your problems you need to fix some errors in the code. I will show you what to fix trying to achieve what you've written by numbers.

    1. To alter textbox value you need to pass the textbox element itself not the value.
    2. You already use it
    3. doing some checks in the script against textbox value (value is not a function)
    4. for this you should use background color CSS property of the textbox
    5. assume second validation is on the server, checks are done on the client via javascript

    For example

    <html:text property="floor" styleClass="input" size="30" tabindex="12" onchange="validateBox(this)"/>
    <script type="text/javascript">
      var textBoxBackgroundColor;
      function validateBox(textBox) {
        var p = textBox.value;
    
        if (textBoxBackgroundColor == null)
          textBoxBackgroundColor = textBox.style.backgroundColor;
        //validate
        if (p < 0)
         textBox.style.backgroundColor = '#000000';
        else
          textBox.style.backgroundColor = textBoxBackgroundColor;
      }
    </script>
    

    will check that textbox floor is positive.