if statement counter variable confusion javascript - javascript

As a novice in javascript, I am having trouble writing an If statement, with an event happening after the fourth turn. I want the alert to pop up after the user has clicked four options. I added the counter variable "turns" to the output so I can see if it has been counting correctly but it does not.
var question1 = new Array();
var turns = 0;
window.onload = function () {
var eSelect = document.getElementById('question1');
var optOtherReason = document.getElementById('displayresponse');
var options = document.getElementsByTagName("option");
eSelect.onchange = function () {
var li = document.createElement("li");
li.innerHTML = options[eSelect.selectedIndex].innerHTML;
var ol = document.getElementById("appendedtext");
ol.appendChild(li);
question1.push(li.innerHTML);
var x = document.getElementById("display");
x.innerHTML = question1 + turns;
turns + 1;
}
if (eSelect.selectedIndex == 3) {
optOtherReason.style.display = 'block';
turns - 1;
}
if (turns = 4) {
alert("hey your turn is over")
}
}
<select id="question1" name="question">
<option value="x">Reason1</option>
<option value="y">Reason2</option>
<option value="other">Otherreason</option>
<option value="none">None</option>
</select>
<br>
<div id="displayresponse" style="display:none;">If you did not see a choice here, you may search for other sites.</div>
<ol id="appendedtext"></ol>
<div id="display"></div>

To compare two expression you need to use == :
if ( turns == 4)
Also, turns is a variable, so to sum/substract one you should use:
turns += 1
turns -= 1
Or, as pointed out in comments, you could also use:
turns++;
turns--;

Related

Dropdown selection value doesn't become a real value and work in JavaScript

