Jump to content

SuperNewbie - Trying to pass a value from an input text box to a js function


DocGrimwig

Recommended Posts

Hello:

 

Below I successfully created a random string generator in js. As you can see, to verify it worked,I logged the output to the console. Now I have tried for hours to do something I thought was incredibly easy, and it probably would be if it weren't I trying to author it :-0

 

Commented out is the latest of my attempts to do so. The live code works correctly.

 

<!doctype html><html><head><meta charset="utf-8"><title>Random String</title></head><body><!-- <h3>Please input a number to represent how long of a string you wish to randomly create</h3><input name= "userInput" id="userInput" maxlength="2"><button type="submit" onClick="createString()">Submit</button> <p id="output"></p>--><script>//Create function that will produce a random string from a supplied set of characters.function createString(n)  {  //Declare String Variable.var text = "";// n =  [];//List of characters to be drawn fromvar char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";  //Loopfor(var i=0; i < n; i++ )  {     text += char_list.charAt(Math.floor(Math.random() * char_list.length));  }  //Return the value of the function to the var "test"return text;  }  //Display the value of the returned random string to the console.  Call the function with a parameter n of 10console.log(createString(10));  //document.getElementById("output").innerHTML= createString();</script></body></html>
Can you help!
Thanks so much,
Doc
Link to comment
Share on other sites

var n will be inside the function

var n = document.getElementById('userinput').value

it is no longer required as a argument which was done manually, it retrieves the value on the click event of button from the input with specific id then it is processed as it was originally, if you want it in console.log add 'console.log(text);' before return.

 

Edit: actually you don't need the return either but document.getElementById("output").innerHTML= text;

Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

My version...

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>Random String</title><style>p{font-weight:bold;color:red}</style><script>window.onerror = function(a,b,c){alert('Javascript Error: '+a+'nURL: '+b+'nLine Number: '+c);return true;}</script><script>'use strict';function init() {  document.getElementById('btn1').onclick = run;}function run(){  var usrn = document.getElementById('userN').value;  var txt = createString(usrn);  document.getElementById("output").innerHTML = txt; }//end functionfunction createString(n){ var m = parseInt(n); var text = ''; var char_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';   var len = char_list.length; var rand; var prod; if (isNaN(m)){   text = 'input error: not-an-integer'; }else if(m<0){   text = 'input error: negative'; }else if(m==0){   text = 'input error: zero'; }else{   for(var i=0; i < m; i++ ){     rand = Math.random();     prod = Math.floor(rand * len);     text += char_list.charAt(prod);     }   } console.log('input of ['+n+'] produced ['+text+']');  return text;}// end functionwindow.onload = init;</script></head><body><h3>Please input a number to represent how long of a string you wish to randomly create:</h3><input type="text" id="userN" maxlength="2"/><input type="button" id="btn1" value="Submit"/> <p id="output"></p></body>    </html>
  • Like 1
Link to comment
Share on other sites

Wow. This is so readable and helps me immensely to understand the flow. Thanks, Dave.

 

dsonesuk, I'm not saying yours isn't, but I am saying that I am so new to this stuff, that your explanation goes right over the top of my head. I'm just barely above the level of "See Spot run. Run Spot run " (A children's book in case you're not from a country or a time when this book was in use teaching children to read :-)

 

Dave and ds, for the sake of my education, is there not a simpler way than having to break the script down into 3 functions? For example, is it possible to include init and run within createString?

 

Thanks so much both of you!!!!

Doc

Link to comment
Share on other sites

