/    Sign up×
Community /Pin to ProfileBookmark

Setting an Initial Value of a Form – randomly!

I am trying to figure out how to have Javascript pick a random option from a list or however and then set that option as the Initial Value of a Form Element

For example… Open the site and a form is there. First box is Name, but the Name box has an initial value of Steve, which was randomly selected from a list…

Is this possible? It sounds a bit weird but i think it can be done!

ANY help would be most appreciated!!
I am very new to Javascript though I have a good knowledge of HTML
Thanks
-nanascalala

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@JonaJul 27.2005 — [font=Trebuchet MS]Yea, just setup an array of names, then when the page loads, assign the value of that input element to a random array value.[/font]

<i>
</i>&lt;script type="text/javascript"&gt;&lt;!--
var names = ['Bob', 'Erin', 'Alex', 'Amy', 'Mike', 'Steve'];
onload = function(){
document.forms['form_name'].elements['input_name'].value = Math.floor(Math.random()*names.length)+1;
}
//--&gt;&lt;/script&gt;


<i>
</i>&lt;form name="form_name" ... &gt;
...
&lt;input type="text" name="input_name" ... &gt;
...
&lt;/form&gt;
Copy linkTweet thisAlerts:
@Mr_JJul 27.2005 — Do you mean like this

[code=php]<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
<script type="text/javascript">
<!--

list=new Array()
list[0]="Steve"
list[1]="Fred"
list[2]="Wilma"
list[3]="Barney"
list[4]="betty"

function randomSelect(){
rdmNum=Math.floor(Math.random()*list.length)
document.forms["f1"].value=list[rdmNum]
}

//-->
</script>
</HEAD>
<BODY onload="randomSelect()">

<form name="f1">

<input type="text" name="t1">

</form>

</BODY>
</HTML>[/code]
×

Success!

Help @nanascalala 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.7,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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