Loop and count in JavaScript - javascript

I try to get at least three responses from a total of 10 textboxes. And an alert will occur if the total number of responses is less than three. I also try to eliminate responses that are only spaces, so I use return x.replace(/^\s+|\s+$/gm,'') to get rid of spaces before and after the string.
What I need to do is first set a variable "count" to be 0. Next to detect whether there is at least one character in a specific textbox, and if so, add 1 to "count". Then do this for all 10 textboxes. After that, check whether "count" is greater than 2; if so, go to a next page; otherwise, an alert will occur.
But it didn't work.
Another question is, how can I avoid iterating the process for all 10 textboxes?
var count=0
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
}
var x1 = document.getElementById("textbox1").value;
var t1 = myTrim("x1");
var n1 = t1.length;
if (n1<1){
count=count+0
} else{
count=count+1
}
var x2 = document.getElementById("textbox2").value;
var t2 = myTrim("x2");
var n2 = t2.length;
if (n2<1){
count=count+0
} else{
count=count+1
}
var x3 = document.getElementById("textbox3").value;
var t3 = myTrim("x3");
var n3 = t3.length;
if (n3<1){
count=count+0
} else{
count=count+1
}
var x4 = document.getElementById("textbox4").value;
var t4 = myTrim("x4");
var n4 = t4.length;
if (n4<1){
count=count+0
} else{
count=count+1
}
var x5 = document.getElementById("textbox5").value;
var t5 = myTrim("x5");
var n5 = t5.length;
if (n5<1){
count=count+0
} else{
count=count+1
}
var x6 = document.getElementById("textbox6").value;
var t6 = myTrim("x6");
var n6 = t6.length;
if (n6<1){
count=count+0
} else{
count=count+1
}
var x7 = document.getElementById("textbox7").value;
var t7 = myTrim("x7");
var n7 = t7.length;
if (n7<1){
count=count+0
} else{
count=count+1
}
var x8 = document.getElementById("textbox8").value;
var t8 = myTrim("x8");
var n8 = t8.length;
if (n8<1){
count=count+0
} else{
count=count+1
}
var x9 = document.getElementById("textbox9").value;
var t9 = myTrim("x9");
var n9 = t9.length;
if (n9<1){
count=count+0
} else{
count=count+1
}
var x10 = document.getElementById("textbox10").value;
var t10 = myTrim("x10");
var n10 = t10.length;
if (n10<1){
count=count+0
} else{
count=count+1
}
function checknumber() {
if (count < 3){
alert("You must enter at least 3 responses before you can continue.");
} else {
location.href="https://www.kindpng.com/imgv/hxbmxi_symbol-thumbs-up-clip-art-vector-free-clipart/" ; // if selection made, go to next page
}
}```

This screams for loops:
let count = 0;
for (let i = 1; i <= 10; i++) {
const textBoxValue = document.getElementById('textbox' + i).value;
if (textBoxValue.trim() !== '') count++;
}
With the code you have, not only the same lines are repeated 10 times (the only meaningful thing that changes there is textbox's ID), but also their values are not actually checked: with myTrim('x2') the parameter you pass inside your function is a literal string 'x2', not the value of x2 variable.
As a sidenote, always express your intent directly; if checking against an empty string, write that check as is. And yes, writing your own trim implementation is not really necessary.
In fact, you don't have to check all the textbox values:
function formHasAtLeast(requiredMinimum) {
let count = 0;
for (let i = 1; i <= 10; i++) {
const textBoxValue = document.getElementById('textbox' + i).value;
if (textBoxValue.trim() !== '') count++;
// this line will stop that iteration immediately,
// as there's no need to check for 4th, 5th etc. textbox
if (count === requiredMinimum) return true;
}
return false;
}
function checkForm() {
const minAnswers = 3;
if (formHasAtLeast(minAnswers)) {
location.href = "YOUR URL";
}
else {
alert(`You have to fill at least ${minAnswers} responses`);
}
}

You can use class selector, Document.getElementsByClassName("text-box"), first apply a common class to all such text boxes. Then loop over the results.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

You can access inputs by class name and work with result as an array:
function calculate() {
const elements = document.getElementsByClassName('value-container');
const result = Array.from(elements).map(e => e.value).filter(v => !!v && !!v.toString().trim()).length;
document.getElementById('result').innerHTML = `Count of fields with value: ${result}`;
}
<input type="text" class="value-container" /><br/>
<input type="text" class="value-container" /><br/>
<input type="text" class="value-container" /><br/>
<input type="text" class="value-container" /><br/>
<button type="button" onclick="calculate()">Get Result</button>
<div id="result">
</div>
https://developer.mozilla.org/ru/docs/Web/API/Document/getElementsByClassName
https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array

Related

JavaScript Random number generator not working for numbers with double digit

I was working on a small project of generating a random number but there seems to be a problem.
The Generator works fine for single digit user input but not for double-digit.
For example,
if a user inputs 12 then the generator will generator will generate a password of 15 digits.
You can see the code on GitHub:
GitHub
JS CODE:
var results = document.getElementById("results");
var num;
var input;
var button = document.getElementById("gen");
var numb = "";
function getvalue(){
input = document.getElementById("user").value;
return input;
}
function randomNumber(upper){
return Math.floor(Math.random()*upper) + 1;
}
var nums = [];
button.addEventListener('click' , function() {
if(!getvalue() || getvalue() == 0){
results.innerHTML="<p>Your Have not entered any Value or Length<p>";
}
else{
var counter = 0;
while(counter<getvalue()){
var num = randomNumber(getvalue());
nums[counter] = num;
counter += 1;
}
numb = nums.join('');
results.innerHTML="<p>Your Password is :<p>" + numb;
numb = "";
nums = [];
}
});
Your randomNumber function generates random numbers between 1 and its upper parameter, which currently comes from the user input (randomNumber(getvalue());) for some reason. So, if the user input is 10 or more, the random number generated can be 10 or more, resulting in a password string that has '10' in it where there should only be one number.
Generate random numbers between 0 and 9 instead:
var results = document.getElementById("results");
var button = document.getElementById("gen");
function getvalue() {
return document.getElementById("user").value;
}
function randomNumber(upper) {
return Math.floor(Math.random() * 10);
}
button.addEventListener('click', function() {
var nums = [];
const value = getvalue();
if (!value || value == 0) {
results.innerHTML = "<p>Your Have not entered any Value or Length<p>";
return;
}
var counter = 0;
while (counter < value) {
var num = randomNumber();
nums[counter] = num;
counter += 1;
}
const numb = nums.join('');
results.innerHTML = "<p>Your Password is :<p>" + numb;
console.log(numb.length);
});
<div id="cont">
<header>
<h1>Generate Your Random Password</h1>
<p class="one">This Application generates Random Password</p>
</header>
<section id="app">
<p id="2">Enter Desired Length :)
<p>
<input type="number" id="user">
<button id="gen">Generate</button>
<div id="results">
<p></p>
</div>
</section>
</div>

How to make a JS If Then statement for a checkbox with numeric value?

I am trying to create a basic pricing calculator for my website so that the customers can get a basic estimate of the cost. For part of the pricing I am trying to make checkboxes, where if they are selected, it adds for example 100 to the total. However if it isn't selected, the nothing is added to the total. I've been trying to use the code below but I'm definitely not doing something right. Thank you in advance for the help. I'm brand new to the JS and HTML world so I appreciate the help!
I have included my current javascript below. I'm hoping to have Number 1 and Number 2 be text boxes and Number 3 be a check box.
var button = document.getElementById("submitButton");
button.addEventListener("click", function() {
var num1 = document.getElementById('Number1').value;
var num2 = document.getElementById('Number2').value;
var num3 = if (document.getElementById('Number3').value == 1)
{
document.getElementById('Number3').value = '100';
}
else if (document.getElementById('Number3').value == 0)
{
value = '0';
} ;
var answer = parseInt(num1) + parseInt(num2) + parseInt(num3);
document.getElementById('Answer').innerHTML = answer;
}, true);
You have multiple errors in your JS. The first one comes from:
var num3 = if (document.getElementById('Number3').value == 1)
{
document.getElementById('Number3').value = '100';
}
else if (document.getElementById('Number3').value == 0)
{
value = '0';
} ;
This is a syntax error. You could instead use the ternary operator:
var num3 = document.getElementById('Number3').checked ? 100 : 0;
// condition ? value to return if true : value to return if false
You also need to check that the value of your inputs are not undefined and assign them a default value:
var num1 = document.getElementById('Number1').value || 0;
var num2 = document.getElementById('Number2').value || 0;
See working example:
var button = document.getElementById("submitButton");
button.addEventListener("click", function() {
var num1 = document.getElementById('Number1').value || 0;
var num2 = document.getElementById('Number2').value || 0;
var num3 = document.getElementById('Number3').checked ? 100 : 0;
var answer = parseInt(num1) + parseInt(num2) + num3;
document.getElementById('Answer').innerHTML = answer;
}, true);
<input id="Number1"/>
<input id="Number2"/>
<input id="Number3" type="checkbox"/>
<button id="submitButton">Go</button>
<div id="Answer"></div>
Instead of:
var num3 = if (document.getElementById('Number3').value == 1)
use:
if(document.getElementById("Number3").checked){
//add the values here
}
Hope this helps

How to add a value to a array with input box them get a average? [duplicate]

This question already has answers here:
How to show a value from array that relates to the value of another array, javascript
(6 answers)
Closed 6 years ago.
I am having trouble with getting the average of the scores after I have add one in the input box. Can figure out where I am going wrong. I am able to add the input to the array but unable to calculate the average.
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 99];
var average;
var total = 0;
var highestScore = 0;
var name = "";
var $ = function (id) { return document.getElementById(id); };
//validate entries and add to array
var addScore = function() {
var nameInput = $("nameInput").value;
var scoreInput = $("scoresInput").value;
if ((nameInput == "" || scoreInput == "") || (scoreInput < 0 || scoreInput > 100 )){
alert("You must enter a name and a valid score");
}
else {
names[names.length] = nameInput;
scores[scores.length] = scoreInput;
}
};
//then calculate the average and highest score
var displayResults = function () {
for (var i = 0; i < scores.length; i++) {
total = total + scores[i];
if (scores[i] > highestScore) {
highestScore = scores[i];
name = names[i];
}
}
average = parseInt(total/scores.length);
$("results_header").innerHTML = ("Results");
$("results_text").innerHTML = ("\nAverage score is " + average + "<br>" + "\nHigh score = " + name + " with a score of " + highestScore);
};
//display scores table
var displayScores = function() {
$("scores_header").innerHTML = ("Scores");
$("names").innerHTML = ("Names");
$("scores").innerHTML = ("Scores");
var table = $("scores_table");
for(var i=0; i < names.length;i++) {
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
var cell2 = row.insertCell(1);
cell.innerHTML = names[i];
cell2.innerHTML = scores[i];
}
};
window.onload = function () {
$("add").onclick = addScore;
$("display_results").onclick = displayResults;
$("display_scores").onclick = displayScores;
};
<main>
<h1>Use a Test Score array</h1>
<label for="name">Name:</label>
<input type="text" id="nameInput"><br>
<label for="score">Score:</label>
<input type="text" id="scoresInput"><br>
<label> </label>
<input type="button" id="add" value="Add to Array" >
<input type="button" id="display_results" value="Display Results" >
<input type="button" id="display_scores" value="Display Scores" ><br>
<div id="results">
<h2 id="results_header"></h2>
<p id="results_text"></p>
</div>
<h2 id="scores_header"></h2>
<table id="scores_table">
<tr>
<th id="names" align="left"></th>
<th id="scores" align="left"></th>
</tr>
</table>
</main>
Could be because scoreInput is a string (any value from an HTML input is) and thus when you try to add the new score to the old in displayResults() it's not adding numbers, but concating a string. Try converting the input to a Number first:
var addScore = function() {
var nameInput = $("nameInput").value;
// convert score to a Number first...
var scoreInput = Number( $("scoresInput").value );
// make sure `scoreInput` is valid AND in range...
if ((nameInput == "" || scoreInput == "") || ((!scoreInput && scoreInput !== 0)|| scoreInput < 0 || scoreInput > 100 )){
alert("You must enter a name and a valid score");
}
else {
names[names.length] = nameInput;
scores[scores.length] = scoreInput;
}
};
EDIT
As #rpadovani says, you should also initialize total each time inside displayResults():
var displayResults = function () {
total = 0;
// ... (the rest of your code)
};
You did not initialize total, so when you do total = total + scores[i]; Javascript treats it as a string.
Just write var total = 0 at the start of displayResults() function

How to dynamically create buttons based on random conditions

I have created a button using JavaScript, and I have a list that is supposed to get a random number when I "roll the dice"
I need to list of numbers to say "You rolled a 1" for example. How do I do that? And also I only need it to show the last 10 numbers.
var rollNumber = 0;
var values = [];
function dieRolled() {
rollNumber += 1;
var numRolled = Math.ceil(Math.random() * 6);
values.push(numRolled);
document.getElementById("results").innerHTML = "";
for (var x = values.length-1 ; x>=0; x--) {
var newRoll = document.createElement("li");
newRoll.innerHTML = values [x] +"You rolled a";
document.getElementById("results").appendChild(newRoll);
if (x == 11)break;
}
}
How about this?
var output = document.getElementById("Output");
var values = [];
function roll()
{
values.push(Math.ceil(Math.random() * 6));
// If the history is too big, drop the oldest...
if (values.length > 10)
{
values.shift();
}
// Rewriting the history log
var text = "";
for (var i in values)
{
text += "You rolled a " + values[i] + "\n";
}
output.innerHTML = text;
}
// Rolling multiple times
setInterval(function(){ roll(); }, 1000);
<pre id="Output"></pre>
Try this:
var list = document.getElementById('demo');
var count = 0;
function changeText2() {
count++;
if(count <= 10)
{
var numRolled = Math.ceil(Math.random() * 6);
var entry = document.createElement('li');
entry.appendChild(document.createTextNode("You rolled:"+numRolled));
list.appendChild(entry);
}
}
<input type='button' onclick='changeText2()' value='Submit' />
<p>Dices you rolled</p>
<ol id="demo"></ol>

Why doesn't it work for rows 7-13

The program is a Seat reservation program rows 1 and 2 are first class, row 3-9 are business class and rows 10 through 13 are economy. They are initialized to * and become X when it is reserved. and alert you if the seat is already filled.
The rows will fill for the first 6 rows but it ignores request for row 7 and beyond. But i know it goes to the appropriate function because if i request Economy with row 3 (which is invalid) it alerts me. But if i ask for first class with row7 it will act like nothing has been requested.
It won't let me post the html code but it will display as row1-13 on the left and A - F across the top. I use drop down list and I set the values to the corresponding for the options to their corresponding spot in a the 2-d array (eg if i select row 5 and seat c the value of row 5 is 5 and the value of C is 3)
var rowSeat;
function start()
{
rowSeat = new Array(14);
for(var i = 0; i <rowSeat.length; i++)
{
rowSeat[i] = new Array(7);
}
var j = 65;
for(var i = 1; i <rowSeat[0].length; i++)
{
rowSeat[0][i] = String.fromCharCode(j);
j++;
}
rowSeat[0][0] = " ";
for(var i = 1; i <rowSeat.length; i++)
{
rowSeat[i][0] = "Row "+i;
}
for(var i = 1; i <rowSeat.length; i++)
{
for(var j = 1; j <rowSeat[i].length; j++)
{
rowSeat[i][j] = "*";
}
}
display();
var subButton = document.getElementById("submitButton");
subButton.addEventListener("click", assign, false);
}
function display()
{
var results = "";
results+="<table>"
for(var i in rowSeat)
{
results+="<tr>";
for(var j in rowSeat[i])
{
results += "<td>" +rowSeat[i][j]+ "</td>";
}
results += "</tr>";
}
results+="</table>"
var show2 = document.getElementById( "show2" );
show2.innerHTML = results;
}
function assign()
{
var inputField = document.getElementById("classAssign");
var classType = inputField.options[inputField.selectedIndex].value;
if (classType == "FirstClass")
{
fClassSearch();
}
else if (classType == "Business")
{
bClassSearch();
}
else
{
eClassSearch();
}
display();
}
function fClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var test = document.getElementById( "test" );
test.innerHTML = row +" "+ seat;
if (row >2){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 1 and 2 are First Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function bClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
if (row <3 ||row >9){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 3 through 9 are BusinessClass";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function eClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var show1 = document.getElementById( "show" );
if (row <10){
show1.innerHTML = "Invalid choice only rows 10 through 13 are Economy Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
window.addEventListener("load",start, false);
</script>
var row = inputField.options[inputField2.selectedIndex].value;
inputField.options should be inputField2.options
inputField.options only goes to 6 because you only have 6 seats wide, but you are trying to look at the row in the seat list.

Categories