buttons are not show assigning to vaules to graphing calculator - javascript

I not sure if this supper basic or not but I am trying to add number values to some buttons through onclick functions. All done in html and javascript.
It can display the numbers fine but doesn't seem to make the numbers have any values to them if that makes sense. I just keep getting null values. Is it because of all the onclick events?
Below is the html.
var getvaule7.value = document.getElementsByClassName("7");
getvaule7.value = 7;
var getvaule8 = document.getElementsByClassName("8");
getvaule8.value = 8;
var getvaule9 = document.getElementsByClassName("9");
getvaule9.value = 9;
var getvaule4 = document.getElementsByClassName("4");
getvaule4.value = 4;
var getvaule5 = document.getElementsByClassName("5");
getvaule5.value = 5;
var getvaule6 = document.getElementsByClassName("6");
getvaule6.value = 6;
var getvaule1 = document.getElementsByClassName("1");
getvaule1.value = 1;
var getvaule2 = document.getElementsByClassName("2");
getvaule2.value = 2;
var getvaule3 = document.getElementsByClassName("3");
getvaule3.value = 3;
var getvaule0 = document.getElementsByClassName("0");
getvaule0.value = 0;
function number7() {
document.getElementById("show").value = getvaule7.value;
}
console.log(number7());
function number8() {
document.getElementById("show").value = getvaule8.value;
}
function number9() {
document.getElementById("show").value = getvaule9.value;
}
function number4() {
document.getElementById("show").value = getvaule4.value;
}
function number5() {
document.getElementById("show").value = getvaule5.value;
}
function number6() {
document.getElementById("show").value = getvaule6.value;
}
function number1() {
document.getElementById("show").value = getvaule1.value;
}
function number2() {
document.getElementById("show").value = getvaule2.value;
}
function number3() {
document.getElementById("show").value = getvaule3.value;
}
function number0() {
document.getElementById("show").value = getvaule0.value;
}
<body>
<h1 style="text-align: center;">
Graphing Calculator from Scratch
</h1>
<div id="Text box" style="text-align: center;">
<input type="text" name="" id="show">
</div>
<br></br>
<div style="text-align:center" id="click-row">
<div id="row one" ><button type="button" class="7" onclick="number7()" value=7> 7</button>
<button type="button" class="8" onclick="number8()" >8</button>
<button type="button" class="9" onclick="number9()">9</button>
</div>
<div id="row two"><button type="button" class="4" onclick="number4()">4</button>
<button type="button" class="5" onclick="number5()">5</button>
<button type="button" class="6" onclick="number6()">6</button>
</div>
<div id="row three"><button type="button" class="1" onclick="number1()">1</button>
<button type="button" class="2" onclick="number2()">2</button>
<button type="button" class="3" onclick="number3()">3</button>
</div>
<button type="button" class="0" onclick="number0()">0</button>
<button type="button" class=".">.</button>
<button type="button" class="𝝅">𝝅</button>
<div id="row 5">
<div id="row 5"><button type="button" class="+/-">+/-</button>
<div id="row 5"><button type="button" class="+">+</button>
<div id="row 5"><button type="button" class="-">-</button>
<button type="button" onclick="enter()" >=</button>
</div>
<br>
<button onclick="document.getElementById('show').value = ''" style="text-align:center;">Clear input field</button>
</div>
</div>
</div>
</div>
</body>
</html>

