/    Sign up×
Community /Pin to ProfileBookmark

use java script variable in form fields

Hi,

I would like to generate a random number and then display that number as the initial value in a form input field.

Example:

<SCRIPT LANGUAGE=”JavaScript”>
var rand_no = Math.random();
rand_no = rand_no * 100;
rand_no = Math.ceil(rand_no);
</SCRIPT>

Now generate the field with the value of the random number:
<p>
<input readonly type=”text” name=”ranNum” value=”<%=rand_no%>”>
</p>

This does not work. Can anyone suggest what has to be done to get it to work.

Alternatively is it possible to just write the value using something like:

<p>
“<%=rand_no%>”
</p>

Many thanks

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@JPnycDec 30.2010 — Give the input an ID like maybe myInput or whatever:



{

var i=Math.floor(Math.random()*100);

document.getElementById('myInput').value=i;

}

Or, if you don't want to give it an ID, you can reference it by name or by its place in the elements array. document.forms[0].elements['ranNum'];

Since the code is not inside a function it will execute on page load. Alternatively you could put it into a function and call it on load.
Copy linkTweet thisAlerts:
@PeterVincentauthorDec 30.2010 — Thanks JPnyc,

I have implemented what I believed was what you provided. This does not work.

My code is:

<SCRIPT LANGUAGE="JavaScript">

var rand_no = Math.random();

rand_no = rand_no * 100;

rand_no = Math.ceil(rand_no);

document.getElementById('myInput').value=rand_no;

</SCRIPT>

<!-- Start code for the form-->

<form ...

...

...

<p>

<input readonly type="text" name="ranNum" value='myInput'>

</p>

...

...

</form>

When I load the page the contents of the text field is myInput.

Please advise how I should use the info that you provided.

Thanks again,

PeterVincent
Copy linkTweet thisAlerts:
@JPnycDec 30.2010 — You designated that here: value='myInput', that must be removed. Just replace everything you have with the following:

<script type="text/javascript">

//<![CDATA[

{

var i=Math.floor(Math.random()*100);

document.forms[0].elements['ranNum'].value=i;

}

//]]>

</script>
Copy linkTweet thisAlerts:
@PeterVincentauthorDec 30.2010 — Thanks again JPnyc.

It works.

I had to copy the javascript to within the <form> ...</form> block as below, I am assuming this is the correct way to implement it.

<!-- Start code for the form-->

<form...

<p>
<input readonly type="text" name="ranNum">
</p>


<script type="text/javascript">

//<![CDATA[

{

var i=Math.floor(Math.random()*100);

document.forms[0].elements['ranNum'].value=i;

}

//]]>

</script>

.

.

.

.

</form>
Copy linkTweet thisAlerts:
@JPnycDec 30.2010 — Actually you're correct. Because I didn't use a function and the on load event handler, the script would render in the browser before the element being referenced. That would throw an exception. Mea Culpa. Anyway I'm glad it works.
Copy linkTweet thisAlerts:
@PeterVincentauthorDec 31.2010 — Hi JPnyc,

Really delighted that this is working, thank you.

I am looking for some additional info:

document.forms[0].elements['ranNum'].value=i;

Does this translate to:

The value of the input field with the name ranNum in the first form in the page becomes equal to the value of the variable named i?

So if for example I had two forms and I wanted to poke into an input variable I would use document.forms[1] ...... ?


Additionally I have searched your forums for info on //<![CDATA[ without success. I did find a page located elsewhere http://javascript.about.com/library/blxhtml.htm

It suggests that the code to provide compatibility with older browsers be provided with /* like:


<script type="text/javascript">

/* <![CDATA[ */

// content of your Javascript goes here

/* ]]> */

</script>

What do you think?

Thanks,

PeterVincent
Copy linkTweet thisAlerts:
@PeterVincentauthorJan 14.2011 — Hi,

I am having a bit of bother getting this to work the way I want.

The problem is that once the form is posted and the browser back button is pressed it goes back to the form but the values of ="ranNum1", "ranNum2" and "sumOf" while changed in the //<![CDATA[ script they are not changed in the form.

I reckon I need some sort of a refresh for the input fields for: "ranNum1", "ranNum2" and "sumOf".

[CODE]
<script type="text/javascript">
//<![CDATA[
{
var i=Math.floor((500-99)*Math.random()) + 100;
var j=Math.floor((500-99)*Math.random()) + 100;
document.forms[0].elements['ranNum1'].value=i;
document.forms[0].elements['ranNum2'].value=j;
document.forms[0].elements['sumOf'].value=i+j;
[COLOR="Red"] //magic refresh in next line
refreshForm(document.forms[0]);[/COLOR]}
//]]>
</script>
[/CODE]



Follows is the extract of code that I am using in the form.

In the extract of code below I have the inputs for "ranNum1", "ranNum2" and "sumOf" as DISABLED and in <td></td>, that is only so that I can see what is going on. If I can get this to work these will be changed to type HIDDEN.


[CODE]
<body>
<form method="post" name="myemailform" action="form-to-email.php">

<table width="800" border="1" align="center" cellspacing="1" cellpadding="1">



<tr>
<td><input DISABLED TYPE=TEXT name="ranNum1" id="ranNum1" size="10"></td>
<td><input DISABLED TYPE=TEXT name="ranNum2" size="10"></td>
<td><input DISABLED TYPE=TEXTN name="sumOf"></td>
</tr>

<script type="text/javascript">
//<![CDATA[
{
var i=Math.floor((500-99)*Math.random()) + 100;
var j=Math.floor((500-99)*Math.random()) + 100;
document.forms[0].elements['ranNum1'].value=i;
document.forms[0].elements['ranNum2'].value=j;
document.forms[0].elements['sumOf'].value=i+j;
}
//]]>
<tr>
<td colspan="6">Anti Spam Measure<font color=red> *</font></td><td colspan="5" align="right"><script>document.write(document.forms[0].elements['ranNum1'].value + ' + ' + document.forms[0].elements['ranNum2'].value + ' = ');</script></td><td colspan="5"><input type="text" name="antiSpamCode"></td>
</tr>

<tr>
<td colspan="16"><input type="submit" name='submit' value="submit"></td>
</tr>

</table>

</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("myemailform");
frmvalidator.addValidation("antiSpamCode","numeric", "Invalid Input for Anti Spam Code:");
frmvalidator.addValidation("sumOf", "eqelmnt=antiSpamCode", "The Anti Spam code does not match");

</script>

</body>
</html>
[/CODE]


Any suggestions?

Many thanks.
Copy linkTweet thisAlerts:
@PeterVincentauthorJan 14.2011 — sorry,

Meant to say that I only want to refresh the inputs in the form for "ranNum1", "ranNum2" and "sumOf".

The other fields which are not in the code extract should not be cleared.

Here is the us of the magic refresh

[CODE]
<script type="text/javascript">
//<![CDATA[
{
var i=Math.floor((500-99)*Math.random()) + 100;
var j=Math.floor((500-99)*Math.random()) + 100;
document.forms[0].elements['ranNum1'].value=i;
document.forms[0].elements['ranNum2'].value=j;
document.forms[0].elements['sumOf'].value=i+j;
[COLOR="Red"][B][I]//magic refresh in next 3 lines
refreshFormElement(document.forms[0].elements['ranNum1'].value);
refreshFormElement(document.forms[0].elements['ranNum2'].value);
refreshFormElement(document.forms[0].elements['sumOf'].value);[/I][/B][/COLOR]}
//]]>
</script>

[/CODE]


Thanks.
×

Success!

Help @PeterVincent spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...