[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

change value of a text input field with javascript

Posted on 2006-05-16
12
Medium Priority
?
4,739 Views
Last Modified: 2007-12-19
i have function that updates the .value of an input text field when it is run.

but when i use dom inspector it doesnt show the updated value for that text input field

also when i put an onchange function for the input field, it never gets called

im testing with firefox

0
Comment
Question by:wrynn
  • 6
  • 3
10 Comments
 
LVL 10

Expert Comment

by:Dennis Maeder
ID: 16692627
Try this. Controls should be named. onchange only happens when the control loses focus. So change something in one box then click the other and watch it change.
D
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<html>
<head>
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-store">
</head>
<body>
<form name='test'>
<input type='text' name='text1' value='test me 1' onchange='text2.value=this.value'>
<input type='text' name='text2' value='test me 2' onchange='text1.value=this.value'>
</form>
</body>
</html>
0
 
LVL 15

Expert Comment

by:dbritt
ID: 16692818
>> when i use dom inspector it doesnt show the updated value for that text input field

I believe the DOM inspector only looks at the original document, not the modified one.


--------------------------------------------------------------------------------------------------------


>> also when i put an onchange function for the input field, it never gets called

The onchange event isn't fired when you set the value of an input through code (programatically)

http://msdn.microsoft.com/workshop/author/dhtml/reference/events/onchange.asp
0
 
LVL 10

Expert Comment

by:Dennis Maeder
ID: 16693039
It seems I didn't correctly parse your four simple declarative statements as a question and that Derek did :)
What he says is quite true. The DOM inspector (like view source) reads the file rather than its current state.
However you can trigger the onchange event from the function. See example below.
D
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<html>
<head>
<script language='javascript'>
function somefun(){
  test_form.text1.onchange()
}
</script>
</head>
<body>
<form name='test_form'>
<input type='text' name='text1' value='test me 1' onchange='text2.value=this.value'>
<input type='text' name='text2' value='test me 2' onchange='text1.value=this.value'>
<input type='submit' onclick='somefun(); return false;'>
</form>
</body>
</html>
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 15

Expert Comment

by:dbritt
ID: 16693065
There's also a way to do it just like he wants (in event-catching style), but I don't know how to do it for Fx, I'm trying to figure out how. This is how you'd handle it in IE:

=================================================

<html>
<head>
      <title>Page</title>

      <script language="JavaScript">

      function runTest()
      {
            document.getElementById("test").value = "foo";
      }

      function propChng(e, o)
      {
            if(!(e && o))
                  return;

            switch(e.propertyName)
            {
                  case "value":
                        alert("Value changed to \"" + o.value + "\"");
                        break;
                  default:
                        break;
            }
      }

      </script>
</head>
<body>

<input type="text" name="test" id="test" value="hi" onpropertychange="propChng(event, this);" />

<input type="button" value="Run Test" onclick="javascript:runTest();" />

</body>
</html>
0
 
LVL 15

Expert Comment

by:dbritt
ID: 16693486
I didn't think Firefox had an equivalent event to IE's onpropertychange, and apparently neither does anyone else (including the W3C page I perused). That said, you could write your pages exclusively for IE (bad choice if Internet pages -- good choice [in my opinion] for intranet pages). You could do as Dennis suggests and call the event explicitly as a function from your script. Or you could have an intervaled check on the element you want to see if it's value has changed (this is a work around, a poor one due to the untracable nature of it's execution, and I would not use it -- but it is available). Another note about the last option is that the intervaled event will fire only after exiting all of the functions currently in the call stack due to IE JScript's single-threaded execution. Fx will execute the interval timeout whenever it gets around to it whether or not it's still inside your other functions. So, DO NOT depend on the timing of this event firing in Fx if you use the interval approach.

Here's an example:

==============================================================