First, the way you are going about it is not the best way to do it but since you are just getting started I will not confuse you and just correct your code instead.
There are a couple of errors in your code
button does not have value it has innerText property. value property
is for input tags only.
use += when you are trying to set value to
show input since = will erase what was in it before hands.
you have not defined enter() function that was it gives you that error you
have to create enter function first
another thing is document.getElementsByClassName("7") does not retun one element like getElementById but it returns an array that is why if you are using gelementsByClassName you have to also write [number] where number is the index of your element in the returned array. in your case number is 0 which means the first element in the array.
another one is you dont need to use getValue7.value = document.get... since you are using it just for storing the element you can just use getValue = document.getlE.....
and you html tag nesting was incorrect please nest them correctly.
To help you understand the correct solution. I wrote minimum code for you project down below. please compare it with your code to see what is wrong,
var getvaule7 =document.getElementsByClassName("7")[0];
var getvaule8 =document.getElementsByClassName("8")[0];
var getvaule9 =document.getElementsByClassName("9")[0];
var getPlus = document.getElementsByClassName("plus")[0];
function number7(){
document.getElementById("show").value += getvaule7.innerText;
}
function number8(){
document.getElementById("show").value += getvaule7.innerText;
}
function number9(){
document.getElementById("show").value += getvaule7.innerText;
}
function plus(){
document.getElementById("show").value += getPlus.innerText;
}
function enter(){
document.getElementById("show").value = eval(document.getElementById("show").value);
}
<h1 style="text-align: center;">
Graphing Calculator from Scratch
</h1>
<div id="Text box" style="text-align: center;">
<input type="text" name="" id="show">
</div>
<br></br>
<div style="text-align:center" id="click-row">
<div id="row one" >
<button type="button" class="7" onclick="number7()" value=7>7</button>
<button type="button" class="8" onclick="number8()" >8</button>
<button type="button" class="9" onclick="number9()">9</button>
</div>
<div id="row 5">
<button type="button" onclick="plus()" class="plus">+</button>
<button type="button" onclick="enter()" >=</button>
</div>
<br>
<button onclick="document.getElementById('show').value = ''" style="text-align:center;">Clear input field</button>

function load() {
let num7=document.getElementById("7").addEventListener('click',()=>{
document.querySelector(".show").value+=7;
})
let num8=document.getElementById("8").addEventListener('click',()=>{
document.querySelector(".show").value+=8;
})
var userEnter1= parseInt(document.querySelector(".show").value);
var userEnter2=parseInt(document.querySelector(".show").value);
[0]
// HOW TO MAKE SURE THAT A USER CAN INPUT ANOTHER DATA AFTER PRESSING THE +
let add=document.getElementById("add").addEventListener('click',()=>{
document.querySelector(".show").value+="+";
userEnter1+userEnter2;
})
const equals=document.getElementById("equals").addEventListener('click',()=>{
console.log( userEnter1+userEnter2);
});
}
window.onload = load;
}
window.onload = load;
<body>
<h1 style="text-align: center;">
Graphing Calculator from Scrach
</h1>
<div id="Text box" style="text-align: center;">
<input type="text" class="show" id="clear">
</div>
<br></br>
<div style="text-align:center" id="click-row">
<div id="activate" >
<div id="row one">
<input type="Button" id="7" class="num7" value="7" > </input>
<input type="Button" id="8" value="8" > </input>
</div>
<div id="row 2">
<input type="Button" id="add" value="+" onclick="" > </input>
<input type="Button" id="equals" value="=" > </input>
</div>
</div>
<br>
<button onclick="document.getElementById('clear').value = ''" style="text-align:center;">Clear input field</button>
</div>
</div>
</div>
</div>
</body>
</html>

Related

How to use localStorage in vanillaJS

