How do I send textbox values to javascript function? - javascript

I seem to be doing something wrong here. This script works with the prompts, which have been commented out, but not with the textboxes. Am I somehow failing to send the input values to the function?
I'm also having trouble using regular expressions in the if-statements, rather than a clumsy list of punctuation marks.
<html>
<head>
</head>
<body>
<div id="myTypingText"></div>
<label>Say what you want typed</label>
<input class="textBox" id="userInput" />
<label>A pregnant pause... (300?)</label>
<input type="number" id="userBreath" />
<button onclick="printLooper()" href="javascript:;">Submit</button>
<! --input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" --/>
<script type="text/javascript" language="javascript">
var myString = document.getElementById('userInput').value;
//var myString = prompt('Say what you want to see typed','Right here, baby'); //prompts are annoying, i know
//var myDelay = prompt('Type speed (try 50)', 'The higher the number, the slower it types');
//var myBreath = prompt('Now tell me how long to pause at each breath (shift+2)', 'Try 300')
var myBreath = document.getElementById('userBreath').value;
var myArray = myString.split("");
var loopTimer;
function printLooper(){
if(myArray.length > 0 ){
var char = myArray.shift();
if ( char === '#'){
document.getElementById("myTypingText").innerHTML
}else {
document.getElementById("myTypingText").innerHTML += char;
}
} else {
clearTimeout(loopTimer);
}
if (char === ' '){
loopTimer = setTimeout('printLooper()', 20);
} else if (char === ',' || char === '.' || char === '?') {
loopTimer = setTimeout('printLooper()', 220); //fiddle with these 2nd params as you see fit
} else if (char === '#'){
loopTimer = setTimeout('printLooper()', myBreath);
} else {
loopTimer = setTimeout('printLooper()', 47);
}
}
printLooper();
</script>
</body>
</html>
Any help appreciated!

You need to have some variables inside your function.
I made a demo and removed the inline js on the button.
Use this if useful:
<button id="sub_btn">Submit</button>
var loopTimer;
var char, myString, myBreath, myArray;
function printLooper() {
if (myArray.length > 0) {
char = myArray.shift();
console.log(char);
if (char === '#') {
document.getElementById("myTypingText").innerHTML = '';
} else {
document.getElementById("myTypingText").innerHTML += char;
}
} else {
clearTimeout(loopTimer);
return false; // To the loop will stop when the array is empty
}
if (char === ' ') {
loopTimer = setTimeout(printLooper, 20);
} else if (char === ',' || char === '.' || char === '?') {
loopTimer = setTimeout(printLooper, 220); //fiddle with these 2nd params as you see fit
} else if (char === '#') {
loopTimer = setTimeout(printLooper, myBreath);
} else {
loopTimer = setTimeout(printLooper, 47);
}
}
document.getElementById('sub_btn').onclick = function () {
myString = document.getElementById('userInput').value;
myBreath = document.getElementById('userBreath').value;
myArray = myString.split("");
printLooper(myString, myBreath, myArray);
};
Demo here

This syntax has extra characters you probably typo'd in there. I also have never seen a button element with the href attribute before but I don't get out much. You might want to revisit this.
<button onclick="printLooper()" href="javascript:;">Submit</button>

You should put these lines inside the function
var myString = document.getElementById('userInput').value;
var myBreath = document.getElementById('userBreath').value;
var myArray = myString.split("");
It's empty because you put it outside the function and initially the inputs are empty and inside the function if(myArray.length > 0 ) is always false, you need to populate the array once the function is called after the button pressed and also href is not a valid attribute for button as another answer stated it.

var myString = document.getElementById('userInput').value;
//var myString = prompt('Say what you want to see typed','Right here, baby'); //prompts are annoying, i know
//var myDelay = prompt('Type speed (try 50)', 'The higher the number, the slower it types');
//var myBreath = prompt('Now tell me how long to pause at each breath (shift+2)', 'Try 300')
var myBreath = document.getElementById('userBreath').value;
var myArray = myString.split("");
Move these inside the function.

Related

How to make .replace script "digit-case-sensitive"?

