I have this code:
$(function() {
/*declare a function call hAddCoin with parameter hValue for value and option for option +,x2,clear or max*/
function hAddCoin(hValue, option) {
var bet = document.getElementById('coincredits'); /*get the element*/
var coins = document.getElementById('coins').innerHTML; /*get the inner of id coins*/
var cur = parseInt(bet.value); /*get the coincredit and convert to integer*/
var res = 0; /*declare res variable for result*/
/*we need to check bet is empty or not*/
if (typeof bet.value === "undefined" || bet.value == "") {
cur = 0;
}
/*cek the option, it's will be +, X2 or max and default to 0*/
switch (option) {
case 1:
{
res = cur + hValue;
}
break;
case 2:
{
res = cur * option;
}
break;
case 3:
{
res = parseInt(coins);
}
break;
default:
{
res = 0;
}
break;
}
bet.value = res; /*set value coin creadit to result*/
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="coincredits" id="coincredits" class="form-control" required="" parsley-type="text" placeholder="Minimum 10 coins" data-parsley-id="40" style="text-align:center; color: ;">
<div class="content" style="text-align:center;">
<button id="clear" class="box-btn" onclick="hAddCoin(0,0)">Clear</button>
<button id="add10" class="box-btn" onclick="hAddCoin(10,1,)">+10</button>
<button id="add100" class="box-btn" onclick="hAddCoin(100,1)">+100</button>
<button id="add1000" class="box-btn" onclick="hAddCoin(1000,1)">+1000</button>
<button id="double" class="box-btn" onclick="hAddCoin(0,2)">x2</button>
<button id="max" class="box-btn" onclick="hAddCoin(0,3)">Max</button>
</div>
It adds (or should add) value to the input field, but it just sends me to mywebsite.com/index.php
I have tried defrient scripts but this is happening every time. It gives me no errors and logs nothing in the console.
I know it might be a piece of cake but i just can't figure it out.
<button> elements are implicitly type="submit" which means they submit the form they reside in. If your <form> doesn't have an action attribute it will use the current page as target URL, which reloads the page.
You need to either explicitly set type="button" on each button or add an onsubmit event handler on the form that invokes event.preventDefault()
Related
I have number of input types and buttons....every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop....where loop will increase in the function name and id......
<input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
<input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
<input type="number" id="s3"> <button onclick="increment_s3">Add</button>
here is JavaSc code
<script>
var i = 1;
for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data;
function ['increment_'+i]() {
data = data + 1;
document.getElementById("s"+i).placeholder = data;
i++;
}
}
</script>
You can't program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.
After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.
Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn't count as the form value.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
var data = 0;
document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>
What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
var divElem = document.querySelector('div');
// Set up empty first
divElem.innerHTML = "";
for(var i=1; i<=5; i++) {
// Create elements here
var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
// Push them all into innerHTML
divElem.innerHTML += innerElem;
}
<div></div>
You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.
I am trying to put different buttons with same function in switch statement. Every button needs to call same function but with different switch parameter.
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">
SQRT
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left:
100px;">
SIN
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left:
100px;">
COS
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left:
100px;">
ROUND
</button>
And here is JS code,
<script>
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
if(x > 0 && x < 1000){
switch(x){
case 0:
document.getElementById("btnSQRT");
document.write("nesta");
break;
case 1:
document.getElementById("btnSIN");
document.write("nesta");
break;
case 2:
document.getElementById("btnCOS");
document.write("nesta");
break;
case 3:
document.getElementById("btnROUND");
document.write("nesta");
break;
}
}
else{
alert("Thats not a wanted number");
}
}
</script>
Change all of your onclick="myFunction()" to onclick="myFunction(this)" - that will allow you to test for the switch in myFunction - in which case you want to switch on the button ID rather than the prompt value.
function myFunction(el){ // el will be the button that called the function
var x = prompt("Input number between 1 i 999");
if(x > 0 && x < 1000){
switch(el.id){ // switching on the ID of the button which tells us which math to use
case 'btnSQRT':
alert('The square root is ' + Math.sqrt(x));
break;
.....
I am not sure what 'nesta' and document.write was for, so I removed them here.
You are trying to switch between INT numbers, and "prompt" return a STRING. So, It will never get in any switch statement. To solve this, I just added a "parseInt()" in your prompt variable.
I changed "document.write('nesta')" by inner.HTML('nesta'), so, it changes the text in the button. But, to change the text inside the button, you got to set a variable to each button.
HTML:
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">SQRT</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left: 100px;">SIN</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left: 100px;">COS</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left: 100px;">ROUND</button>
JS:
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
var x = parseInt(x);
if(x > 0 && x < 1000) {
switch(x){
case 1:
var nesta = document.getElementById("btnSQRT");
nesta.innerHTML = 'nesta';
break;
case 2:
var nesta =document.getElementById("btnSIN");
nesta.innerHTML = 'nesta';
break;
case 3:
var nesta = document.getElementById("btnCOS");
nesta.innerHTML = 'nesta';
break;
case 4:
var nesta =document.getElementById("btnROUND");
nesta.innerHTML = 'nesta';
break;
}
} else {
alert("Thats not a wanted number");
}
}
Here you have:
One event listener for all buttons.
getting the "value" from the button using the attribute id. An alternative could be to use a data-attribute (like I did with the 2ed button).
A switch statement for handling what to do next.
It is not completely clear for me if the switch statement is the right approach here. Please comment if you have questions.
document.addEventListener('DOMContentLoaded', e => {
let buttons = document.getElementById('buttons');
let output = document.getElementById('output');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
switch (e.target.id) {
case 'btnSQRT':
output.innerHTML = 'You clicked SQRT';
break;
case 'btnSIN':
output.innerHTML = 'You clicked SIN';
break;
case 'btnCOS':
output.innerHTML = 'You clicked COS';
break;
case 'btnROUND':
output.innerHTML = 'You clicked ROUND';
break;
}
}
});
});
div#buttons {
display: flex;
justify-content: space-between;
}
<div id="buttons">
<button id="btnSQRT">SQRT</button>
<button data-func="SIN" id="btnSIN">SIN</button>
<button id="btnCOS">COS</button>
<button id="btnROUND">ROUND</button>
</div>
<div id="output"></div>
I'm trying to add an event that changes the text of a button when I click on it. However it doesn't matter which one I click, it always changes the text of the last button.
At first I tried by passing the button to the method "pulsar", and always the last button was the one changing. I thought it may be the reference of the variable so I tried passing the possition, but the same happens.
class Buscaminas{
constructor () {
this.botones = [];
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 7; j++) {
let boton = document.getElementById(i + "" + j);
boton.textContent = "Hi";
boton.onclick = e => {
this.pulsar(6*i+j);
}
this.botones.push(boton);
}
}
}
pulsar = (n) => {
console.log(n);
this.botones[n].textContent = "Bye";
}
}
The console.log always prints 55
You're approaching this incorrectly.
You never want to add a bunch of individual event handlers to each element in a case where you have lots of elements. You want to create a single event handler at a root node where click events for each child element bubble up to.
In this example, we have 10 divs:
<div id="btn-root">
<input type="button" class="btn" value="1">
<input type="button" class="btn" value="2">
<input type="button" class="btn" value="3">
<input type="button" class="btn" value="4">
<input type="button" class="btn" value="5">
<input type="button" class="btn" value="6">
<input type="button" class="btn" value="7">
<input type="button" class="btn" value="8">
<input type="button" class="btn" value="9">
<input type="button" class="btn" value="10">
</div>
And we have this simple code that listens for clicks on any of the child ".btn" elements:
class Buscaminas {
constructor() {
document.querySelector('#btn-root').addEventListener('click', (evt) => {
evt.target.textContent = Math.random();
});
}
}
new Buscaminas();
If you run that, you'll see that every time you click one of the buttons, its content is replaced with a random number.
Later edit:
Say you're in the case where you want to find the index of the element being clicked. We still don't want to assign individual event handlers for each element, but we aren't provided with the index of the target element in the parent.
To get around this, we want to search through the child nodes of #btn-root until it matches. A binary search won't work here, but we want something better than indexOf which just does a linear search. What we can do instead is only loop for the length of half the array and check both ends. Then we can get the index fairly efficiently.
document.querySelector('#btn-root').addEventListener('click', (ev) => {
const children = ev.target.parentNode.children;
for (let i = 0; i < Math.floor(children.length / 2); i++) {
const lowMatch = ev.target === children[i] && i;
const highMatch = ev.target === children[children.length - 1 - i] && children.length - 1 - i;
const index = Number.isInteger(lowMatch) && lowMatch || Number.isInteger(highMatch) && highMatch;
if (index) {
ev.target.value = `${index + 1}-${Math.random()}`;
break;
}
}
});
You could try this:
function sayHello(e) {
e.target.textContent = "Darth Vader";
}
var buttons = document.querySelectorAll("button");
buttons.forEach(e => e.addEventListener("click", sayHello, false));
<button>Hello</button>
<button>I</button>
<button>Am</button>
<button>Your</button>
<button>Father</button>
This code successfully takes the contents of the form and saves it to an ordered list, 2 more functions do the same thing but instead create a timestamp. I'm trying to take every li element that gets generated and save it to localStorage when you push the save button and then repopulate it again from the local storage when you push the "load" button. I can't get it to work come hell or high water. The load button does nothing, and oddly enough the "save" button acts as a clear all and actually removes everything rather then saving it. Console log shows no errors. I have the JavaScript below and the corresponding HTML.
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
document.getElementById("todoList").appendChild(newItem)
};
function save() {
const fieldvalue = querySelectorAll('li').value;
localStorage.setItem('item', JSON.stringify(item));
}
function load() {
const storedvalue = JSON.parse(localStorage.getItem(item));
if (storedvalue) {
document.querySelectorAll('li').value = storedvalue;
}
}
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="save()">Save</button>
<button id="load" onclick="load()">Load</button>
</form>
As #Phil and #Gary explained part of your problem is trying to use querySelectorAll('li') as if it would return a single value. You have to cycle through the array it returns.
Check the below code to give yourself a starting point. I had to rename some of your functions since they were causing me some errors.
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="saveAll()" type="button">Save</button>
<button id="load" onclick="loadAll()" type="button">Load</button>
</form>
<div id="todoList"></div>
<script>
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
//Had to add the element
document.getElementById("todoList").appendChild(newItem);
}
function saveAll() {
//Create an array to store the li values
var toStorage = [];
var values = document.querySelectorAll('li');
//Cycle through the li array
for (var i = 0; i < values.length; i++) {
toStorage.push(values[i].innerHTML);
}
console.log(toStorage);
//CanĀ“t test this on stackoverflow se the jsFiddle link
localStorage.setItem('items', JSON.stringify(toStorage));
console.log(localStorage);
}
function loadAll() {
const storedvalue = JSON.parse(localStorage.getItem('items'));
console.log(storedvalue);
//Load your list here
}
</script>
Check https://jsfiddle.net/nbe18k2u/ to see it working
We need one button to switch upper case and lower case of 26 alphabet by using JavaScript, just like android input method did. The code of using two button is as below. In order to save space, we just gave 3 alphabet button.
Any help is appreciated!
<input type="button" id="myBtn_q" onclick="myFunctionTest(this.value)" value="q">
<input type="button" id="myBtn_w" onclick="myFunctionTest(this.value)" value="w">
<input type="button" id="myBtn_e" onclick="myFunctionTest(this.value)" value="e">
<input type="button" id="myBtn_upperCase" onclick="myFunctionupperCase()" value="upperCase">
<input type="button" id="myBtn_lowerCase" onclick="myFunctionlowerCase()" value="lowerCase">
function myFunctionupperCase() {
if(document.getElementById("myBtn_a").value=="a"){
alert(document.getElementById("myBtn_a").value);
var controller=97;
for (controller=97; controller < 123; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller);
//alert(id_code);
document.getElementById(id_code).value=String.fromCharCode(controller-32);
}
}
}
function myFunctionlowerCase() {
if(document.getElementById("myBtn_a").value=="A"){
alert(document.getElementById("myBtn_a").value);
var controller=65;
for (controller=65; controller < 91; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller).toLowerCase();
//alert(id_code);
document.getElementById(id_code).value=String.fromCharCode(controller+32);
}
}
}
We attempt to combine two button's code into one button. However, it did not works. The code is as below.
<input type="button" id="myBtn_caseChange" onclick="myFunctioncaseChange()" value="caseChange">
function myFunctioncaseChange() {
if(document.getElementById("myBtn_a").value=="a"){
document.getElementById("myBtn_caseChange").value=="Lower Case"
alert(document.getElementById("myBtn_a").value);
var controller=97;
for (controller=97; controller < 123; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller);
document.getElementById(id_code).value=String.fromCharCode(controller-32);
}
}
if(document.getElementById("myBtn_a").value=="A"){
document.getElementById("myBtn_caseChange").value=="Upper Case"
alert(document.getElementById("myBtn_a").value);
var controller=65;
for (controller=65; controller < 91; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller).toLowerCase();
document.getElementById(id_code).value=String.fromCharCode(controller+32);
}
}
}
This should do it:
(function() { // closure to encapsulate the toggle state
// choose the initial case
var is_upper = true;
// get the toggle button's ID
var toggle = document.getElementById('myBtn_toggle');
// helper function that sets the buttons how you want
function update() {
toggle.value = is_upper ? '\u21E9' : '\u21E7';
for (var c = 1; c <= 26; ++c) {
var lc = String.fromCharCode(96 + c);
var uc = String.fromCharCode(64 + c);
var el = document.getElementById('myBtn_' + lc);
if (!el) continue;
el.value = is_upper ? uc : lc;
}
}
// add an event handler _properly_, without inline handlers
toggle.addEventListener('click', function() {
is_upper = !is_upper; // flip the case
update(); // update the buttons
});
update(); // make sure the page starts how you want
})(); // execute the above closure immediately
Demo at https://jsfiddle.net/alnitak/1c5x76uf/