I have 2 html pages which are for a laundry services website and I have a javascript file. The first html page is called booking page where user get to book the number of clothes to be washed and it automatically calculate the total amount to be paid. Now on the second html page which is the summary page, I want the same amount on the booking page to reflect on the summary page showing the total amount and also also the buttons (plus and minus button) adding to it in the summary page.
I tried using localStorage for this project and I couldn't figure it out.
Skirt(s)</p>
<div>
<p>
<button type="button" class="sub" data-
target="skirts">−</button>
<input type="text" value="0"
class="field_skirts" />
<button type="button" class="add" data-
target="skirts">+</button>
<p class="display_skirts" name="price"
max="3" min="1">₦ 0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/blouse.png" /></div>
<p class="second-booking-container-icon"
name="product" value="100" id="qnty_4">
Blouse(s)</p>
<div>
<p>
<button type="button" class="sub" data-
target="blouses">-</button>
<input type="text" value="0"
class="field_blouses" />
<button type="button" class="add" data-
target="blouses">+</button>
<p class="display_blouses" name="price"
max="3" min="1">₦ 0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/jacket.png" /></div>
<p class="second-booking-container-icon-long"
name="product" value="100" id="qnty_5">Suit/Jacket(s)
</p>
<p>
<button type="button" class="sub" data-
target="suits">-</button>
<input type="text" value="0" class="field_suits"
/>
<button type="button" class="add" data-
target="suits">+</button>
<p class="display_suits" name="price" max="3"
min="1">₦ 0</p>
</p>
</div>
</div>
<div class="third-booking-container">
<p>Total:₦ <span id="totalValue"></span></p>
<button>Set pick up date
<FontAwesomeIcon class="second-container-button-right"
icon="angle-right" /></button>
</div>
</div>
var subElm = document.querySelectorAll('.sub');
var addElm = document.querySelectorAll('.add');
var totalValueElm = document.getElementById('totalValue');
for (var i = 0; i < subElm.length; i++) {
subElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
if (currentValue !== 0) {
var incValue = currentValue - 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
// displayElm.innerHTML = "₦" + strValue;
displayElm.innerHTML = "₦ " + incValue * 100;
totalValueElm.innerText = Number(totalValueElm.innerText) -
100;
}
});
addElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
var incValue = currentValue + 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
// displayElm.innerHTML = "₦" + strValue;
displayElm.innerHTML = "₦ " + incValue * 100;
totalValueElm.innerText = Number(totalValueElm.innerText) + 100;
});
}
<div class="summaryContainer">
<div class="summaryNavBar"><p
className="summaryTitle">Summary</p></div>
<div class="summaryContent">
<p class="total" id="total">Total:</p>
<p class="sum">₦0.00</p>
</div>
<div class="summaryCard">
<div class="summary-card-title">
<div>Item</div>
<div>Quantity</div>
</div>
<div class="summary-card-content">
<div >Shirt(s)</div><div id="
first" class="summary-quantity"><button type="button"
id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content">
<div>Trouser(s)</div>
<div class="summary-quantity" id="second">
<button type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content" id="third">
I want the total calculation of price on the booking page to also appear at the summary page when I automatically click on summary page
In your booking page, store the total price in local storage using localStorage.setItem().
localStorage.setItem('totalPrice', JSON.stringify(totalValue));
In your summary page, access this total price using localStorage.getItem().
var totalPrice = JSON.parse(localStorage.getItem('totalPrice'));
Note that all the values are stored as strings, so you have to use JSON.parse() to convert the string back to the object or value.

How do I perform math on items in array, when some are strings and some are numbers?