I have a simple side-project here to help me at work. What I have is a script that will replace a specified number with another.
My problem now though is, I cannot find a way to make it "digit-case-sensitive" (I'm not sure what it's called sorry), meaning, if I want to change the following, they replace only the specified and not anything else. For example:
10 = 80
1 = 75
0 = 65
The problem is, if I replace 10, there's a tendency that it will become 865.
It's changing 10 to 80 first and then the 0 to 65.
Now I really need help as to how do I make the replace script to the specified digit only and not cut the digits or take only half and change them.
Also, how can I make it so that it changes only once for 1 click of button? In this case, it's processing it twice with 1 click of button. It changes 10 to 80 first and then the 0 to 65. What I'd like is run the script only once per click. In this flawed script, it should only be 65 and not process the 0 to 65, since doing so should take 2 clicks.
Here's my sample code, there will be thousands of digits to replace once I move on from this obstacle.
function fixTextarea(textarea) {
textarea.value = textarea.value.replace("", "")
.replaceAll("10", "80")
.replaceAll("1", "75")
.replaceAll("0", "65")
};
function fixtext() {
let textarea = document.getElementById("textarea1");
textarea.select();
fixTextarea(textarea);
}
window.addEventListener('DOMContentLoaded', function(e) {
var area = document.getElementById("textarea1");
var getCount = function(str, search) {
return str.split(search).length - 1;
};
var replace = function(search, replaceWith) {
if (typeof(search) == "object") {
area.value = area.value.replace(search, replaceWith);
return;
}
if (area.value.indexOf(search) >= 0) {
var start = area.selectionStart;
var end = area.selectionEnd;
var textBefore = area.value.substr(0, end);
var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore, search);
area.value = area.value.replace(search, replaceWith);
area.selectionStart = start + lengthDiff;
area.selectionEnd = end + lengthDiff;
}
};
});
<textarea id="textarea1" name="textarea1">10</textarea>
<button onclick="fixtext()">Update</button>
I apologize in advance for not being able to make myself too clear.
You could replace with searching for alternative strings and take the longest first.
For prevent changing the value again on a click, store the orginal value to a data-* attribute.
const
replace = s => s.replace(/10|1|0/g, s => ({ 10: '80', 1: '75', 0: '65' }[s]));
console.log(replace('1010'));
console.log(replace('01'));
You'll have to be a little creative, by changing "10" to something that has special meaning so that the match on "0" won't change it, then change it to your end result:
function fixTextarea(textarea) {
textarea.value = textarea.value.replace("", "")
.replaceAll("10", "xx")
.replaceAll("1", "75")
.replaceAll("0", "65")
.replaceAll("xx", "80")
};
You can do the replace in an if else if else block
function fixTextarea(textarea) {
if(textarea.value === "10"){
textarea.value = textarea.value.replace("", "").replaceAll("10", "80")
}else if(textarea.value === "1"){
textarea.value = textarea.value.replace("", "").replaceAll("1", "75")
}else{
textarea.value = textarea.value.replace("", "").replaceAll("0", "65")
}
};
function fixtext() {
let textarea = document.getElementById("textarea1");
textarea.select();
fixTextarea(textarea);
}
window.addEventListener('DOMContentLoaded', function(e) {
var area = document.getElementById("textarea1");
var getCount = function(str, search) {
return str.split(search).length - 1;
};
var replace = function(search, replaceWith) {
if (typeof(search) == "object") {
area.value = area.value.replace(search, replaceWith);
return;
}
if (area.value.indexOf(search) >= 0) {
var start = area.selectionStart;
var end = area.selectionEnd;
var textBefore = area.value.substr(0, end);
var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore, search);
area.value = area.value.replace(search, replaceWith);
area.selectionStart = start + lengthDiff;
area.selectionEnd = end + lengthDiff;
}
};
});
<textarea id="textarea1" name="textarea1">10</textarea>
<button onclick="fixtext()">Update</button>

Combining Javascript Validation Functions

Alright I need help combining the two JavaScript Functions... I have tried multiple times and am not coming up with any luck. There almost identical functions except the fact that I change one number so that it thinks there different textboxes. I tried putting a variable in its place but then it always only validates to the ending number of the loop. Please show me how I may be able to combine these two functions. (Its my only work around and I can not find any examples similar to mine)
First:
<script type="text/javascript">
var QnoText = ['abc_1']; // add IDs here for questions with optional text input
function doSubmit_1() {
var ids_1 = '';
flag_1 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_1 = QnoText[i]+'Certificate_1';
if (CkStatus && document.getElementById(ids_1).value == '') {
alert('Please enter certificate number 1.');
document.getElementById(ids_1).focus();
flag_1 = false;
alert('return flag_1');
}
}
return flag_1;
}
</script>
Second:
<script type="text/javascript">
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit_2() {
var ids_2 = '';
flag_2 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_2 = QnoText[i]+'Certificate_2';
if (CkStatus && document.getElementById(ids_2).value == '') {
alert('Please enter certificate number 2.');
document.getElementById(ids_2).focus();
flag_2 = false;
alert('return flag_2');
}
}
return flag_2;
}
</script>
You can pass a parameter in your function with the number of the textbox, like this:
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit(n) {
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
alert('return flag_' + n);
}
}
return flag;
}
doSubmit(1); // for your submit 1
doSubmit(2); // for your submit 2
Is this what you wanted? because is not very clear. If is not feel free to explain.

