can't access value through input using button - javascript

I'm doing some exercises and come across where I can't pass the value from the input box to a function inside a script, I don't really know what I have done wrong, I tried different things but didn't really work out. How can I make it work? I want to able to enter a number then press a button so that it prints pyramid according to given number, here is my code :
window.onload = function() {
let aantalLijnen = parseInt(document.getElementById('number').value);
document.getElementById("button").onclick = stars();
function stars() {
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>

You're calling stars() and assigning the result to the onclick handler.
You need to pass the function itself...
document.getElementById("button").onclick = stars;
Or just create an anonymous function directly...
document.getElementById("button").onclick = function() {
...
}
As pointed out by #j08691, you are setting the value of aantalLijnen on the page load.
Instead you want to get the value at the time the function runs, so you need to move it into the function itself...
window.onload = function() {
document.getElementById("button").onclick = function () {
let aantalLijnen = parseInt(document.getElementById('number').value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>

you have to get the value from input every time you click on the button
window.onload = function () {
const numberElem = document.getElementById('number');
document.getElementById("button").addEventListener('click', stars);
function stars() {
let aantalLijnen = parseInt(numberElem.value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};

Besides what already said by others
Don't use onclick handlers. Stick to cumulative listeners with addEventListener
You could use String.prototype.repeat();
Defer your script or place it right before the closing </body> tag
Learn the difference between let and const
function stars() {
const num = parseInt(document.getElementById('number').value, 10);
if (num < 2 || num > 10) return console.log("Use from 2 to 10 inclusive");
const row = '*'.repeat(num);
console.log(row)
}
document.getElementById("button").addEventListener('click', stars);
Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button>

Related

Finishing a sub-function with setTimeout loop before function

I've been wrestling with a timing issue in my code for a few nights now, and can't come up with the correct solution.
Psuedo code description:
//event listener on button trigger a die roll each time it is clicked
// call animation function
//generate random values x number of times
//display each result with setTimeout
//run code to determine final "settled upon" value and display results
HTML:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<head>
<title>Make Cards</title>
</head>
<body>
<p>Total:<span id="total"></span></p>
<div id="contain">
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<br>
<button id="rollBtn">Roll</button>
<input type="number" value = "1" min="1" max="6" id = "numDice">
</div>
</body>
</html>
Javascript:
var diceValue = ["&#9856", "&#9857", "&#9858", "&#9859", "&#9860",
"&#9861"];
var dice = document.querySelectorAll(".die");
// select number of dice
var numDice = document.querySelector("#numDice");
// convert string to value
var newNumDice = Number(numDice.value);
var roll = document.querySelector("#rollBtn");
var total = document.querySelector("#total");
// make animation function
// call animation function
init();
function init(){
displayDice();
}
//THIS IS THE BUTTON LISTERNER
roll.addEventListener("click", function(){
//THIS SHOULD RUN BEFORE THE REST OF THE FUNCTION (BUT DOESN'T SEEM TO)
animate();
var subTotal = 0;
for (var i = 0; i < newNumDice; i++){
var value = generateRandomDice()
dice[i].innerHTML = diceValue[value];
subTotal = subTotal + (value+1);
total.innerHTML = subTotal;
}
for (var i = 0; i < 6; i++){
dice[i].style.color = "black";
}
})
numDice.addEventListener("click", function(){
total.innerHTML = "-";
newNumDice = Number(numDice.value);
resetDice();
displayDice();
// console.log(Number(numDice.value));
})
function resetDice(){
for (var i = 0; i < diceValue.length; i++){
dice[i].innerHTML = "";
}
}
// only display chosen number of dice
function displayDice(){
for (var i = 0; i < newNumDice; i++){
dice[i].innerHTML = diceValue[i];
}
}
function generateRandomDice(){
var dieSide = Math.floor(Math.random() * 6);
return dieSide;
}
//ATTEMPT AT WRITING CODE FOR ANIMATION
function animate(){
for (var i = 0; i < 50000; i++){
var ani = setTimeout(rolling, 650);
}
}
function rolling(){
for (var i = 0; i < newNumDice; i++){
var value = generateRandomDice()
dice[i].innerHTML = diceValue[value];
dice[i].style.color = "grey";
}
}
Not sure what is going on, but it appears to me that the animate(); code is not run until the rest of eventListener is finished. Any help is great, thank you.
The issue is that you are waiting for asynchronous code to finish before you execute synchronous code. Every time you call setTimeout, it is storing the function to call for when it's ready to be called (which is 650 ms from 'now'!).
To fix, you can await for your animation to finish. Here's how I got it working on your codepen:
Change animate to:
function animate() {
return new Promise((resolve, reject) => {
for (let i = 0; i < 50000; i++) {
setTimeout(() => {
rolling();
if(i == 49999)
resolve();
}, 650);
}
});
}
and then you can await for the Promise to resolve by changing your click listener to this:
roll.addEventListener("click", async function() {
await animate();
var subTotal = 0;
for (var i = 0; i < newNumDice; i++) {
var value = generateRandomDice();
dice[i].innerHTML = diceValue[value];
subTotal = subTotal + (value + 1);
total.innerHTML = subTotal;
}
for (var i = 0; i < 6; i++) {
dice[i].style.color = "black";
}
});
The result showing afterward was correct for me.
Hope that helps!

How do I create different button for each item in an array / JavaScript

Here's my code:
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
}
}
I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.
The best way is to append created buttons in container.Each by each
var never = [1,2,3,4,7];
function please () {
var more=document.getElementById("more");
for (var i = 0; i < never.length; i++) {
var butt=document.createElement("button");
butt.innerHTML=never[i];
more.appendChild(butt);
}
}
By appending to innerHTML instead of assigning, like
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
}
}
please();
<div id="more">
</div>

Jquery code won't run loaded from footer, but run from console

I'm trying to get a value and pass it to a hidden input in order to send form data via $_POST. I have a dropdown button and the following code in order to update the value when a user select an option:
jQuery(document).ready(function($) {
var espSeleccionada = $('button[data-id="select-especialidad"]');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#boton-prueba').text(x);
});
});
The code is supposed to pass the value from one button to another, as shown in here the example, but, when I load the code from WordPress header/footer/theme nothing happens. Instead, when I write it on the console it works fine. There are no JS errors in console.
Please note that I'm using .text() to test if the code works, but it would have .val() before going live.
This is the button HTML:
<button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" data-id="select-especialidad" title="Hacienda" aria-expanded="false"><span class="filter-option pull-left">Hacienda</span></button>
Here is an example: https://fiddle.jshell.net/t9mvoxj5/
EDIT TO INCLUDE THE FULL CODE:
( function( $ ) {
var num_cols = 3,
container = $('#menu-preparadores-de-oposiciones-en'),
listItem = 'li',
listClass = 'sub-list';
container.each(function() {
var items_per_col = new Array(),
items = $(this).find(listItem),
min_items_per_col = Math.floor(items.length / num_cols),
difference = items.length - (min_items_per_col * num_cols);
for (var i = 0; i < num_cols; i++) {
if (i < difference) {
items_per_col[i] = min_items_per_col + 1;
} else {
items_per_col[i] = min_items_per_col;
}
}
for (var i = 0; i < num_cols; i++) {
$(this).append($('<ul ></ul>').addClass(listClass));
for (var j = 0; j < items_per_col[i]; j++) {
var pointer = 0;
for (var k = 0; k < i; k++) {
pointer += items_per_col[k];
}
$(this).find('.' + listClass).last().append(items[j + pointer]);
}
}
});
if ($("body").hasClass("page-id-64")) {
$('.tab-content').addClass('col-sm-9');
$('#custom-tabs-0').tabCollapse();
}
} ) ( jQuery );
jQuery(document).ready(function($) {
var espSeleccionada = $('button[data-id="select-especialidad"]');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#boton-prueba').text(x);
});
});
Well, the code is fine, the problem is that the target button[data-id="select-especialidad"] is being used by bootstrap-select and even if bootstrap-select loads before my code, it takes a few seconds (or at least a bit) to process the information.
So the code should be wrapped after a function that checks that the event has been loaded. This is the final code:
$('#select-especialidad').on('loaded.bs.select', function (e) {
var y = $(this).val();
$('#select-especialidad-hidden').val(y);
var espSeleccionada = $('button[data-id="select-especialidad"] > span.filter-option.pull-left');
espSeleccionada.on("click", function() {
var x = $(this).text();
$('#select-especialidad-hidden').val(x);
});
});
loaded.bs.select here more info on the bootstrap-select events.

