Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java Script Text box Name Doesn't like

I don't want to change my text box name in Form because it' using some where else in program.

Problem is JavaScript doesn't like my textbox name (m4j-117). it's Considering "-" as minus.

How can I make it work with out change my text box name.

Thanks

Any help will be appreciate.

Here is my Sample Code.

 <form name="randform">
 <body>
 <script language="javascript" type="text/javascript">



 function randomString() {
   var chars = "0123456789";
   var string_length = 8;
   var randomstring = '';
   for (var i=0; i<string_length; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(rnum,rnum+1);
    }
    document.randform.m4j-117.value = "P"+randomstring;
}
</script>


<input type="button" value="Create Random String" onClick="randomString();">&nbsp;
<input type="text" name="name" value="value" onblur="randomString();;"/>
<input type="text" name="m4j-117" value="">
</body>
</form>
like image 202
krish kim Avatar asked Jan 21 '26 18:01

krish kim


2 Answers

How about:

document.getElementsByName("m4j-117")[0].value = "P"+randomstring;

From a specific form:

document.randform.elements["m4j-117"] = "P"+randomstring;
like image 129
Gabe Avatar answered Jan 23 '26 06:01

Gabe


document.randform['m4j-117'].value

Relying on names is a bit antiquated though; I'd suggest giving it an ID and using document.getElementById directly, or using querySelector with an appropriate ID for the form

like image 45
Explosion Pills Avatar answered Jan 23 '26 08:01

Explosion Pills