<html>
<head>
      <title>Page</title>

      <script language="JavaScript">

      var oldVals = new Array();

      function main()
      {
            var o1 = document.getElementById("test");
            o1.onvaluechange = myFunc;

            // Be sure to store the initialize the old values
            oldVals[o1.id] = o1.value;

            // "Bind" the checker to this ID
            setInterval("checkValueChanged('test')", 10);
      }
      
      </script>

      <script language="JavaScript">
      function myFunc(o)
      {
            alert(o.id + "'s value changed to \"" + o.value + "\"");
      }

      function runTest()
      {
            document.getElementById("test").value = "foo";
      }

      function checkValueChanged(id)
      {
            var o = document.getElementById(id);

            if(o && o.value != oldVals[id])
            {
                  oldVals[id] = o.value;

                  if(o.onvaluechange)
                        o.onvaluechange(o);
            }
      }

      </script>
</head>
<body onload="main();">

<input type="text" name="test" id="test" value="hi" onpropertychange="propChng(event, this);" />

<input type="button" value="Run Test" onclick="javascript:runTest();" />

</body>
</html>
0
 
LVL 15

Expert Comment

by:dbritt
ID: 16693995
Made a little tweak just so it's a little friendlier to add more fields:

=================================================

<html>
<head>
      <title>Page</title>

      <script language="JavaScript">

      var oldVals = new Array();

      function main()
      {
            addValueListener("test", myFunc);
      }

      function addValueListener(id, func)
      {
            var o = document.getElementById(id);
            o.onvaluechange = func;

            // Store the initialize the old values
            oldVals[id] = o.value;

            // "Bind" the checker to this ID
            setInterval("checkValueChanged('" + id + "')", 10);
      }

      function checkValueChanged(id)
      {
            var o = document.getElementById(id);

            if(o && o.value != oldVals[id])
            {
                  oldVals[id] = o.value;

                  if(o.onvaluechange)
                        o.onvaluechange(o);
            }
      }
      
      function myFunc(o)
      {
            alert(o.id + "'s value changed to \"" + o.value + "\"");
      }

      function runTest()
      {
            document.getElementById("test").value = "foo";
      }

      </script>
</head>
<body onload="main();">

<input type="text" name="test" id="test" value="hi" />

<input type="button" value="Run Test" onclick="javascript:runTest();" />

</body>
</html>
0
 
LVL 15

Expert Comment

by:dbritt
ID: 16694189
I love proving myself wrong :)

Use obj.watch(val, func) for Firefox. I'm working on an example incase you need one. If not, good luck!
0
 
LVL 15

Accepted Solution

by:
dbritt earned 2000 total points
ID: 16694404
OK, here's the example. You need to have the watch event's function return true if you want the value to actually get set on Firefox. This works on IE and Fx. It does not respond to user changes in the field in Fx but can be modified to either limit IE from handling user changes or to additionally call the handler from a onkeydown or onpaste event on the fields in Fx (but be sure to not execute twice for IE!). Enjoy! ^^

==============================================

<html>
<head>
      <title>Page</title>

      <script language="JavaScript">

      function main()
      {
            var test = document.getElementById("test");

            test.onpropertychange = myFunc;

            if(test.watch)
                  test.watch("value", callPropChange);
      }
      
      function callPropChange(prop, oldVal, newVal)
      {
            if(this.onpropertychange)
                  if(!(this.onpropertychange(this, prop, oldVal, newVal)))
                        return oldVal;

            return newVal;
      }

      function myFunc(obj, prop, oldVal, newVal)
      {

            if(obj == null
            && window.event
            && window.event.srcElement
            && window.event.propertyName
            && window.event.getAttribute)
            {
                  obj = event.srcElement;
                  prop = event.propertyName;
                  newVal = obj.getAttribute(prop);
            }
            
            if(prop == "value")
            {
                  alert(obj.id + "'s value has been set to \"" + newVal + "\"");
            }
            
            return true;
      }

      function runTest()
      {
            document.getElementById("test").value = "foo";
      }

      </script>
</head>
<body onload="main();">

<input type="text" name="test" id="test" value="hi" />

<input type="button" value="Run Test" onclick="javascript:runTest();" />

</body>
</html>
0
 

Author Comment

by:wrynn
ID: 16694810
thanks for the responses guys i will take a look at these tonight
0
 
LVL 10

Expert Comment

by:Dennis Maeder
ID: 16694831
What Derek's function set gets you is a completely generalized solution which is applicable to any situation. Nice work!
D
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question