Javascript - change value of variable on button click - javascript

I have an 10 HTML buttons that I need to change the value of a javascript variable when clicked.
song2 = "mp3Player/kingRight.mp3";
function returnVar2(song2) { return this[song2]; }
Song2 needs a new URL depending on which button is clicked.
Having a hard time figuring this out.

<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<script>
var b1 = document.getElementById('b1'), b2 = document.getElementById('b2');
var x = "Hello!";
function showX() {
alert(x);
}
b1.onclick = function() {
x = "button one";
showX();
};
b2.onclick = function() {
x = "button two";
showX();
};
</script>
Demo

HTML:
<div id="mp3buttons">
<div title="mp3Player/kingRight.mp3">King Right</div>
<div title="mp3Player/AnotherSong.mp3">Another Song</div>
etc.
</div>
JavaScript:
var mp3buttons = document.getElementById( 'mp3buttons' );
mp3buttons.onclick = function ( e ) {
var url = e.target.title;
// do stuff with this URL
};
So, you put your buttons inside a wrapper. For each button, you place the URL inside the title attribute (or some other appropriate attribute).
In JavaScript code, you bind a click handler to the wrapper. The clicked button is referenced with e.target.

Related

Not possible to remove paragraph dynamicaly

<html>
<body>
<div id="div1">
<button id="btn1">click me to show line </button>
<button id="btn2">click me to hide line </button>
</div>
<script>
var lines = ["line1", "line2", "line3"];
var button1 = document.getElementById("btn1");
button1.addEventListener("click", myfunction1);
function myfunction1 () {
var show = document.getElementById("div1");
var crt = document.createElement("p");
crt.innerText = lines[0];
show.appendChild(crt);
}
var button2 = document.getElementById("btn2");
button2.addEventListener("click", myfunction2);
function myfunction2 () {
var hide = document.querySelector("p");
hide.remove();
}
</script>
</body>
</html>
With the above code I would like when I click the first button to display text from the array and when I click the second button to delete it. My problem is that it is not deleted by clicking the second button.
The id of your second button is the same as the first. It must be btn2.

Display button value in div onclick. Javascript/HTML

I have a set of buttons with different values. When I press a button I want the value of the button to be displayed in the div picked_letters, but nothing is showing. The code is divided in an html file and a javascript file.
html file looks like this:
<body>
<script src="cases.js"></script>
<div id="written_word">
</div>
<div id="list_of_letters">
</div>
<div id="picked_letters">
</div>
</body>
and the onclick in the javascript file looks like this:
for(let i = 0; i < 26; i++) {
let btn = document.createElement("button");
btn.style.background = 'silver';
btn.style.width = '15%';
btn.style.fontWeight = 'bold';
btn.style.fontSize = '135%';
btn.style.display = 'inline-block';
btn.value = case_values[i];
btn.onmouseover = function (){
btn.style.background = 'goldenrod';
}
btn.onmouseleave = function() {
btn.style.background = 'silver';
}
btn.onclick = function() {
btn.style.background = 'darkgrey';
btn.disabled = true;
btn.innerHTML = String(btn.value);
document.getElementById("picked_letters").innerHTML =
String(btn.value);
}
btn.innerHTML = String(i+1);
document.body.appendChild(btn);
}
The button changes color, becomes disabled and displays the value inside the button but it's the last line with getting the button value into a div that I am having problems with. Have looked around but haven't found a solution that solves this problem.
##Edit: The problem seems to have been fixed when I put the script import at the end of the body (and some other minor changes).
Where are you setting the value of the button?
Can you share the button code?
Does your button look like this?
<button>My Button</button>
or do you set your value like this?
<button value="my button value">My button</button>
If you have a value set - you can do this:
btn.onclick = function () {
console.log(btn.innerHTML);
btn.style.background = "darkgrey";
btn.disabled = true;
document.getElementById("picked_letters").innerHTML = btn.value;
};
If you don't have a value set - using btn.value won't return anything.
I would try adding a value to your button if you dont have one. Or if you want to call the innerhtml of the button:
<button>My button</button>
and then
btn.onclick = function () {
console.log(btn.innerHTML);
btn.style.background = "darkgrey";
btn.disabled = true;
document.getElementById("picked_letters").innerHTML = btn.innerHTML;
};
The code above is perfectly fine, the is definately being displayed in the "picked_letters" div, but the value of btn is ""(empty) so the value set to the div is also empty. To solve this issue, add value to the button by doing:-
. and the issue will be gone.
const btn = document.querySelector('#btn')
btn.onclick = function() {
btn.style.background = 'darkgrey';
btn.disabled = true;
console.log(btn.value)
btn.innerHTML = String(btn.value);
document.getElementById("picked_letters").innerHTML =
String(btn.value);
}
<body>
<div id="written_word">
</div>
<div id="list_of_letters">
</div>
<div id="picked_letters">
</div>
<button id='btn' value='5'>Tap me</button>
</body>

