How do I change an onclick function to have multiple functions? - javascript

I'm trying to change a button's onclick function to remove one function and add two functions. This is my current code
var random;
function number(){
var random =Math.floor(Math.random()*Math.floor(Math.random()*20))
}
function show(){
var display = document.getElementById('number').innerHTML= random;
}
function start(){
var random =Math.floor(Math.random()*Math.floor(Math.random()*20))
var button = document.getElementById('button').innerHTML="I give up!!";
var change = document.getElementById("button").onclick = show; number;
}

Add 2 event listeners to your button
function start(){
var random = Math.floor(Math.random()*Math.floor(Math.random()*20)),
button = document.getElementById('button').innerHTML="I give up!!";
changeButton = document.getElementById("button");
changeButton.addEventListener('click', show);
changeButton.addEventListener('click', number);
}

You need to assign onclick an anonymous function and include both functions in it:
document.getElementById("button").onclick = function() {
show();
number();
};

Related

How to execute a second javascript function after changing a button's id?

I have an html button where I change the value and id in an attempt to execute a javascript function based on the new ID.
From this;
<button id="Start" class="Button">Start</button>
to this;
<button id="Stop" class="Button">Stop</button>
The intent is for the user to click on the Start button to execute the associated function and change the existing button into a Stop button to execute its associated function. One button with two separate tasks.
var mySocket = new WebSocket("ws://192.168.1.102:5678/");
window.onload = function() {
var StartST = document.getElementById('Start');
var StopST = document.getElementById('Stop');
var socketStatus = document.getElementById('usercontent');
if (StartST) {
StartST.addEventListener("click", function (e) {
StartST.innerHTML = "Stop";
StartST.id = "Stop";
mySocket.send('start');
socketStatus.insertAdjacentHTML('afterbegin','<div class="received">Start -> ' + StartST.id + '</div>\n');
e.preventDefault();
})
}
if (StopST) {
StopST.addEventListener("click", function (e) {
mySocket.send('stop');
StopST.innerHTML = "Start";
StopST.id = "Start";
socketStatus.insertAdjacentHTML('afterbegin','<div class="received">Stop</div>\n');
e.preventDefault();
})
}
};
The issue is I cannot execute the Stop button function and I am not sure how to implement delegation to get it to work correctly.

Using addEventListener() in a for loop with various listeners

I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", listenerName);
}
var listener1 = function() {
document.getElementById('demo').innerHtml = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHtml = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHtml = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHtml = "4";
}
</script>
</body>
</html>
Unfortunately, it doesn't work. What's up with that? Thank you.
There are 3 issues with your code:
In your for loop, you are essentially attaching strings as eventlisteners. You need to access your event listeners from the string you have.
Since you eventlisteners are declared in the global scopre, you can use window to access them:
button.addEventListener("click", window[listenerName]);
You are attaching the event listeners before declaring them. You need to declare listener1 and so on before your for loop
innerHtml does not exist. The right syntax is innerHTML
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var listener1 = function() {
document.getElementById('demo').innerHTML = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHTML = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHTML = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHTML = "4";
}
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", window[listenerName]);
}
</script>
</body>
</html>
your line button.addEventListener("click", listenerName); tried to add a function called listenerName to the click event, and since listenerName is a variable and not a function, it doesn't work.
You could use an array of function to make it work instead.
var array_of_functions = [
'listener1' : listener1,
'listener2' : listener2,
'listener3' : listener3,
'listener4' : listener4
]
and then in your loop you could create the listener by giving the right function:
button.addEventListener("click", array_of_functions[listenerName]);
Also, make sure you create the function and the array before running the loop or they won't exist yet when the code runs.
There's a slightly easier way to do this - just have one function that handles the event:
for (var button of allButtons) {
button.addEventListener("click", handleClick, false);
}
function handleClick() {
var id = this.id.match(/button-listener(\d)/)[1];
document.getElementById('demo').innerHTML = id;
}
DEMO
Or, you can change your loop like this and your code will work
allButtons.forEach(function (button, i) {
var listenerName = button.id.slice(button.id.lastIndexOf("-") + 1);
button.addEventListener("click", function () {
document.getElementById('demo').innerHTML = i + 1;
});
});

Including strings as parameters for a function chosen for .setAttribute to a button in javascript

I want to be able to pass along a string as a value for a button's onclick function using setAttribute. I am getting the error that "add is not defined" when I click on the button and I am not sure what I am doing wrong.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(AddString,SectorString)');
function AddOrDeleteDiv(AddString, SectorString) {
//code
}
Do not use content attribute event handlers! Use event listeners instead:
var addButton = document.createElement("button");
var addString = "add";
var sectorString = "1_1";
addButton.addEventListener('click', function() {
addOrDeleteDiv(addString, sectorString);
});
function addOrDeleteDiv(addString, sectorString) {
//code
}
Well js is known for not having nice methods for string joining and please try to use function parameter names not same as global variable names, it's not a nice thing to do.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(' + JSON.stringify(AddString) + ',' + JSON.stringify(SectorString) + ')');
function AddOrDeleteDiv(addStr, secStr) {
//code
}
or as #Thomas said you could use acutual javascript event handler like , not modifying attributes to assign event handler
AddButton.onclick = function(){AddOrDeleteDiv(AddString,SectorString);}

Events and handlers JavaScript

I am writing a code in which I want to display a word and sentence to my webpage when clicked(button). So far I have one text being displayed onto the page.I want to display the sentence after the text.The sentence is not displaying... anyone know why?
function handleButtonClick(){
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
var textInput = document.getElementById("word");
var termName = textInput.value;
var dt = document.createElement("dt");
dt.innerHTML = termName;
var dl = document.getElementById("p");
dl.appendChild(dt);
var textInput = document.getElementById("sentence");
var termDefine = textInput.value;
var dd = document.createElement("dd");
dd.innerHTML = termDefine;
var dl = document.getElementById("define");
dl.appendChild(d);
}
window.onload = handleButtonClick;
button.onclick = handleButtonClick;
supposed to be
button.addEventListener('click', handleButtonClick);
The second point is that the click event handler should be bound outside the function scope. Otherwise a new event will be bound every single time the function handleButtonClick fires.
var button = document.getElementById("addButton");
button.addEventListener('click', handleButtonClick);
function handleButtonClick() {
// Your other code here
// that excludes the click handler
}
And developer tools is your friend. Always use it to check for any errors.
In addition to what #sushanth already mentioned there is a typo in your code:
Instead of
dl.appendChild(d);
It should be
dl.appendChild(dd);

How to run script when a button is clicked

Hi I'm running a sum and multiplication script for some field input values to a form i made. How can I get this script to run on a button click so that after a user enters a new value they can click a update form button to run the calculations script and update the total sum.
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Define a function and put the code you want to run inside it.
var doStuff = function () {
// do some stuff here
};
Select your button and call that function on click. If you're using an A or BUTTON tag you may want to prevent the default action, which I've included in this example.
$('.button').on('click', function (event) {
doStuff();
event.preventDefault();
});
This assumes that you're using jQuery 1.7+.

Categories