Validate an validation? - javascript

It works almost perfect, but i dont get why this code had to validate the 0 or my 10
I am doing a validation, that if the counter reaches 0 the button is deactivated. But for some reason, in the console and in the html it shows 0, but it makes me click once more to be able to deactivate the button. I'm not understanding what's going on. Exactly the same thing happens with the other stop, when you reach 10 you have to click again on the add button to deactivate the button.
const botonmas = document.getElementById("mas")
botonmas.addEventListener("click", ()=>{
increme(contador)
})
const botonmenoss = document.getElementById("menos")
botonmenoss.addEventListener("click", ()=>{
decre(contador)
})
const prodcSelct = document.getElementById("productosSelec")
let contador = 0
function increme(){
if(contador<10){
contador++
botonmenoss.disabled = false
}else if(contador == 10){
botonmas.disabled = true
}
prodcSelct.innerHTML = contador
console.log(contador)
}
function decre(){
if(contador>0){
contador--
botonmas.disabled = false
}else if(contador == 0){
botonmenoss.disabled = true
}
prodcSelct.innerHTML = contador
console.log(contador)
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script defer src="./contador2.js"></script>
</head>
<body>
<section>
<img src="" alt="">
<p id="precio"></p>
<p id="stock"></p>
<p id="productosSelec"></p>
<div>
<button id="menos">-</button>
<button id="mas">+</button>
<button id="comprar">Comprar</button>
</div>
</section>
</body>
</html>
i expect when it marks 0, the botton get disabled

So thanks to Pointy in comments allow me to see what is wrong
In the validation, i am changing the counter after the if checks. So correctly its
function increme(){
contador++
if(contador<10){
botonmenoss.disabled = false
}else if(contador == 10){
botonmas.disabled = true
}
prodcSelct.innerHTML = contador
console.log(contador)
}

Related

I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output

I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output.
Here is my code:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = document.getElementById('userInput').value;
if (input == randomNumber) {
alert.innerHTML = "Your guess is right " + "," + ",it was " + randomNumber;
} else if (number > randomNumber && input < 10) {
alert.innerHTML = "Your guess is to high";
} else if (input < randomNumber && input > 1) {
alert.innerHTML = "Your guess is too low ";
} else if (isNaN(input)) {
alert.innerHTML = "Invalid operator";
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
}
Here it the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<script src="script.js">
</script>
</body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="aginButton">Try again</button>
</div>
</html>
There a couple of issues in your code, first in the html code, you got the id of again button wrong, it should be like this:
<button id="againButton">Try again</button>
Then in the JS code, you should move the two addEventListener() methods out of the checkNumber() function definition. Most importantly, you set the input variable to be the value of the input html element. The value property returns string, and then you compare randomNumber with a string which will not work as expected.
Also, the alert.innerHTML will not work. alert() is a global method which will accepts a string type as its parameter. Please see the JS code corrected below:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = parseInt(document.getElementById('userInput').value);
if (input === randomNumber) {
window.alert("Your guess is right it was " + randomNumber)
} else if (input > randomNumber && input < 10) {
window.alert("Your guess is to high");
} else if (input < randomNumber && input > 1) {
window.alert("Your guess is too low ");
} else if (isNaN(input)) {
window.alert("Invalid operator");
}
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
You should also put your script tag right before the ending </body> tag for it to be able to do its tasks on the DOM elements. Take a look here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="againButton">Try again</button>
</div>
<script src="script.js"></script>
</body>
</html>
There were a few errors in your script. Check out this fixed version.
UPDATE
I now put the <script> element ahead of the <body> element to demonstrate the necessitiy of the window.onload=function(){...}. My whole script is now placed within this function as otherwise, the DOM elements the script refers to, would not yet exist.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
<script>
window.onload=function(){
const [form1,againButton,output,inp]="container,againButton,outputText,userInput".split(",")
.map(id=>document.getElementById(id)), setrndm=_=>randomNumber=Math.ceil(Math.random()*10);
var randomNumber;
setrndm();
form1.addEventListener('submit', checkNumber);
againButton.addEventListener('click', setrndm);
function checkNumber(ev) {
ev.preventDefault(); inp.select();
var input = inp.value;
if (input == randomNumber) {
console.log("Your guess is right, it was " + randomNumber);
} else if (input > randomNumber && input < 11) {
console.log("Your guess is to high");
} else if (input < randomNumber && input > 0) {
console.log("Your guess is too low ");
} else if (isNaN(input)) {
console.log("Invalid operator");
}
}
};
</script>
</head>
<body>
<form id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button type="button" id="againButton">Try again</button>
</form>
</body>

How can I change the display a message depending on which number the user has selected?

I want when somebody input a number lower than 4.2, my app shows message as result, but i can't make it happen.
I already tried with return.
JS code
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styleRx.css"/>
<script src="Rxappjs.js"></script>
<title>HVDN Rx app</title>
</head>
<body>
<div class="container">
<header>
<h1>Valoraciones de Rx</h1>
</header>
<div class="box">
<form action="">
<div class="values">
<label for="peso" id="peso__label">Peso</label>
<input class="text__input" type="number" step="0.1" id="number__select" placeholder="Peso"
min="0" required>
</div>
<button id="calcular" onclick="calculate()">Calcular</button>
</form>
<p id="results"></p>
</div>
</div>
</body>
</html>
You have the variable numberEl set to an html element and therefor it will never be less than or equal too 4.2. Try to get the value of that element instead:
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl.value <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}

todos list with a saved array and then retrieve it stuck?