Allow the user to change a JavaScript variable with a button click

I have a JavaScript variable:
var setClickTime = "2000";
I would like to give the user a choice of 2000 or 4000 based on their preference by clicking a button.
What is the best way to allow the user to change this variable? I have considered having two buttons one of which will have the class active when clicked. That would require me to set up an if / else statement to change the variable based on which button is active. But I am new to this and I do not know the best approach.
Just give your buttons IDs and bind listeners.
Say, you have two buttons id="setTime2000" and id="setTime4000", then you just need:
HTML Code:
<div>
<button id="setTime2000">Set time as 2000</button>
<button id="setTime4000">Set time as 4000</button>
</div>
JS Code:
$(document).ready() {
var mTime = 2000; // set the default value of time
$("#setTime2000").click(function () {
mTime = 2000;
}
$("#setTime4000").click(function () {
mTime = 4000;
}
// ... do something with the variable set
}
Do you just want a button event listener to change it:
<button id="changeBtn">4000</button>
JS
var setClickTime = "2000";
$("#changeBtn").click(function() {
setClickTime = "4000";
})
First, you have a JavaScript variable, it has nothing to do with jQuery.
Then, if you want something easy, without dependencies. Here a simple example:
var myValue = 2000;
updateOutput();
a.addEventListener('click', function() {
myValue = 2000;
updateOutput()
});
b.addEventListener('click', function() {
myValue = 4000;
updateOutput()
});
function updateOutput() {
output.value = myValue;
}
<button id="a">2000</button>
<button id="b">4000</button>
<input readonly id="output">
A generic answer in pure javascript.
<button class='setTime'>
2000
</button>
<button class='setTime'>
4000
</button>
Pure Javascript:
var setClickTime = "";
var buttons = document.getElementsByClassName('setTime')
for (i = 0; i < buttons.length; i++) {
this.onclick = function setTime(event) {
setClickTime = event.target.innerHTML;
alert(setClickTime);
}
}
fiddle: https://jsfiddle.net/b1vy8ahp/
You can define multiple radio buttons for more options ( with same name attribute to group them ) and then just delegate or bind a change event on that group of radios buttons to get the selected value.
<input type="radio" name="test" value="2000">2000
<input type="radio" name="test" value="4000">4000
<script>
var setClickTime;
$('input:radio[name=test]').on('change',function()
{
setClickTime = this.value;
});
</script>
Example : https://jsfiddle.net/DinoMyte/71hgeqnb/1/

Identifying which Div was selected with JavaScript

I have an HTML document with 6 Divs, I've written a javascript code that changes the heading depending on which div is selected (6 vars and 6 functions) e.g.
var divSelect = document.getElementById("firstDiv");
divSelect.onclick = function () {
var mainHeading = document.getElementById("heading");
mainHeading.innerHTML = "You have selected the first option";
};
I then have an anchor div which is linking to another HTML page, when it opens I want it to know which div was selected from the first HTML page, and then input a new heading based on the selection.
So I need to know which of the six functions was actioned based on the div that was clicked.
Any help much appreciated.
You can pass it in url query. Passing for example id parameter, like this: http://example.com/secondpage.html?firstpagedivid=firstDiv And then on second page you can parse url to get div id or whatever parameter you passed.
Here you can find how to get url parameter on second page: link
Html:
<div class="clickable" id="firstDiv">first</div>
<div class="clickable" id="secondDiv">second</div>
<div class="clickable" id="thirdDiv">third</div>
<br>
<div id="heading"></div>
<br>
<a id="navigator" href="second.html">Next page</a>
Javascript:
(function() {
var currentSelectedDiv;
var heading = document.getElementById('heading');
var navigator = document.getElementById('navigator');
var divs = document.querySelectorAll('.clickable');
for(var i=0; i<divs.length; i++) {
divs[i].onclick = function(e) {
var target = e.target;
currentSelectedDiv = target.getAttribute('id');
heading.innerHTML = ['You have selected ', currentSelectedDiv].join('');
}
}
navigator.onclick = function(e) {
e.preventDefault();
var a = e.target;
var href = a.getAttribute('href');
href += '?previousPageDivId=' + currentSelectedDiv;
alert(href);
//Just uncomment line below
//document.location.href = href;
}
})();
Here you have working example: https://jsfiddle.net/3wdzh2d4/

Change the onClick function to target the edit buttons

I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element

Categories