Link to home
Start Free TrialLog in
Avatar of IntercareSupport
IntercareSupport

asked on

Generate random number to SharePoint textbox on page load (JavaScript)

I have a SharePoint 2010 textbox that I need to randomly generate an ID for on page load.  I think the code is good, but I don't think it correctly references the textbox.  The snippet is below, and the full code is attached.  I don't know how to programmatically reference the box, but I pulled the "aspnetForm.person_nbr" from the rendered HTML code.  Ideas?

<SCRIPT TYPE="TEXT/JAVASCRIPT">
_spBodyOnLoadFunctionNames.push("outrnd");
// Random number generator
function rnd(max) {
  var rndnum = max * Math.random()
  rndnum = Math.ceil (rndnum)
  return rndnum
}

// Call random number generator
function outrnd() {
  document.aspnetForm.person_nbr.value = rnd(9999)
}
</SCRIPT>

Open in new window


Original code from http://gwydir.demon.co.uk/jo/javascript/code.htm#random
code.txt
Avatar of COBOLdinosaur
COBOLdinosaur
Flag of Canada image

Assuming aslnetForm is the name of the form and person_nbr is the name of the input then this should work:

document.forms.aspnetForm.person_nbr.value = rnd(9999)

If person_nbr is the id of the input then this should work:

document.getElementById('person_nbr').value = rnd(9999)

If neither works then post the rendered code for the form and we will figure out the correct reference

Cd&
Avatar of Rainer Jeschor
Hi,
could you post at least the part of the generated HTML code from Sharepoint where the textbox is?

Could you use / utilize jQuery?

Thanks
Rainer
Avatar of IntercareSupport
IntercareSupport

ASKER

I tried using...
document.getElementById('person_nbr').value = rnd(9999)
...and no change.

Attached is the HTML output and screenshot, and I yes, I can use jQuery.  Thanks.
code.txt
Capture.PNG
ASKER CERTIFIED SOLUTION
Avatar of COBOLdinosaur
COBOLdinosaur
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That was it!  Thanks!

//Final code
<SCRIPT TYPE="TEXT/JAVASCRIPT">
_spBodyOnLoadFunctionNames.push("outrnd");
// Random number generator
function rnd(max) {
  var rndnum = max * Math.random()
  rndnum = Math.ceil (rndnum)
  return rndnum
}

// Call random number generator
function outrnd() {
  document.aspnetForm.ctl00$m$g_d4831854_1c77_499d_a129_21a860f66db0$ff21$ctl00$ctl00$TextField.value = rnd(9999)
}
</SCRIPT>