how to pass the javascript variable to textbox?
i would like to ask a question.
how can i pass the javascript generated code to the textbox "code" ?
I surf the internet but I cannot find the answer
I hope all of you can help me.
thanks!!
<form&开发者_开发技巧gt;<input name="code" type="text" value="" >
<script>
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for( var i=0; i < 6; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
alert(text);
return text;
}
</script>
<input type="button" style="font-size:9pt" value="Generate Code" onclick="makeid()">
</input></form>
You have to set the value of the text box, rather than returning the value
The updated code,
var codeElem = document.getElementById('code');
function makeid() {
var text = "", possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", i = 0;
for( ; i < 6; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
//alert(text);
codeElem.value = text;
}
You've to add an id
attribute to the text box, so that it can be accessed easily.
<input id="code" name="code" type="text" value="" >
Working example
You need to set that textbox's value
value. If its id
was code
, you could just do this:
document.getElementById('code').value = text;
But as it stands, you'll have to cycle through all inputs to look for it:
var inputs = document.getElementsByTagName('input'),
i = inputs.length;
while (i) {
i -= 1;
if (inputs[i].name === 'code') {
inputs[i].value = text;
break;
}
}
The following code change for the two input fields will cause the random string to appear in the input text field, in addition to the alert box:
<input name="code" id="code" type="text" value="" >
<!-- original javascript code goes here-->
<input type="button" style="font-size:9pt" value="Generate Code"
onclick="document.getElementById('code').value = makeid()">
精彩评论