I am attempting to create a calculator using jQuery and JavaScript. My approach involves adding each entry (numbers and operators) to an array and then performing math on them. The calculator itself is incomplete as a cannot get the items in the array to sum/subtract/multiply/divide based on what button is clicked.
I've tried creating 2 separate arrays thinking the operator should not be either array, but that did not work and would create more issues down the road.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container w-25 align-left">
<form>
<div class="form-group">
<input type="text" class="form-control align-left" id="box" value='' placeholder="" readonly>
</div>
</form>
</div>
<div class='container w-25'>
<div class="container pb-2">
<button type="button" id='seven' value='7' class="num-btn btn btn-dark">7</button>
<button type="button" id='eight' value='8' class="num-btn btn btn-dark">8</button>
<button type="button" id='nine' value='9' class="num-btn btn btn-dark">9</button>
<button type="button" id='divide' value='/'class="op-btn btn btn-dark">/</button>
</div>
<div class="container pb-2">
<button type="button" id='four' value='4' class="num-btn btn btn-dark">4</button>
<button type="button" id='five' value='5' class="num-btn btn btn-dark">5</button>
<button type="button" id='six' value='6' class="num-btn btn btn-dark">6</button>
<button type="button" id='multiply' value='*' class="op-btn btn btn-dark">*</button>
</div>
<div class="container pb-2">
<button type="button" id='one' value='1' class="num-btn btn btn-dark">1</button>
<button type="button" id='two' value='2' class="num-btn btn btn-dark">2</button>
<button type="button" id='three' value='3' class="num-btn btn btn-dark">3</button>
<button type="button" id='minus' value='-' class="op-btn btn btn-dark">-</button>
</div>
<div class="container pb-2">
<button type="button" id='zero' value='0' class="num-btn btn btn-dark">0</button>
<button type="button" id='decimal' value='.' class="num-btn btn btn-dark">.</button>
<button type="button" id='plus' value='+' class="op-btn btn btn-dark">+</button>
<button type="button" id='equals' value='=' class="eq-btn btn btn-dark">=</button>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src='scripts.js'></script>
</html>
$('document').ready(function () {
var num1 = []; //creates array for first number set
var result = '';
$('.num-btn').click(function () {
num1.push($(this).prop('value')); //add each number to array
arr1 = num1.join(' '); //joins numbers without comma using ''
$('#box').val(arr1);
console.log(arr1);
result = (arr1);
console.log(result);
});
$('.op-btn').click(function () {
var operator = $(this).attr('value');
num1.push(operator);
console.log(operator);
$('#box').val(''); //clears input #box
console.log($('#box').val())
});
});
You can use eval function result = eval(arr1);
More reference at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
$('document').ready(function () {
var num1 = []; //creates array for first number set
var result = '';
$('.num-btn').click(function () {
num1.push($(this).prop('value')); //add each number to array
arr1 = num1.join(' '); //joins numbers without comma using ''
$('#box').val(arr1);
console.log(arr1);
result = eval(arr1);
console.log(result);
});
$('.op-btn').click(function () {
var operator = $(this).attr('value');
num1.push(operator);
console.log(operator);
$('#box').val(''); //clears input #box
console.log($('#box').val())
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container w-25 align-left">
<form>
<div class="form-group">
<input type="text" class="form-control align-left" id="box" value='' placeholder="" readonly>
</div>
</form>
</div>
<div class='container w-25'>
<div class="container pb-2">
<button type="button" id='seven' value='7' class="num-btn btn btn-dark">7</button>
<button type="button" id='eight' value='8' class="num-btn btn btn-dark">8</button>
<button type="button" id='nine' value='9' class="num-btn btn btn-dark">9</button>
<button type="button" id='divide' value='/'class="op-btn btn btn-dark">/</button>
</div>
<div class="container pb-2">
<button type="button" id='four' value='4' class="num-btn btn btn-dark">4</button>
<button type="button" id='five' value='5' class="num-btn btn btn-dark">5</button>
<button type="button" id='six' value='6' class="num-btn btn btn-dark">6</button>
<button type="button" id='multiply' value='*' class="op-btn btn btn-dark">*</button>
</div>
<div class="container pb-2">
<button type="button" id='one' value='1' class="num-btn btn btn-dark">1</button>
<button type="button" id='two' value='2' class="num-btn btn btn-dark">2</button>
<button type="button" id='three' value='3' class="num-btn btn btn-dark">3</button>
<button type="button" id='minus' value='-' class="op-btn btn btn-dark">-</button>
</div>
<div class="container pb-2">
<button type="button" id='zero' value='0' class="num-btn btn btn-dark">0</button>
<button type="button" id='decimal' value='.' class="num-btn btn btn-dark">.</button>
<button type="button" id='plus' value='+' class="op-btn btn btn-dark">+</button>
<button type="button" id='equals' value='=' class="eq-btn btn btn-dark">=</button>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src='scripts.js'></script>
</html>
What you're trying to do is actually a bit complex because particular string values (such as *) need to trigger particular operations (such as multiplication).
One way to handle this is with the operation function below. You would run this function once for each operation selected by the user.
The evaluate function assumes that you have already collected numbers into one array and operators into a separate array. (This separation helps to prevent type errors, and make it easy to tell how many operations need to be performed.) The function accumulates the mathematical result in the resultSoFar variable, and prints it when there are no operations left to perform.
let nums = [8, 5, 2];
let ops = ["*", "+"];
evaluate(nums, ops);
function operation(a, operator, b){ // eg: operation(8, "*", 5)
switch (operator){
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b; // This will fail spectacularly if b is zero
default:
console.log("Unknown operator: " + operator);
return NaN;
}
}
function evaluate(numsArray, opsArray){
// Requires numsArray to have exactly one item more than opsArray
if(opsArray.length + 1 != numsArray.length){
console.log("Error: Array lengths mismatch");
return; // Function will stop here if lengths aren't compatible
}
// Starts out with the first number
let resultSoFar = numsArray[0];
// We care about the index of each item, which is the second argument
// to the anonymous function that we pass to `Array.forEach`.
// The first argument is not important to us, as its name implies.
opsArray.forEach(function(_, index){
// Applies the operation to `resultSoFar` and the next number
resultSoFar = operation(resultSoFar, opsArray[index], numsArray[index + 1]);
// (In the example, there are two operations to perform:
// The first time through the loop, 8 * 5 = 40
// The second time through the loop, 40 + 2 = 42)
});
console.log(resultSoFar);
}
I leave it to you to collect the values from the user (and update the display after each entry.)
You might want to use the parseInt function to convert values from inputs into numerical values.
Note: The evaluate function could be implemented more succinctly by using the Array.reduce function, but this example uses more verbose syntax to be more easily readable by anyone unfamiliar with that (very useful) function.

Creating a store button to add/remove amount and display amount (Very Basic)

Seeking assistance with creating add and subtract buttons within a form to add and remove amount of a line of stock.
Similar to:
I'm new to html and very new to javascript.
function minus(){
var bCount = parseInt(document.calculateCart.count.value);
var count = bCount--;
document.calculateCart.count.value = count;
}
function minus(){
var bCount = parseInt(document.calculateCart.count.value);
var count = bCount++;
document.calculateCart.bCount.value = count;
}
<div class="productForm">
<form name="calculateCart" action="#">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="int" name="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
If you want to chane your number using buttons and using text-input, you can change your code to that:
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="number" name="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
<script>
function minus(){
document.calculateCart.count.value = --document.calculateCart.count.value;
}
function add(){
document.calculateCart.count.value = ++document.calculateCart.count.value;
}
</script>
In HTML don't exist type of input - int, you need to use number or text.
If you want change value only using the buttons, you can make it like this:
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<span id="your-number">0</span>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
<script>
var a = 0;
function minus(){
a -= 1;
document.getElementById('your-number').innerHTML = a;
}
function add(){
a += 1;
document.getElementById('your-number').innerHTML = a;
}
</script>
Your both functions are named 'minus'. One of them (the second one) should be 'add'.
you have s sort of a typo in your code: your function for adding valus is called minus(). So you have two functions with the same name
I believe you are getting the value of count in a wrong way. You should assign an id to the input and use getElementById
working code:
function minus(){
var bCount = document.getElementById('count').value;
bCount--;
document.getElementById('count').value = bCount;
document.getElementById('count');
}
function add(){
var bCount = document.getElementById('count').value;
bCount++;
document.getElementById('count').value = bCount;
document.getElementById('count');
}
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="int" name="count" id="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
You need to use document.getElementById in order to get old textbox value.
Please check below code:
function minus(){
var oldVal = parseInt(document.getElementById("myVal").value);
oldVal--;
document.getElementById("myVal").value = oldVal;
}
function add(){
var oldVal = parseInt(document.getElementById("myVal").value);
oldVal++;
document.getElementById("myVal").value = oldVal;
}
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="text" id="myVal" name="count" value="0">
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
you have two function minus, one of them must be add
if you want use attributre name to select, you need to use something look like:
document.getElementsByName("count")[0].tagName

Get specific h3 from multiple cloned divs

I'm trying to get a specific h3 from a cloned div when pressing a button. Since I got 10 cloned divs with the exact same values I want to be able to get the h3 from the specific button I just pressed.
$("body").on("click", ".btnFavorite", function() {
var favoriteMovieTest = $(this).parent().find("h3");
alert(favoriteMovieTest);
});
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
You can do it like this:
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
}
$(".btnFavorite").on("click", function() {
var favoriteMovieTest = $(this).closest("div").find("h3");
favoriteMovieTest.css('color','red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
As you can see i get that specific h3 element from the button.
Now you can do whatever you like with it, for example manipulate it's CSS code to change the color, like I did.
Try this.
Note : Keep code to attach event handler after for loop because if it is executed before for loop, elements created by for loop won't be attached with a event handler.
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search").find("h3").append(" "+i);
}
$(".btnFavorite").on("click", function() {
var favoriteMovieTest = $(this).siblings("h3")[0];
console.log(favoriteMovieTest);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
You can climb up and down the DOM to get and title or index number of which cloned element was clicked.
$("body").on("click", ".search .btnFavorite", function(e) {
var elIndex = Array.from(e.target.parentNode.parentNode.children).indexOf(e.target.parentNode);
var favoriteMovieTest = e.target.parentNode.innerText;
alert('H3: ' + favoriteMovieTest + ' index: ' + elIndex);
});
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3 id='title'>Title(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>

How to get innerHTML for each button and display in text box?

Just some of the HTML, but it's the whole alphabet. I want to click any button and that letter will go in the text box. Do i have to create getelementbyID for each button or can I create some kind of loop?
html - this is the html and it is basically the alphabet.
<div id="alpha" >
<br/>
<div align="center">
<button id="q" class="letters">Q</button>
</div>
<div align="center">
<button id="w" class="letters" onclick="theclick()">W</button>
</div>
<div align="center">
<button id="e" class="letters">E</button>
</div>
<div align="center">
<button id="r" class="letters">R</button>
</div>
<div align="center">
<button id="t" class="letters">T</button>
</div>
**THIS IS THE JAVASCRIPT I HAVE. I only have the onclick function for button "w" for testing**
javascript - this is the javascript, it's not working but want to do some kind of loop to make it a more simple javascript code
<script>
function theclick() {
var x = document.getElementByClassName("letters").innerHTML;
document.getElementById("textbox").value = x;
};
</script>
One approach I'd suggest is the following, using plain JavaScript:
// creating a named function to act as the event-handler:
function buttonOutput() {
// to support older browsers you may need to declare
// your variables with 'var' rather than 'let';
// here we cache the textarea, via its id attribute:
let textarea = document.querySelector('#result');
// and here we update the textContent of that
// textarea to the existing textContent with the
// addition of the newly-clicked element (the
// 'this' is the <button> element and is passed
// from the EventTarget.addEventListener() method)
// after calling String.prototype.trim() on that
// textContent (to remove leading and trailing
// white-space):
textarea.textContent += this.textContent.trim();
}
// here we retrieve the <button> elements with the class
// of 'letters' from the document:
let buttons = document.querySelectorAll('button.letters'),
// here we convert the Array-like NodeList into an Array,
// using Array.from():
buttonArray = Array.from(buttons);
// using Array.prototype.forEach() to iterate over the
// Array of <button> elements:
buttonArray.forEach(
// 'button' is the current array-element of the Array
// over which we're iterating; here we bind the
// buttonOutput() function as the event-handler for
// the 'click' event (note the deliberate lack of
// parentheses in the function name):
button => button.addEventListener('click', buttonOutput)
);
div > div {
text-align: center;
}
div > button {
width: 30%;
text-align: center;
}
<div id="alpha">
<div>
<button id="q" class="letters">Q</button>
</div>
<div>
<button id="w" class="letters" onclick="theclick()">W</button>
</div>
<div>
<button id="e" class="letters">E</button>
</div>
<div>
<button id="r" class="letters">R</button>
</div>
<div>
<button id="t" class="letters">T</button>
</div>
<div>
<button id="y" class="letters">Y</button>
</div>
</div>
<textarea id="result"></textarea>
JS Fiddle demo.
The above snippet leans heavily towards using ES6 features, such as let, Array.from() and Arrow functions; an ES5 alternative – compatible with older browsers – follows:
// creating a named function to act as the event-handler:
function buttonOutput() {
// 'let' changed to 'var':
var textarea = document.querySelector('#result');
textarea.textContent += this.textContent.trim();
}
// here we retrieve the <button> elements with the class
// of 'letters' from the document:
let buttons = document.querySelectorAll('button.letters'),
// here we convert the Array-like NodeList into an Array,
// using Function.prototype.call() and Array.prototype.slice():
buttonArray = Array.prototype.slice.call(buttons);
// using Array.prototype.forEach() to iterate over the
// Array of <button> elements:
buttonArray.forEach(function(button) {
// button is the current Array-element of the
// Array over which we're iterating.
// here we assign the buttonOutput() function
// as the event-handler for the 'click' event:
button.addEventListener('click', buttonOutput)
});
div > div {
text-align: center;
}
div > button {
width: 30%;
text-align: center;
}
<div id="alpha">
<div>
<button id="q" class="letters">Q</button>
</div>
<div>
<button id="w" class="letters" onclick="theclick()">W</button>
</div>
<div>
<button id="e" class="letters">E</button>
</div>
<div>
<button id="r" class="letters">R</button>
</div>
<div>
<button id="t" class="letters">T</button>
</div>
<div>
<button id="y" class="letters">Y</button>
</div>
</div>
<textarea id="result"></textarea>
JS Fiddle demo.
References:
Array.from().
Array.forEach().
Arrow functions.
document.querySelectorAll().
EventTarget.addEventListener().
let.
Node.textContent.
var.
A solution with jQuery would be:
$(function() {
$('.letters').on('click', function() {
$('#textbox').text( $('#textbox').text()+$(this).text() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textbox"></div>
<div id="alpha" >
<div align="center">
<button id="q" class="letters">Q</button>
</div>
<div align="center">
<button id="w" class="letters">W</button>
</div>
<div align="center">
<button id="e" class="letters">E</button>
</div>
<div align="center">
<button id="r" class="letters">R</button>
</div>
<div align="center">
<button id="t" class="letters">T</button>
</div>
</div>
Pure JS
var letters = document.getElementsByClassName("letters");
var addLetter = function() {
var val = document.getElementById("textbox").innerHTML,
thisVal = this.innerHTML;
document.getElementById("textbox").innerHTML = val + thisVal;
};
for (var i = 0; i < letters.length; i++) {
letters[i].addEventListener('click', addLetter, false);
}
<div id="textbox"></div>
<div id="alpha" >
<div align="center">
<button id="q" class="letters">Q</button>
</div>
<div align="center">
<button id="w" class="letters">W</button>
</div>
<div align="center">
<button id="e" class="letters">E</button>
</div>
<div align="center">
<button id="r" class="letters">R</button>
</div>
<div align="center">
<button id="t" class="letters">T</button>
</div>
</div>
Or a Vanilla JS solution would be this:
var buttons = document.querySelectorAll("#alpha button");
for(var i =0; i < buttons.length; i++){
var btn = buttons[i];
btn.addEventListener("click", function() {
document.getElementById("textbox").value += this.innerHTML;
});
}
<div id="alpha">
<div align="center">
<button id="q" class="letters">Q</button>
</div>
<div align="center">
<button id="w" class="letters">W</button>
</div>
<div align="center">
<button id="e" class="letters">E</button>
</div>
<div align="center">
<button id="r" class="letters">R</button>
</div>
<div align="center">
<button id="t" class="letters">T</button>
</div>
</div>
<input id="textbox">

Categories