I have a language dropdown and I try to alert the user to have to choose one language before doing anything further like languageOption can become a string and go into array. But it's not working and I don't understand why. I tried:
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
But they all don't work.
And I thought another way to solve this, which I make
<option value="1" selected>English (American)</option>
but then the value = "1" doesn't become the a value for variable 'languageOption'. So the arrays don't respond and don't know what to do when I see in console. I don't understand why the array is not responding.
Any help I would appreciate.
Below is my code:
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
var audioSrc = "sound/"
var audioType = ".wav";
// default number of random question, if user this used the dropdown
var default_numFollowUp = 4;
// default delai (seconds) between random questions, if user this used the dropdown
var default_secFollowUp = 10;
// Create the audio element
var audioElement = document.createElement('audio');
var endingArr = [];
var runThroughArr = [];
var randomArr = [];
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
languageOption = $(this).val(); // Make languageOption value be string
//if(languageOption.length==0){languageOption=1;}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === ""){
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
}
else if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
You need to assign the onchange function after loading the document. With jQuery, you can do it like this
var languageOption;
$(document).on("ready", function() {
languageOption = $("#languageSelection").val();
$("#languageSelection").on("change", function() {
your code here ...
}
}

Some of the JavaScript code doesn't work

I have a HTML select which onchange fires a function run()
<select id="select-para" onchange="run();">
<option value="paragraph 1...">Para 1</option>
<option value="paragraph 2...">Para 2</option>
<option value="paragraph 3...">Para 3</option>
<option value="paragraph 4....">Para 4</option>
</select>
What run() does is that it set value of select equals a variable text and value of text is set equal to value of input box.
function run(){
var text = document.getElementById("select-para").value;
var storyTextarea = document.getElementById("storytext");
storyTextarea.value = text;
}
I am making a typing test and I want user to select paragraph of his choice. Problem is that after this function ends, the rest of typing test code doesn't fire. Paragraph in input box changes but rest of typing test code doesn't work. How to make rest of code work? Rest of code is here.
var textArr = text.split(" ");
var usertext = "";
var lastWord = ""
var usertextArr = new Array();
var mistakes = new Array();
var highlightArgs = new Array();
var score = 0;
var count = 0;
var highlightIndex = 0;
//Prevent pasting into user text box
$('textarea').bind("cut paste", function (e) {
e.preventDefault();
});
//Keep highlighted text responsive
$(window).on('resize', function(){
$(".highlightTextarea").css('width','100%');
$(".highlightTextarea-container").css('width','99%');
if (highlightArgs.length > 0){
updateHighlight();
}
});
//Jump to next word to be typed
function textJump(jumpIndex){
var textStr = text.substring(0, jumpIndex);
storyTextarea.value = textStr;
storyTextarea.scrollTop = storyTextarea.scrollHeight;
storyTextarea.value = text;
}
//Jump to specified line of TextArea
//OLD METHOD DO NOT USE
function textareaJump(line){
storyTextarea = document.getElementById("storytext");
var lht = (storyTextarea.clientHeight / storyTextarea.rows)*0.875;
var jump = (line - 1) * lht;
storyTextarea.scrollTop = jump;
}
//Refresh the highlighted area
function updateHighlight(){
$('#storytext').highlightTextarea('destroy');
$('#storytext').highlightTextarea({ ranges: highlightArgs });
}
function typeTest(){
function updateUsertext(){
usertext = $('textarea#usertext').val();
var usertextLatestArr = usertext.split(" ");
usertextArr.push(usertextLatestArr[usertextLatestArr.length-1]);
count = usertextArr.length - 1;
var wordLen = textArr[count].length;
var charBufferIndex = textArr[count].length < 3 ? 5 : 2;
//Word spelling matches
if(textArr[count] === usertextArr[count]){
if (mistakes[mistakes.length-1] === count){ mistakes.pop() }
score++;
highlightArgs.push({ color: '#c1f5b0', start: highlightIndex, length: wordLen })
highlightIndex += (wordLen + 1);
}
//Missed one word
//any more than a single consecutive missed word counts as an error
else if(textArr[count+1] === usertextArr[count]){
usertextArr.splice(count, 0, "blank");
if (mistakes[mistakes.length-1] === count){ mistakes.pop() }
score++;
mistakes.push(count);
highlightArgs.push({ color: '#febbb9', start: highlightIndex, length: wordLen })
highlightIndex += (wordLen + 1);
highlightArgs.push({ color: '#c1f5b0', start: highlightIndex, length: textArr[count+1].length })
highlightIndex += (textArr[count+1].length + 1);
}
//Spelling mistake
else{
highlightArgs.push({ color: '#febbb9', start: highlightIndex, length: wordLen })
highlightIndex += (wordLen + 1);
mistakes.push(count);
}
//Rebuild the highlight object
updateHighlight();
//Jump to the next word
var jumpIndex = highlightIndex + (wordLen + 1) + charBufferIndex;
textJump(jumpIndex);
};
//User presses backspace
$('#usertext').on('keydown', function(e) {
var lastChar = $('textarea#usertext').val().slice(-1);
var secondLastChar = $('textarea#usertext').val().slice(-2).substring(0, 1);;
if(e.keyCode == 8 && lastChar === " " && secondLastChar !== " "){
usertextArr.pop();
mistakes.pop();
highlightArgs.pop();
updateHighlight();
highlightIndex -= ( textArr[count].length + 1 );
count--;
}
});
$('#usertext').on('keydown', function(e) {
var lastChar = $('textarea#usertext').val().slice(-1);
var spaceTest = lastChar === " " ? true : false;
if(e.keyCode == 32 && spaceTest == false){
updateUsertext();
}
});
}
How to make all code work and typing test function smoothly. Here is the HTML:
<select id="select-para" onchange="run();">
<option value="paragraph 1...">Para 1</option>
<option value="paragraph 2...">Para 2</option>
<option value="paragraph 3...">Para 3</option>
<option value="paragraph 4....">Para 4</option>
</select>
<div class="typebox">
<textarea id="storytext" name="storytext" class="form-control" type="text" readonly="readonly" rows="3"></textarea>
</div>
<div class="typebox">
<textarea id="usertext" name="usertext" type="text" class="form-control" rows="2" placeholder="Start typing here to begin the test..."></textarea>
</div>
<div class="timer">You have <span id="time" class="timerTime">02:00</span> minutes left.</div>
Add typeTest() while onChange of paragraph
<select id="select-para" onchange="run(); typeTest();">
include the
$("#usertext").bind("cut paste", function (e) {
e.preventDefault();
});
//Keep highlighted text responsive
$(window).on('resize', function(){
$(".highlightTextarea").css('width','100%');
$(".highlightTextarea-container").css('width','99%');
if (highlightArgs.length > 0){
updateHighlight();
}
});
in run() function, so that the handlers get registered.
remove "textarea" from, as it is not needed to identify the ID.
$("textarea#usertext")
The logic may need to be properly formatted to work properly for all the other keycodes apart from '8' bs and '32' space.

Add array values without clearing previous value using javascript

I have a password generator which works fine. But need a little change. The below image shows
Once I click the "Generate Password" button it generates one password.
Required: When I click the button again, I need to have another password generated below without clearing the previous one. Tried a couple of variations in loop but did not work.
**passGen.js**
function passGen() {
var Generator = {};
Generator.generateMnemonic = function(length, num_length, mixcase) {
var ret = '';
var vowels = 'aeioe';
var consonants = 'bcdfghklmnpqrstvwxzy';
if (mixcase) {
vowels += vowels.toUpperCase();
consonants += consonants.toUpperCase();
}
vowels = vowels.split('');
consonants = consonants.split('');
for(var i = 0; i < length / 2; i++) {
ret += vowels.getRandom();
ret += consonants.getRandom();
}
if (!num_length) return ret;
var pos = $random(2, length - 2 - num_length);
return ret.substr(0, pos) + $random(Math.pow(10, num_length - 1), Math.pow(10, num_length) - 1) + ret.substr(pos + num_length);
};
var observe = new Observer('#generator-length, #generator-num_length, #generator-mixcase, #generator-amount', function(values) {
var length = values[0].toInt();
var num_length = values[1].toInt();
var mixcase = values[2].toInt();
var amount = values[3].toInt();
// Fill passwords in a loop
var words = [];
for (var i = 0; i < amount; i++) {
words.push(Generator.generateMnemonic(length, num_length, mixcase) );
}
// Get the output area
var output = $('generator-output');
// Output it and highlight it so users will notice the update
output.value = words.join("\n");
output.getParent().highlight('#ff8', '#fff');
}, {
// periodical: 1000 // interval in ms
});
// To fill in the first values
observe.fire();
}
**Part of Hmtl**
<script type="text/javascript" src="passGen.js"></script>
<span>How many passwords:</span>
<br>
<select name="amount" id="generator-amount">
<option value="1" selected>1</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</label>
<input type="button" name="button" value="Generate Password" onclick="passGen();">
<label>
<br>
<span>Your passwords:</span>
Do something along these lines: (small example to give the feel) with a static variable.
function passGen() {
if ( typeof passGen.words == 'undefined' ) { /* It has not been called do initialization*/
passGen.words = [];}//else previous passwords persist, and you push, onto them.
passGen.words.push("Hello");
alert(passGen.words);
}
passGen();
passGen();
In your case keep my initial if, remove your line
var words = [];
and prepend passGen. to your words.push and words.join
adapted from Static variables in JavaScript

Text Box Event Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a noobie and I need some help with changing events in textbox.
Here's the code I am working with:
<body>
<form action="#">
<input type="text" id="begin" /> Apple
=
<input type="text" id="done" />
<select id="newValue" onchange = "function()">
<option value="a">Apple</option>
<option value="b">Blueberry</option>
<option value="c">Cheese</option>
</select>
<p id = "weight"></p>
</form>
<script>
var apple = document.getElementById('begin'),
choice = document.getElementById('done');
apple.onkeyup = function(){
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; //if cheese
}
</script>
</body>
I have two text boxes. The left text box ('begin') will accept the weight of apple. But the right box ('done') should change the number value depending on what the user chooses form the drop-down text list.
My
apple.onkeyup = function(){
is not doing the right thing. If I give the value of '2' to the left text box,no matter what I choose in the dropdown list, it will return 2 * 3 = 6, meaning it skips everything in the function and evaluates only the last statement.
choice.value = this.value * 3; /*if cheese
How I want it to work is:
Left Box : 2 Right Box : 2 (if apple was chosen)
Left Box : 2 Right Box : 4 (if blueberry was chosen)
I'm sure I need a few 'if statements' to determine which output choice was chosen, something along the lines of
if(temp = Apple){
choice.value = this.value * 1;
}else if(temp = Blueberry){
choice.value = this.value * 2;
}
}
The value in Right Box should also change as the user chooses a different item from the list..
Although I'm not sure if that's the right approach/syntax.
I think this may be what you are looking for, here is a fiddle.
Remove the onchange from your newValue selection and set it in your JavaScript, just like you are doing with your onkeyup function for apple. In your code above, your are calling function() which will likely just cause errors. function() represents an anonymous function, you need to name your function with the syntax function name() if you'd like to call it in this way. However, since you are already setting onkeyup from your JavaScript, you might as well set onchange from the same place in this case.
Then change your JavaScript to this:
var apple = document.getElementById("begin"),
choice = document.getElementById("done"),
fruits = document.getElementById("newValue");
// This function properly sets the done field.
var setDone = function() {
var newVal = document.getElementById("newValue").value;
if (newVal == "a") {
choice.value = apple.value * 1; //if apple
} else if (newVal == "b") {
choice.value = apple.value * 2; //if blueberry
} else if (newVal == "c") {
choice.value = apple.value * 3; //if cheese
} else {
alert("I couldn't find that value!");
}
}
apple.onkeyup = setDone;
fruits.onchange = setDone;
I made your anonymous function into a named variable ,added if statements to check for the value of newValue and set the value of apple appropriately.
Then I set the onkeyup and onchange events for apple and the new variable I created for your selector, fruits.
If you have any questions about how any of this works, feel free to ask in the comments below.
Try this - I'm not sure if I got my apples and blueberries in the right order, but it looks to work OK:
var apple = document.getElementById('begin'),
choice = document.getElementById('done');
apple.onkeyup = function(){
var temp = document.getElementById("newValue").value;
if (temp == 'a') {
choice.value = this.value * 1;
}
if (temp == 'b') {
choice.value = this.value * 2;
}
if (temp == 'c') {
choice.value = this.value * 3;
}
}
FIDDLE
Your code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; /*if cheese
is equal to :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 3;
you repeat assign value to choice.value, so the finally result is :
choice.value = this.value * 3;
you should change the code :
<select id="newValue" onchange = "function()">
<option value="1">Apple</option>
<option value="2">Blueberry</option>
<option value="3">Cheese</option>
</select>
to :
<select id="newValue" onchange = "function()">
<option value="a">Apple</option>
<option value="b">Blueberry</option>
<option value="c">Cheese</option>
</select>
and then change the code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; /*if cheese
to the code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * temp;
So, I'm going to recreate some stuff here. From what I can tell, you want to select a food item and output its weight in the other text field.
/* begin and done are input and output. */
var input=document.getElementById("input");
var output=document.getElementById("output");
/* Handles a change in the input text field, like if the user types apple, blueberry, etc. */
/* You could make this a keyup listener as well, I suppose. */
input.addEventListener("change",function(event_){
switch(this.value){
case "apple":
output.value="weight of apple";
break;
case "blueberry":
output.value="weight of blueberry";
break;
/* Optional default value for when the user is messing around. */
default:
output.value="Please select an item from the drop down list."
break;
}
});
Be sure to use conditionals to evaluate your output. I used a switch statement, but if statements are great, too! What I mean is this:
var x=10;
x=15;
x=7;
alert(x);// Returns 7
var y=Math.random()*100;
if (y<50){
alert("y is less than 50");
} else {
alert("y is greater than 50");
}
Multiple assignments in a row will be overwritten by subsequent assignments.
try this, I tested which can be work.
<body>
<form action="#">
<input type="text" id="begin" /> Apple
=
<input type="text" id="done" />
<select id="newValue" onchange = "f();">
<option value="1">Apple</option>
<option value="2">Blueberry</option>
<option value="3">Cheese</option>
</select>
<p id = "weight"></p>
</form>
<script>
var weightTag = document.getElementById('begin');
var totalTag = document.getElementById('done');
function f(){
var priceTag = document.getElementById('newValue');
if (weightTag.value != "") {
var index = priceTag.selectedIndex;
var priceValue = priceTag.options[index].value;
totalTag.value = weightTag.value * priceValue;
}
}
weightTag.onkeyup = f;
I think this is what you need.
<html>
<head>
</head>
<body>
<form action="#">
<input type="text" id="begin" onkeyup="k(1);" />
<select id="Fruitbox1" onclick="k(1);">
<option value = "3">Apple</option>
<option value = "1.5">Blueberry</option>
<option value = "1">Cherry</option>
</select>
=
<input type="text" id="done" onkeyup="k(0);"/>
<select id="Fruitbox2" onclick="k(0);">
<option
value="3">Apple</option>
<option value="1.5">Blueberry</option>
<option value="1">Cherry</option>
</select>
<p id = "leftWeight"></p>
<p id = "rightWeight"></p>
</form>
<script>
function k(x){
var weightOfFruit1=document.getElementById("Fruitbox1")
var weightOfFruit2=document.getElementById("Fruitbox2")
var NumberofFruit1=document.getElementById("begin")
var NumberofFruit2=document.getElementById("done")
if(x==1)
{
TotalNumberofFruit2=(NumberofFruit1.value * weightOfFruit1.value)/weightOfFruit2.value
NumberofFruit2.value=parseInt(TotalNumberofFruit2)
}else
{
TotalNumberofFruit1=(NumberofFruit2.value * weightOfFruit2.value)/weightOfFruit1.value
NumberofFruit1.value=parseInt(TotalNumberofFruit1)
}
}
</script>
</body>
</html>

Finding Closest Matching Value using jQuery or javascript

Consider a markup such as
<select id="blah">
<option value="3">Some text</option>
<option value="4">Some text</option>
<option value="8">Some text</option> // <---- target this tag based on value 7
<option value="19">Some text</option>
</select>
Suppose I have a value with me, say 7. Is it possible to target the option tag whose value attribute is closest to 7 which, in this case, would be <option value="8">?
I'm aware of ^ which means starting with and $ which means ending with and was hoping if there is something like this to find the closest match for a given value.
I'll go like this:
http://jsfiddle.net/GNNHy/
var $tmpOption = $('<option value="7">Some text 7</option>');
$("#blah").append($tmpOption);
var my_options = $("#blah option");
my_options.sort(function(a,b) {
if (parseInt(a.value,10) > parseInt(b.value,10)) return 1;
else if (parseInt(a.value,10) < parseInt(b.value,10)) return -1;
else return 0
})
$("#blah").empty().append( my_options );
How about a recursion? It will find the closest value:
JS-BIN Demo
function getClosest(val, ddl, increment){
if(ddl.find('option[value="'+val+'"]').length){
return val;
}
else
try{
if(increment)
return getClosest(++val, ddl, increment);
else
return getClosest(--val, ddl, increment);
}
catch(err){
return -1;
}
}
function findClosest(val, ddl){
var larger = getClosest(val, ddl, true);
var smaller = getClosest(val, ddl, false);
if(larger == smaller == -1)
return -1;
else if (larger == -1)
return smaller;
else if (smaller == -1 )
return larger;
if(larger - val > val - smaller)
return smaller;
else
return larger
}
Yes just substract your value (7) with the option values(use each function)...the value with the minimum positive outcome will be your targeted option. I hope you will have the desired result.
The easiest way is perhaps the good old linear search (you can do binary, but it's more tricky than usual):
var target;
var $options;
var best=Infinity;
var bestAt;
$options.each(function(){
var error = this.value - target;
error = error>0 ? error : -error;
if(error<=best){
best=error;
bestAt=this;
}
})
//return $(bestAt);
function findClosest(num){
var select = document.getElementById('blah');
var options = select.options;
var dif = Infinity;
var index;
for(var i = 0; i < options.length; i++){
var newdif = Math.abs(parseInt(options[i].value) - num);
if(newdif < dif){
dif = newdif;
index = i;
}
}
select.selectedIndex = index;
}
If you can use jquery I would do something like
$(function () {
// comes from somewhere
var val = 7;
var sortByDifference = $("#blah option").sort(function (opt1, opt2) {
return Math.abs(parseInt($(opt1).val()) - val) - Math.abs(parseInt($(opt2).val()) - val);
});
alert($(sortByDifference[0]).val());
});
In sortByDifference you have all values sorted by how close they are to your value. The routine returns the closest greater or lower and doesn't require the options to be sorted.

Categories

Resources