i started an app todoslist , after creating first code simply of adding new todos in DOM
now my task is this :
addtodo :
// grab todo value
// pu tit in the array
// tell the draw method to redraw the todos
drawtodo :
grab the array
for each text add a todo entry in the documen
the array
my html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<title>TodoList</title>
</head>
<body>
<div class="todolist_box">
<h3> To Do List </h3>
<div class="input">
<input type="text" id ="inp" placeholder="Add new Task">
<button onclick="newTodo()" ><i> enter </i></button>
<button onclick="newTodo()" ><i> save </i></button>
<button onclick="drawtodo()" ><i> load </i></button>
</div>
<ul id="myUL">
</ul>
</div>
<script src="script.js" type="application/javascript"></script>
</body>
</html>
and this is my javascript code
function newElement() {
// this code doesn't work, but it gives you an idea
const li = document.createElement("li")
const newEntry = document.getElementById("inp").value
const u = document.createTextNode(newEntry)
li.appendChild(u)
document.getElementById("myUL").appendChild(li)
document.getElementById("inp").value = "Nothing"
// something like thi
let todos = []
function newTodo() {
let inpvalue = document.getElementById('inp').value
todos.push(inpvalue)
// trigger draw event
}
function drawtodo() {
for (var i = todos.length - 1; i >= 0; i--) {
let li = document.createElement('li')
let newlist = li.appendChild(document.createTextNode(todos[i]))
inpvalue.appendChild(newlist)
}
}
document.onload = function() {
// this will excute when the document loads
}
}
Try using Javascript event listener instead of onclick attribute in html.
HTML:
<button id="load" ><i> load </i></button> // Removed onclick attribute
JS:
document.getElementById("load").addEventListener("click", drawtodo, false);
same with enter and save buttons, when click triggers the newTodo function.

How should I make input permanent and make the input stay even after reloading the page in html? [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 1 year ago.
How should I make input permanent? Like for example, if I type in "Hello world" it should say "hello world " and "hello world" should be there even after reloading
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="content"></p>
<input type="text" id="userInput">
<script>
function getInputFromTextBox() {
let input = document.getElementById("userInput").value;
document.getElementById("content").innerHTML = input;
}
</script>
<button onclick="getInputFromTextBox()">submit</button>
</body>
</html>
You can use localStorage
// JAVASCRIPT
// Getting the value from localStorage
// The "key" here need to be the same defined below on the save() function
const getValue = localStorage.getItem("key");
if (getValue) {
document.getElementById("inputId").value = getValue;
}
function save() {
const setValue = document.getElementById("inputId").value;
// Here you can set 'key' with any name you like
// Setting the value in localStorage
localStorage.setItem("key", setValue);
}
<!-- HTML -->
<input type="text" id="inputId" />
<button onclick="save()">save value</button>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>Type here</h3>
<input type="text" id="inputText">
<input type="submit" id="submit">
<p id="seeHere"></p>
</body>
<script>
if(localStorage.getItem("info")==null){
}
else{
value();
}
let submit = document.getElementById("submit");
submit.addEventListener("click", function () {
console.log("hello world");
let inputText = document.getElementById("inputText");
let inputTextvalue = inputText.value;
inputText.value="";
let localValue = localStorage.getItem("info");
if (localValue == null) {
arr = [];
}
else {
arr = JSON.parse(localValue);
}
arr.push(inputTextvalue);
localStorage.setItem("info", JSON.stringify(arr));
value();
})
function value() {
let localValue = localStorage.getItem("info");
let seeHere = document.getElementById("seeHere");
seeHere.innerHTML="";
let seeHeretext="";
let parsedLocalvalue= JSON.parse(localValue);
parsedLocalvalue.forEach(element => {
seeHeretext=seeHeretext+`${element}<br>`;
});
seeHere.innerHTML=seeHeretext;
}
</script>
</html>
This is the required answer for the question see carefully .

Using checkboxes to render selected items to <div>

I have a populated table of JSON data with a checkbox next to each---I want it so that when a checkbox is selected it pushes that selected item into an array (in this case the div myFave.hs-gc-header).
When I console.log(arr) it just shows a bunch of empty arrays (I believe one for each of the list items). Not sure why this is--if anyone could shed light on this that would be great.
I think the problem lies with the populateArr() block, but I can't say for sure.
JS:
loadTableData() {
let tableRes = redactedName.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
// "FileName": obj.FileLeafRef,
// "Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name
}
});
let allTitles = tableRes;
for (var i = 0; i < allTitles.length; i++) {
let tr = $("<tr/>");
$(tr).append("<td> </td>");
$(tr).append("<td>" + allTitles[i].Titles + "</td>");
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
/* ---------- */
function populateArr() {
let arr = [];
$(".checkbox input[type='checkbox']:checked").each(function() {
arr.push($(this).val());
});
return arr;
}
$("#myFave.hs-gc-header").click(function() {
populateArr();
})
};
HTML snippet
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1, shrink-to-fit=no">
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<!------------------------------->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.6.2/core.min.js"></script>
<script
type="text/javascript"
src="dist/js/jquery_wrapper.min.js"></script>
</head>
<body>
<script src="./bundle.js"></script>
<div class="km-div-container">
<div class="col-md-2"> <!-- Left -->
<div class="form-group">
<input
type="search"
class="form-control"
id="searchbar"
placeholder="Search All Documents...">
</div>
<div id="myFave.hs-gc-header">
<p>My Favorites:</p>
</div>
</div>
</div> <!-- km -->
</body>
</html>
I don't think this will work, I had a similar problem while using vanilla JavaScript.
When you append to the dom like below, you won't be able to add event listeners to the html tags.
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
You should do this in your for loop when you filter for the .checkbox with attribute check it should work.
// convert code to jquery
let checkbox = document.createElement('checkbox');
check.setAttribute('type', 'checkbox');
checkbox.className = 'checkbox';
tr.appendChild(checkbox);

Categories

Resources