Some of the JavaScript code doesn't work - javascript

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.

Related

Bind another dropdowns as per previous values

I have total 4 dropdowns list... all dropdown contain numbers.
The maximum number of the last three dropdowns together is always equal to the amount that’s selected in the 1st dropdown.
If user selected 4 from 1st dropdown.
In this case all remaining dropdowns contain the values 0, 1, 2 ,3 and 4.
If customer selects 2 from 2nd dropdown then other two dropdowns will only show the values 0,1 and 2.
If customer selects 1 from 3rd dropdown then last should only show the values 0 and 1.
can anyone help me to sort-out this. Thanks in advance
I have tried so far
var tripChildSelect = $('#trip-child-count-range_0');
var childRangeLength = "<?php echo $this->getChildRangeLength()?>";
var j;
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
}
tripChildSelect.change(function() {
tripChildSelect = $(this);
availableChildren = tripChildSelect.data('max-count') - tripChildSelect.val();
console.log(tripChildSelect.data('max-count') - tripChildSelect.val());
if(tripChildSelect.data('max-count') - tripChildSelect.val() === 0) {
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
childRange.prop('disabled', true);
}
} else {
for(j=1; j <= childRangeLength; j++ )
{
var childRange = $('#trip-child-count-range_' + j);
childRange.find('option').each(function (index, element) {
selectOption = $(element);
if(selectOption.val() <= availableChildren) {
selectOption.show();
} else {
selectOption.hide();
}
});
childRange.prop('disabled', false);
}
}
});
//disable if sum equals
$('.trip-child-count-range').change(function() {
// body...
var sum = 0;
$('.trip-child-count-range :selected').each(function() {
sum += Number($(this).val());
});
// console.log('sum- '+sum);
if(sum == $('#trip-child-count').val())
{
$('.trip-child-count-range').each(function() {
if($(this).val() == 0)
$(this).attr('disabled', true);
});
}
else
{
$('.trip-child-count-range').each(function() {
if($(this).val() == 0)
$(this).attr('disabled', false);
});
}
})
$('#trip-child-count').change(function() {
// body...
var i;
for (i = 1; i <= $(this).val(); i++)
{
if ( $(".trip-child-count-range option[value='"+i+"']").length == 0 )
$('.trip-child-count-range').append( '<option value="'+i+'">'+''+i+'</option>' );
}
//set adta-max-xount
$('#trip-child-count-range_0').data( "max-count", $(this).val());
// console.log('hello' + $('#trip-child-count-range_0').data( "max-count"));
//remove greater options
$(".trip-child-count-range option").each(function() {
if($(this).val() > $('#trip-child-count').val())
{
$(".trip-child-count-range option[value="+this.value+"]").remove();
}
});
//added finalllu
$('.trip-child-count-range').attr('disabled', false);
$('.trip-child-count-range option[value=0]').attr('selected','selected');
availableChildren = $('#trip-child-count').val();
});
first dropdown id : #trip-child-count
common class for remaining 3 dropdowns: trip-child-count-range
Here I put your basic need. First create first drop down with 0-4 options and make other three drop down as empty. Then append options to other drop down based on the current drop down value
<!DOCTYPE html>
<html>
<body>
<div>
<select id="dropdown1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="dropdown2">
</select>
<select id="dropdown3">
</select>
<select id="dropdown4">
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#dropdown1").on("change",function(){
var dd1 = parseInt($(this).val());
$("#dropdown2, #dropdown3, #dropdown4").empty();
for(var i=0;i<=dd1;i++){
$("#dropdown2, #dropdown3, #dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
$("#dropdown2").on("change",function(){
var dd1 = parseInt($("#dropdown1").val());
var dd2 = parseInt($(this).val());
$("#dropdown3, #dropdown4").empty();
for(var i=0;i<=dd1-dd2;i++){
$("#dropdown3, #dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
$("#dropdown3").on("change",function(){
var dd2 = parseInt($("#dropdown2").val());
var dd3 = parseInt($(this).val());
$("#dropdown4").empty();
for(var i=0;i<=dd2-dd3;i++){
$("#dropdown4").append('<option val='+i+'>'+i+'</option>');
}
});
});
</script>
</body>
</html>

How to get the value from N dynamic inputs

I have a select with an options, this options have the number of inputs that user want to draw, after that user can type information in that inputs and finally they have to click a button to display that values, right now I'm doing this like this:
var value1 = $('#Input1').val();
The problem here is that the user can create a maximum of 200 inputs, so if I keep doing this in the above way I'll need to do that with the 200 inputs and it's a lot of code lines, my question is if exits a way to get the value of N inputs, I draw the inputs dynamically with a for loop, so all the input ID is something like Input(MyForVariable), Input1, Input2... etc, so maybe I'm thinking in create another loop to get the value of that inputs, here is my code:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
if (total == 2) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
alert(val1 + val2);
}
if (total == 3) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
var val3 = $('#Imput3').val();
alert(val1 + val2 + val3);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
Put all your inputs inside a container, and loop through them:
$('#add').on('click', function () {
$('<input />').appendTo('#myinputs');
});
$('#get').on('click', function () {
var values = [];
$('#myinputs input').each(function () {
values.push(this.value);
});
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myinputs">
<input />
</div>
<button id="add">Add another input</button>
<hr />
<button id="get">Get values</button>
You can set some attribute and get all elements that has it:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" to-count />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
var sum = "";
var inputs = $('[to-count]');
console.log(inputs.length);
for (let i=0; i < inputs.length ; i++){
sum += inputs[i].value;
}
alert(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
You can get the values for each of the Select options by using the following code:
$("#sel option").each(function() {
console.log($(this).val());
});
You can always loop throw your inputs like this:
var myInputArray = [];
$('input[type="text"]').each(function(){
myInputArray.push($(this).val());
}
Then you can get your values by locking in the array:
alert(myInputArray[0]) //The first value of the array => first input

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

How to find Currently Selected value from this Custom HTML form Tag?

I have an element which is text box but its value is populated from another hidden select element.
<input type="text" id="autocompleteu_17605833" style="box-shadow: none; width: 119px;" class="mobileLookupInput ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<select id="u_17605833" name="u_17605833" style="visibility: hidden">
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
var mySelObju_17605833 = document.getElementById("u_17605833");
$(function () {
var availableTagsu_17605833 = new Array();
for (var i = 0; i < mySelObju_17605833.options.length; i++) {
if (mySelObju_17605833.options[i].text != 'Other') {
availableTagsu_17605833[i] = mySelObju_17605833.options[i].text;
}
}
$("#autocompleteu_17605833").width($(mySelObju_17605833).width() + 5);
availableTagsu_17605833 = $.map(availableTagsu_17605833, function (v) {
return v === "" ? null : v;
});
$("#autocompleteu_17605833").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var a = $.grep(availableTagsu_17605833, function (item, index) {
var items = item.split(" ");
for (i = 0; i < items.length; i++) {
if (matcher.test(items[i])) return matcher.test(items[i]);
}
return matcher.test(item);
});
response(a);
},
close: function (event, ui) {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
}
});
});
$("#autocompleteArrowu_17605833").click(function () {
$("#autocompleteu_17605833").autocomplete("search");
$("#autocompleteu_17605833").focus();
});
$("#autocompleteu_17605833").focusout(function () {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
//$(this).autocomplete("close");
});
I want to find value selected in the hidden select box!
I tried to do the following
$("#autocompleteu_17605833").on("click", function (event) {
$((this.id).substring((this.id).indexOf("_") - 1)).attr("onchange", function (event) {
var selece = this.value;
alert(selece);
});
});
$("#autocompleteu_17605833").next().on("click", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Click on Arrow" + selectedValue);
});
$("#autocompleteu_17605833").on("change", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Changing the value" + selectedValue);
});
what I'm getting is older value where as I need the current assigned value.
How to achieve this??
WORKING DEMO
If am not wrong you want the selected value for this you can use select method
select:function(event,ui) {
alert("You have selected "+ui.item.label);
alert("You have selected "+ui.item.value);
}
This is a simple piece of code that will work as you required.
function result(){
document.getElementById("result").innerHTML= document.getElementById("u_17605833").value;
}
<html>
<head>
</head>
<body>
<div>
<select id="u_17605833" name="u_17605833" >
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
<input type="button" value="Show the result" onclick="result()"/>
</div>
<div id="result"></div>
</body>
</html>

if statement counter variable confusion 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--;

Categories

Resources