Create 2 arrays

I need to create 2 arrays in JS from an input value. The first should contain all my inputs values and the second one should contain all my inputs values but for the last one.
I tried this but it doesn't work.
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
var comp = [];
function clickHandler()
{
n = input.value;
for (var i =0; i < 10; i++)
{
valori.push(parseInt(n));
comp = valori.pop();
console.log(valori);
console.log(comp);
break;
}
}
</script>
</body>
The ideea is that I want to check if an input value has been entered before. I thought of doing that by creating 2 arrays like I mentioned before and then compare "n" to the "comp" array
if you are just to check element exist or not.. why dont u why indexOf(n)??
no need to create two array and for loop etc etc.. just indexOf will work for you..
check the below code..
<html>
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
function clickHandler()
{
if(isNaN(input.value))
{
alert('value is not a Number');
}
else
{
var nbr = parseInt(input.value);
if(valori.indexOf(nbr) < 0)
{
valori.push(nbr);
input.value="";
}
else
{
alert('element already exists.');
}
}
}
</script>
</body>
</html>
U are setting value on comp which is array u need to set value at index .
function clickHandler()
{
var is = true;
var n = parseInt(document.getElementById("inp").value);
if(!isNaN(n))
{
for (var i =0; i < valori.length; i++)
{
if(n === valori[i])
{
console.log("duplicate");
is = false;
break;
}
}
if(is)
valori.push(n);
}
console.log(valori);
}
DEMO

Javascript/HTML button click error

I am using JavaScript with my html page to try an get a button to show a message to the user, but when I click the button, nothing happens. Is there something I am doing wrong?
<input type="button" name="get" id="getmsg" value="Get Message"/>
<script type="text/javascript">
document.getElementById("getmsg").onclick = msgtouser;
function (msgtouser)
{
var msg = "";
var topick = "012345";
for(var i = 0; i < 8; ++i)
{
msg += topick[Math.floor((Math.random()*topick.length)+1)];
}
alert(msg);
}
</script>
That is not how you define a function
function (msgtouser)
should be
function msgtouser ()
Try on this way:
document.getElementById("getmsg").onclick = msgtouser;
function msgtouser()
{
var msg = "";
var topick = "012345";
for(var i = 0; i << 8; ++i)
{
msg += topick[Math.floor((Math.random()*topick.length)+1)];
}
alert(msg);
}
Note function msgtouser() instead function (msgtouser).
Here are some of the points which you need to correct:
function (msgtouser) should be function msgtouser ()
Use window.load or .ready() function.
My guess is you are trying to generate random number between 1 and 012345 i.e topick.length,if so then remove that outer array topick[].
Here is a working code:
window.onload=function(){
document.getElementById("getmsg").onclick = msgtouser;
function msgtouser()
{
var msg = "";
var topick = "012345";
for(var i = 0; i < 8; ++i)
{
msg += Math.floor((Math.random()*topick.length)+1);
}
alert(msg);
}
}

Categories

Resources