Click to See Complete Forum and Search --> : Dynamic assignment of input values


Padrill
06-25-2003, 04:17 AM
How can I assign the value of a Javascript variable to the value of an input field?

something like
<INPUT name="Phone" value="phoneVariable">

Thanx

Gopinath
06-25-2003, 04:28 AM
<script language="Javascript">
var phoneno=12121212
</script>

<html>
--
--
<form>
<input type="text" name="phoneno" value="+phoneno+">
</form>
--
</html>

Padrill
06-25-2003, 04:35 AM
<input type="text" name="phoneno" value="+phoneno+">

Excuse me, but this doesn't make any sense.

Did you mean?

document.write('<input type="text" name="phoneno" value="' + phoneno + '">');

I'm trying to avoid that.

Charles
06-25-2003, 04:46 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>
<script type="text/javascript">
<!--
onload = function () {document.king.tut.value = 'Son of Amonhoteph IV'}
// -->
</script>
<form action="" name="king">
<div>
<input type="text" name="tut">
</div>
</form>

Padrill
06-25-2003, 04:51 AM
Many Thanx,

But is this the only way? Any other suggestions?

requestcode
06-25-2003, 06:53 AM
The example Charles gave will set the value of the form element when the page loads. If you want to do it as part of a function that gets performed when some other action takes place then you can have one like this:
function setValue()
{
document.form_name.Phone.value="some text"
}

You could also set the value to a value in a variable like this:
x="some text"
document.form_name.Phone.value=x

Maybe if you gave us some more details on what you are attempting to accomplish we could give you a more detailed explanation.

Gopinath
06-25-2003, 08:21 AM
html code

<input type="text" id="phone_no" value="">


JS file

function fun1()
{
var x="123456"
document.getElementById("phone_no").value=x
}

it is compatible for ie and nn

pyro
06-25-2003, 08:30 AM
Originally posted by Gopinath
it is compatible for ie and nn Only in IE5+ and NN6+... You are much better off referencing form via Charles method...

Vladdy
06-25-2003, 08:53 AM
Nope, getElementById is THE COMPLIANT method of accessing page elements.
And while name attribute is a part of HTML4.01 spec, it is included for backward compatibilty only. Applications should use id attribute to identify page elements.

Charles
06-25-2003, 09:16 AM
Originally posted by Vladdy
Nope, getElementById is THE COMPLIANT method of accessing page elements. Both are complient and perfectly valid JavaScript. The just use different document object models (DOM). My example uses the better supported Netscape DOM and Gopinath's method uses the morally superior W3C DOM.