Forum Moderators: open

Message Too Old, No Replies

how to change text in an input box?

         

lli2k5

6:54 am on Sep 26, 2006 (gmt 0)

10+ Year Member



I read about this before, but I can't find it anymore. Is there a way to change the text in an input type=text onclick a link?

DrDoc

6:59 am on Sep 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



... you need to change the
value
property of the input.

lli2k5

7:03 am on Sep 26, 2006 (gmt 0)

10+ Year Member



Yeah, its value and encapsulated in single quotes.

penders

8:34 am on Sep 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



To access the forms[] array to change the value property of the input element (as DrDoc mentioned):

<a href="#" onclick="document.forms['name_of_form'].name_of_input.value = 'mynewvalue'; return false;">

The

value
property of the <input> element does not contain the single quotes (in this case).

The

name_of_form
and
name_of_input
values correspond to the values of the
name
attributes on your form and input elements respectively.

Fotiman

4:41 pm on Sep 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I would use the Yahoo UI Library to attach the event handler. But assuming you're not using that library, here's how I'd do it otherwise.

Assuming the following HTML:


<form name='yourForm' action="">
<div>
<input type='text' name='yourInput' id='yourInput' value='Hello World'>
<a href='#yourInput' id='yourLink'>Change the world!</a>
</div>
</form>

Define the following script in the head of your document to keep it unobtrusive:


<script type="text/javascript">
// Assign the value to the input with the id passed in
function changeTheWorld( idRef, val ) {
// Make sure browser supports getElementById
if(!document.getElementById ) return;
// Find the input by it's id
var inputObj = document.getElementById( idRef );
if( inputObj ) {
// Update the value
inputObj.value = val;
}
}
// Attach all of the behaviors requiured on the page
function attachBehaviors() {
// Make sure browser supports getElementById
if(!document.getElementById ) return;
// Find the link by it's id
var linkObj = document.getElementById( 'yourLink' );
if( linkObj ) {
// Attach the onclick handler
linkObj.onclick = function() {
changeTheWorld( 'yourInput', 'Hello Dolly' );
};
}
}
// Define the onload method and tell it to attachBehaviors
window.onload = function() {
attachBehaviors();
};
</script>

Just a different approach. :-)

rocknbil

7:45 pm on Sep 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Foitman, has anyone told you lately you kick-A? :-)

if (post.value==Foitman) { bookmark(this); return true; }

Fotiman

2:50 pm on Sep 27, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hahaha... thanks rocknbil. :-)