Taking var with JS prompt - how can I make it through HTML form?

I've been learning HTML/CSS/JavaScript for a couple of weeks now, and I am currently practicing on a mini project, which consists of letting people answer math questions, and validating their answers.
My current progress can be seen at http://dany.faceflow.com
I know I am probably not using the best strategy to develop this mini game, so any advice would be useful on that. However right now, the problem is that I am taking the user answer with a variable through JS prompt, and I want to do it via an HTML form (less annoying).
In my source code you can see this line within the function:
var userInput = prompt(numb1 + symbol + numb2);
Then, still in the same function, I have an if/else structure to compare the user's answer with the right answer. The code works, I just don't know how to make the prompt HTML-based instead. I've tried an html form with an ID and in the JS using getElementById, document.write and some other stuff but I never got it to work for that part.
(Here's all the JS)
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
var userAnswer = function() {
var numb1 = number1();
var numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
// Prompts the user to give an answer. Change this to HTML.
var userInput = prompt(numb1 + symbol + numb2);
//var userInput = document.getElementById('tw').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
return userInput;
}
(The HTML)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="js/script.js"></script>
<title>Improve Your Math Skills!</title>
</head>
<body>
<center>
<button onclick="userAnswer()">PLAY NOW!</button>
<div id="bubble"></div>
<div id="feedback"></div>
<!-- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> -->
</center>
</body>
</html>
Thank you
You can use an input tag instead of the prompt. Change the HTML just as in Dinesh's answer;
<div id="bubble"></div>
<div id="inp" style="display: none;">
<input type="text" id="ans"></input> <button id="subBtn">Submit</button>
</div>
<div id="feedback"></div>
Now, for the JavaScript, there a few things to consider. Firstly, you have
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
Both functions do exactly the same thing; you don't need two separate functions to get two separate random numbers. So, only one function will suffice.
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
Secondly, now we have two functions. userAnswer to post a new question when 'Play Now!' is clicked and, say, evalAnswer to evaluate the answer written in the input field when 'Submit' is clicked.
In userAnswer, you generate two new random numbers and figure out which operation will be conducted on them. At this point, you can simply evaluate the answer yourself and store it in a global variable. This makes things easier when you evaluate the answer, you only need to do a simple comparison.
Other than that, you update innerHTML for bubble and display the div inp.
In evalAnswer, you get the value from ans and compare it with the previously computed value of the current answer, and then accordingly update feedback.innerHTML.
Here's the code;
//variable to maintain the current answer
var curAns = 0;
//Here, I get all the DOMElements I will use
var playBtn = document.getElementById('playBtn');
var bubble = document.getElementById('bubble');
var inp = document.getElementById('inp');
var ans = document.getElementById('ans');
var subBtn = document.getElementById('subBtn');
var feedback = document.getElementById('feedback');
//I add the event listeners
//This is equivalent to using 'onclick'
//in the HTML, and doing it this way is only
//my personal preference
playBtn.addEventListener('click', function() {userAnswer();}, false);
subBtn.addEventListener('click', function() {evalAnswer();}, false);
//Function to get random number
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
//This function will be executed when 'Play Now!' is clicked.
var userAnswer = function() {
//Get two separate random numbers in
//numb1 and numb2
var numb1 = number();
var numb2 = number();
var symbol = '';
var randomSymbol = Math.random();
//Determine the operation to be used
//and compute the corresponding correct answer for the current
//question
if (randomSymbol > 0.5) {
symbol = "+";
curAns = numb1+numb2;
} else {
symbol = "-";
curAns = numb1-numb2;
}
//Add math question to bubble
bubble.innerHTML = 'What is ' + numb1 + ' ' + symbol + ' ' + numb2 + '?';
feedback.innerHTML = '';
//Make inp div visible
inp.style.display = 'block';
//Reset input value to ''
ans.value = '';
};
//This function will be executed when 'Submit' is clicked
var evalAnswer = function() {
//Simply compare input value with computed
//answer and update feedback
if(parseInt(ans.value) !== curAns) {
feedback.innerHTML = 'Wrong answer, try again!';
}
else {
feedback.innerHTML = 'You got it right, congratulations!';
}
};
Here's a working example.
Hope that helped!
What I understand from your question is that you need the same functionality in HTML itself rather than driven by JS in a prompt box, if so,the below additions to your code should help:
HTML adition:
<div id="bubble"></div>
<div id="check_ans_div" style="display:none;">
<input type="text" id="txt_answer" />
<input type="submit" value="Check Answer" onclick="checkanswer()" />
</div>
<div id="feedback"></div>
JS changes:
var number1 = function() {
var numbx = Math.floor(Math.random() * 41) + 10;
return numbx;
}
var number2 = function() {
var numby = Math.floor(Math.random() * 41) + 10;
return numby;
}
var numb1=0; var numb2=0;
var userAnswer = function() {
numb1 = number1();
numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
if(document.getElementById('check_ans_div').style.display=='none')
document.getElementById('check_ans_div').style.display='block';
document.getElementById('txt_answer').value='';
}
function checkanswer(){
var userInput= document.getElementById('txt_answer').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
}

Javascript Limit Commas

I have a function that displays a countdown next to a text field for the number of characters in the field (think twitter)
<script language="javascript" type="text/javascript">
function countDown(control, maxLen, counter, typeName) {
var len = control.value.length;
var txt = control.value;
var span = document.getElementById(counter);
span.style.display = '';
span.innerHTML = (maxLen - len);
if (len >= (maxLen - 10)) {
span.style.color = 'red';
} else {
span.style.color = '';
}
}
</script>
And the next field down takes a comma separated value. Example:
tomato, apple, orange, pear
and I'd like to limit that list to 5 things (and 4 separating commas).
How can I make a similar function that counts down for the number of commas in the input.
I got this started, but it's not changing the value in the span.
my Javascript
<script language="javascript" type="text/javascript">
var max = 5;
function commaDown(area,ticker){
// our text in the textarea element
var txt = area.val();
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.val(txt.substring(0, lastComma));
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
</script>
and my html (I think the problem lies here)
<input id="choices" type="text" name="choices" class="text medium" onkeyup="commaDown('choices','limit');"/> <span id="limit">5</span><br/>
Any ideas?
Something like this (assuming you have a text field with id csv)
document.getElementById('csv').onkeydown = function(e){
if (!e) var e = window.event;
var list = this.value.split(',');
if (list.length == 5 && e.keyCode == '188' )
{
// what to do if more than 5 commas(,) are entered
// i put a red border and make it go after 1 second
this.style.borderColor ='red';
var _this = this;
setTimeout(function(){
_this.style.borderColor='';
_this.disabled=false;
},1000);
// return false to forbid the surplus comma to be entered in the field
return false;
}
}
example at http://www.jsfiddle.net/gaby/YEHXf/2/
Updated Answer
You seem to have mixed parts of jQuery in your code and that causes the script to fail
var max = 5;
function commaDown(_area, _ticker){
var area = document.getElementById(_area);
// our text in the textarea element
var txt = area.value;
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(_ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.value = txt.substring(0, lastComma);
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
live example at http://jsfiddle.net/z4KRd/
here is a solution:
test: http://jsbin.com/ulobu3
code: http://jsbin.com/ulobu3/edit
if you never used jsBin before, it is very easy, on the left side you have the javascript code (like if it was in your HTML code, and in your right side you have the html code.
and you just need to add /edit to the end of a jsbin url to edit that code, and save any new revisions to that code.
I added jQuery framework to make the example faster to code.

For-loop changing values to upper or lower case depending on their length

I'm trying to make a simple JavaScript program which prompts you to enter a sentence on page load. This sentence is then split up into an array separated by a space " ".
My issue currently is that it's not converting anything to uppercase or lowercase at all. I can't seem to understand why and some help would be appreciated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>for-loop replacement exercise</title>
<script language="JavaScript" type="text/JavaScript">
var wordString = prompt("Please enter a sentence: ", 0);
var processedString;
var cont = boolean(true);
// this function is called upon page startup
function startMeUp() {
do {
wordString;
if (wordString == "") {
cont = boolean(false);
}
} while(cont);
processString(wordString);
document.write(processedString);
}
// this function is attempting to iterate through a array of strings and anything that is 4 characters long it is put to lower case
// otherwise if the iteration is less than 4 its put to upper case
function processString(someInput) {
var wordArray = someInput.split(" ");
var lengArray = wordArray.length;
for (var i = 0; i < lengArray; i++) {
if (lengArray[i] == 4) {
wordArray[i].toLowerCase();
} else if (lengArray[i] < 4) {
wordArray[i].toUpperCase();
}
}
processedString = wordArray.toString();
}
</script>
</head>
<body onload="startMeUp();">
</body>
</html>
Try assigning the return value to the array index, rather than just calling the function and not storing it:
wordArray[i] = wordArray[i].toLowerCase();
First your not calling startMeUp() so I added that. next you could simplify the code by using a map().
var wordString = prompt("Please enter a sentence: ", '');
startMeUp();
function startMeUp() {
document.write(processString(wordString));
}
function processString(someInput) {
return someInput.split(" ").map(v => {
if (v.length == 4) return v.toLowerCase()
if (v.length < 4) return v.toUpperCase()
return v
}).join(' ')
}

Categories