Davej extra functions are because he has used the unobtrusive method of separating the JavaScript onclick event from the html making it more manageable and error reporting code you don't really need, but because the targeted element must be rendered first he decided to use window.onload to wait for page to be fully rendered before applying the onclick event, but the code could have been placed directly below the targeted element which would mean the window.onload would not be required. Placing below targeted element has become the preferred method as linking to and loading a external large js file/s can slow the rendering of a page when placed in <head>...</head> or amongst and midway within html, but when placed just before </body> tag the page renders the previuos html before the hinderence of loading large js files occurs.Your original code is calling the function and setting parameter value usingcreateString(10)Which returns the text directly in this case to the console log, this approach will only work as it is by using possibly onkeyup event on input itself where it will retrieve the value directly from itself and use as parameter within function called when use releases a keypress, this is more complicated but!Because you are using button to trigger the function call and sending the returned text to another location and not its present location you need1) a user to input value2) user to click button3) function to find input value using id, process and then place result within set location using another id.With your first code example

<!doctype html><html><head><meta charset="utf-8"><title>Random String</title></head><body><h3>Please input a number to represent how long of a string you wish to randomly create</h3><input name= "userInput" id="userInput" maxlength="2"><button type="submit" onclick="createString()">Submit</button> <p id="output"></p><script>//ideally ALL placed in external file and linked to//Create function that will produce a random string from a supplied set of characters.//function createString(n)  parameter not required as not passing value from current input but calling function on submit button input 'onclick="createString()" ' to get value from a different inputfunction createString(){  //Declare String Variable.var text = "";var n = document.getElementById('userInput').value //amended by dsonesuk//List of characters to be drawn fromvar char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";  //Loopfor(var i=0; i < n; i++ )  {     text += char_list.charAt(Math.floor(Math.random() * char_list.length));  }  //Return the value of the function to the var "test"//return text;  not returning text to current location but different element so use its id as belowdocument.getElementById('output').innerHTML=text; //added by dsonesuk//Display the value of the returned random string to the console. console.log(text);}  //Display the value of the returned random string to the console.  Call the function with a parameter n of 10//console.log(createString(10));  //document.getElementById("output").innerHTML= createString();</script></body></html>

Unobtrusive method

<!doctype html><html><head><meta charset="utf-8"><title>Random String</title></head><body><h3>Please input a number to represent how long of a string you wish to randomly create</h3><input name= "userInput" id="userInput" maxlength="2"><button type="submit" id="btn1">Submit</button> <!--amended by dsonesuk --><p id="output"></p><script>document.getElementById('btn1').onclick = createString; //added by dsonesuk//Create function that will produce a random string from a supplied set of characters.//function createString(n)  parameter not required as not passing value from current input but calling function on submit button input 'onclick="createString()" ' to get value from a different inputfunction createString(){  //ideally ALL placed in external file and linked to//Declare String Variable.var text = "";var n = document.getElementById('userInput').value //amended by dsonesuk//List of characters to be drawn fromvar char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";  //Loopfor(var i=0; i < n; i++ )  {     text += char_list.charAt(Math.floor(Math.random() * char_list.length));  }  //Return the value of the function to the var "test"//return text;  not returning text to current location but different element so use its id as belowdocument.getElementById('output').innerHTML=text; //added by dsonesuk//Display the value of the returned random string to the console. console.log(text);}  //Display the value of the returned random string to the console.  Call the function with a parameter n of 10//console.log(createString(10));  //document.getElementById("output").innerHTML= createString();</script></body></html>
Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

dsonesuk...What an incredible gift you have given me. Thank you. I know that all of your Moderating takes up a great deal of time an effort, and so I want to say how appreciative I am of the time spent educating me. This was undoubtedly the best teaching on the web!

 

I'm glad to say...I"VE GOT IT!!!

 

-Doc

Link to comment
Share on other sites

Not really! cause I'm not a mod, if i was, half people who come here and don't make effort to learn the basics would be kicked out (remember eduardchille, arrrghh where are the pills), IE that is why i'm not a mod :-)

The new members who want to be a friend, yet i have not had any contact with them through posts, and they haven't made a single post or topic, because.. well! their NEW, gets a instant block, don't take to such nonsense,

again! that is why i'm not a mod :-) power corrupts.

Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...