JavaScript click not working with InnerHtml [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
When user click on tag with class ".btn" it should console.log(1), if user click on "Next" button - .buttons>button should replace with given values in array tasks. It works well with replacement, but after replacement click ".btn" doen't work anymore.
What issue?
<div class="buttons">
<button class="btn">
<span class="text1">var 1</span>
</button>
<button class="btn">
<span class="text2">var 2</span>
</button>
</div>
<button class="right">
<span class="text">Next</span>
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
$(".btn").on('click', function() {
console.log(1)
})
</script>
<script>
var tasks = [
["task1", "task_addition1", "1", "var1", "img1.url", "var1", "img1.url"],
["task2", "task_addition2", "2", "var2", "img1.url", "var2", "img2.url"],
["task3", "task_addition3", "1", "var3", "img1.url", "var3", "img3.url"],
];
var task_number = 0;
$(".right").on('click', function() {
let buttons = ""
for (var i = 3; i < tasks[task_number].length;) {
buttons += '<button class="btn btn-light"><span class="text1">{}</span></button>'.replace("{}", tasks[task_number][i])
i += 2;
};
$(".buttons").html(buttons);
task_number += 1
})
</script>

Your binded event will be removed when you replace buttons. In this case, you should bind an event to parent(I usually use body selector) and provide selector to find it's children.
var tasks = [
["task1", "task_addition1", "1", "var1", "img1.url", "var1", "img1.url"],
["task2", "task_addition2", "2", "var2", "img1.url", "var2", "img2.url"],
["task3", "task_addition3", "1", "var3", "img1.url", "var3", "img3.url"],
];
var task_number = 0;
$(".right").on('click', function() {
let buttons = ""
for (var i = 3; i < tasks[task_number].length;) {
buttons += '<button class="btn btn-light"><span class="text1">{}</span></button>'.replace("{}", tasks[task_number][i])
i += 2;
};
$(".buttons").html(buttons);
task_number += 1
})
$("body").on("click", ".btn", function() {
console.log(1)
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
<div class="buttons">
<button class="btn">
<span class="text1">var 1</span>
</button>
<button class="btn">
<span class="text2">var 2</span>
</button>
</div>
<button class="right">
<span class="text">Next</span>
</button>
</body>
</html>

Related

I want to dynamically create a tag by using javascript

I'm using a bootstrap modal.
The Function what I want to dynamically create a button at body tag when I click the modal button.
Description about function what I apply: As soon as I click the bluebutton, I want to create it at the body tag('beside the '+' button')
window.onlaod = function(){
var blue = document.getElementById('blue');
blue.onclick = function(){
blue.onclick = null;
var result = document.getElementById('result');
var newblue = document.createElement('span');
newblue.id = 'newblue';
newblue.innerHTML += '<button type="button" class="btn btn-primary btnWH " id="blue"></button>';
result.appendChild(newblue);
};
};
-> This is the code about event after click the bluebutton.
<!-- label color -->
<div class="modal-body">
<button type="button" class="btn btn-primary btnWH " id="blue"></button>
</div>
-> This is the code about bluebutton.
<div class="card border-secondary mb-3" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<div id="result">
<span id="first">
<button type="button" class="btn btn-primary plusbtn" data-toggle="modal" data-target="#mymodal"> +
</button>
</span>
</div>
</div>
</div>
-> This is the code about '+'button.
This will create a button when click on add button inside div id of result code as follows:
<html>
<body>
<button type="button" id="blue">add</button>
<div id="result"></div>
<script>
window.onload = function() {
return addEvent();
}
function addEvent() {
var blueButton = document.getElementById('blue');
blueButton.addEventListener("click", addButton)
}
function addButton() {
var result = document.getElementById('result');
var newBtn = document.createElement('span');
newBtn.id = 'newblue';
newBtn.innerHTML += '<button type="button" id="blue">test</button>';
result.appendChild(newBtn);
}
</script>
</body>
</html>

How can I set a global click listener to grab the value from many buttons?

I have an array of buttons, which each hold a different value.
I need to add an event listener to listen for when it has been clicked.
The value of the button clicked will be pushed into a different array.
I feel like I need forEach, but can't quite fit it in.
function placeBet() {
var betBtn_nodelist = document.querySelectorAll('.bet_amount > button');
var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist);
for (var i = 0; i < betButtonsArr.length; i++) {
betButtonsArr[i];
}
}
<div class="bet_amount">
<button class="five" value="5">5</button>
<button class="ten" value="10">10</button>
<button class="fifty" value="50">50</button>
<button class="hundred" value="100">100</button>
</div>
You have to attach a click event handler for every item from your array.
result = [];
function placeBet(){
var betBtn_nodelist = document.querySelectorAll('.bet_amount > button');
var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist);
for (let i = 0; i < betButtonsArr.length; i++) {
betButtonsArr[i].onclick = function(){
result.push(this.value);
console.log(result);
}
}
}
placeBet();
<div class="bet_amount">
<button class="five" value="5">5</button>
<button class="ten" value="10">10</button>
<button class="fifty" value="50">50</button>
<button class="hundred" value="100">100</button>
</div>
You can do it this way using jquery :
var values = []
$(document).on('click', 'button', function() {
values.push(this.value)
console.log(values)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="bet_amount">
<button class="five" value="5">5</button>
<button class="ten" value="10">10</button>
<button class="fifty" value="50">50</button>
<button class="hundred" value="100">100</button>
</div>
how can I set a global click listener to grab the value?
Yes, you have to set a global click listener for all buttons in only one object – <div class="bet_amount">. If you set one click listener for each button then it is bad for the browser perfomance.
With e.target.nodeName == 'BUTTON' you can recognize the click on buttons inside "bet_amount" class element.
var result = [];
function placeBet()
{
var betAmount = document.querySelector('.bet_amount');
betAmount.onclick = function(e)
{
if(e.target.nodeName == 'BUTTON')
{
result.push(+e.target.value); //"+" is converting to integer
console.log(result.join(','))
}
};
}
placeBet();
<div class="bet_amount">
<button class="five" value="5">5</button>
<button class="ten" value="10">10</button>
<button class="fifty" value="50">50</button>
<button class="hundred" value="100">100</button>
</div>

How to add a link in javascript

I have the following Javascript that I am using to make a sort of flowchart where the user clicks through a set of questions. For certain responses i want to link to an external site where more info can be found. How do I add these links?
HTML
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 text-right">
<button class="btn btn-default btn-corner" type="submit" data-bind="click: startOver, visible: queryData().id > 0">Start over</button>
</div>
</div>
</div>
<div class="container main">
<div class="row">
<div class="c12 text-center">
<h1 data-bind="text: queryData().text"></h1>
<h3 data-bind="text: queryData().subhead"></h3>
<div class="option-group" data-bind="foreach: queryData().answers">
<button class="btn btn-default btn-lg" type="submit" data-bind="click: $parent.goToTarget, text: text"></button>
</div>
<button class="btn btn-default" type="submit" data-bind="click: stepBack, visible: navHistory().length > 1">Previous Step</button>
</div>
</div>
</div>
<div class="push"></div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script src="app.js?v=0.4.0"></script>
<script>
</script>
</body>
</html>
The Javascript is as follows:
JS
var queries = [{
id: 0,
text: "Where to start?",
answers: [{
text: "Let's Begin!",
target: 1
}]
}, {
id: 1,
text: "Which genre do you want to start in?",
answers: [{
text: "Fantasy",
target: 100
}, {
text: "SciFi",
target: 2
}, {
text: "Neither",
target: 59
}]
}, {
id: 2,
text: "It's huge but it's worth it. The Cryptonomicon by Neal Stephenson",
answers: [{
text: "Amazon.co.uk",
target: "_blank"
}, {
text: "Amazon.com"
}]
}];
function QueryViewModel() {
var self = this;
self.querySet = ko.observable();
self.currentStep = ko.observable();
self.queryData = ko.observable();
self.sfw = ko.observable();
self.navHistory = ko.observableArray();
// Operations
self.goToTarget = function(obj) {
self.navHistory.push(self.currentStep());
self.currentStep(obj.target);
self.queryData(self.querySet()[obj.target]);
}
self.startOver = function() {
self.navHistory.removeAll();
self.goToTarget({target: 0});
}
self.stepBack = function() {
var lastStep = self.navHistory().length > 1 ? self.navHistory.pop() : 0;
self.currentStep(lastStep);
self.queryData(self.querySet()[lastStep]);
}
var paramsString = document.location.hash.substring(1);
var params = new Array();
if (paramsString) {
var paramValues = paramsString.split("&");
for (var i = 0; i < paramValues.length; i++) {
var paramValue = paramValues[i].split("=");
params[paramValue[0]] = paramValue[1];
}
}
params ? paramTarget = params['target'] : params = [];
self.sfw() ? self.querySet(queriesSFW) : self.querySet(queries);
if (paramTarget) {
self.navHistory.push(0);
self.currentStep(0);
self.goToTarget({target: paramTarget})
} else {
self.goToTarget({target: 0});
}
}
ko.applyBindings(new QueryViewModel());
In html you can do something like this:
<button type="button" onclick="window.open('https://google.com/', '_self')">Button</button>
You don't have to use a button, different elements can use onclick like text or images. This can also call js functions, just put the function name where "window.open..." is.
Of course the standard way to do it is
<a href='https://www.google.com/'>Link</a>
You can practice using js here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html
and learn more about it here: http://www.w3schools.com/js/js_intro.asp
I am not sure why you would show us the JSON for open a link to another page. Unless I misunderstood. This kind of basic information can be found by a quick Google search.
Add your link in the object like:
text: "Fantasy",
link: "http://www.stackoverflow.com",
target: 2
Now when you need to go to that link, use this function:
var link = obj.link;
window.open(link, "_blank");

I'm trying to assign a label to a button using a variable in javascript

I'm reading through a playlist and trying to capture the title info for each item in the playlist and assign the title to a button in a grid made up of buttons. The goal is to create something like an electronic program guide that the user would click on and have the button change what is playing in the main playback window. I've included my current code below. Any help is greatly appreciated.
Thank you.
<div align="Center" id="playerContainer">
<div id="nowplaying"></div>
<script type="text/javascript">
jwplayer("nowplaying").setup({
playlist: "http://content.jwplatform.com/feeds/MFPT0wUf.rss",
image: "http://content.jwplatform.com/thumbs/Wf8BfcSt-640.jpg",
width: "580",
height: "370",
primary: "html5",
advertising: {
client: "vast",
tag: "http://demo.tremorvideo.com/proddev/vast/vast2RegularLinear.xml"
}
});
</script>
<script type="text/javascript">
var items = jwplayer().ge
tPlaylist(),
allButtons = ''; //empty str
for(var i = 0; i < items.length; i++) {
console.log(items.title);
var singleButton = '<div class="buttons01"><button type="button">' + items[i].title + '</button></div>';
allButtons += singleButton;
console.log(singleButton);
// console.log(allButtons);
}
</script>
</div>
<p></p>
I'd like to be able to automatically change the label of each button below by inserting the "title" value from the play list above into the "Title # Goes Here" space below.
<div class="buttons">
<div class="buttons01">
<button id="Video01" align="center">Title 1 Goes Here</button>
<button id="Video02" align="center">Title 2 Goes Here</button>
<button id="Video03" align="center">Title 3 Goes Here</button>
<button id="Video04" align="center">Title 4 Goes Here</button>
<button id="Video05" align="center">Title 5 Goes Here</button>
<button id="Video06" align="center">Title 6 Goes Here</button>
</div>
<div class="buttons02">
<button id="Video01" align="center">Title 7 Goes Here</button>
<button id="Video02" align="center">Title 8 Goes Here</button>
<button id="Video03" align="center">Title 9 Goes Here</button>
<button id="Video04" align="center">Title 10 Goes Here</button>
<button id="Video05" align="center">Title 11 Goes Here</button>
<button id="Video06" align="center">Title 12 Goes Here</button>
</div>
</div>
Not sure exactly what you're doing, your code is kind of a mess but maybe...
var items = jwplayer().getPlaylist();
for(var i = 0; i < items.length; i++) {
document.getElementById("buttons0"+i).innerHTML = items[i].title;
}

How do I make JS code not affect other DIV?

Hi I am try to make a list of item, I have "add" and "minus" button for each item. The problem is that the JS code I had control two items together. ex. if I click "add" for item1, then the item2 gets added as well.
Looks like that my JS functions works for all button elements. So when I click a "button" element, all buttons get triggered.
How can I do add them individually?
PS: I guess I need to do something like a specific ID for JS to trigger. My thought is add a unique ITEM ID for each one and trigger the button under that specific ID so other buttons under other ITEM ID don't get triggered.
Here is my HTML code:
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">
¥50
<div class="food-edit">
<button class="btn btn-info" value="50.55" id="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info" value="50.55" id="add">+</button>
</div>
</div>
</div>
</div>
</div>
Here is my JS:
var theTotal = 0;
var theSales = 0;
var minusButton = document.getElementById('minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function () {
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales++;
var num = theTotal.toFixed(2);
$('.total').text("¥" + num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales--;
var num = theTotal.toFixed(2);
if ( theSales == 0 ) {
$('.total').text("");
$('.total-num-of-sales').text("");
$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0 ) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$('.num-sales').text(theSales);
}
};
});
Don't use multiple id on same page
http://jsfiddle.net/bjc1c9tr/4/
Check this will help you
var theTotal = 0;
var theSales = 0;
var minusButton = $('.minus');
if (theSales == 0) {
$(minusButton).hide();
}
$('button').click(function(){
var ID = $(this).attr('data');
if (ID == "add") {
$(this).parent().find('.minus').show();
theTotal = Number($(this).parent().find('.num-sales').text()) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text()) + Number(1);
var num=theTotal.toFixed(2);
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number($(this).parent().find('.num-sales').text()) - Number($(this).val());
theSales= Number($(this).parent().find('.num-sales').text()) - Number(1);
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$(this).parent().find('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
$(this).parent().find('.minus').hide();
}
else if ( theSales > 0) {
$(this).parent().find('.total').text("¥"+num);
$(this).parent().find('.total-num-of-sales').text(theSales + "份")
$(this).parent().find('.num-sales').text(theSales);
}
};
});
html (added new classes)
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>
<div class="row bb">
<div class="col-xs-12 food-container">
<img src="img/1.png" class="min-w img-responsive" />
<div class="food-detail">
<div class="food-name">test</div>
<div class="food-sales">test:233333</div>
<div class="food-price">¥50
<div class="food-edit">
<button class="btn btn-info minus" value="50.55" data="minus">-</button>
<span class="num-sales"></span>
<button class="btn btn-info add" value="50.55" data="add">+</button>
</div>
</div>
</div>
</div>
</div>
$('button').click(function(){
var ID = this.id;
if (ID == "add") {
$(minusButton).show();
theTotal = Number(theTotal) + Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())+1;
var num=theTotal.toFixed(2);
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales+"份");
$(this).parent().find('.num-sales').text(theSales);
};
if (ID == "minus") {
theTotal = Number(theTotal) - Number($(this).val());
theSales = Number($(this).parent().find('.num-sales').text())-1;
var num=theTotal.toFixed(2);
if ( theSales == 0) {
$('.total').text("");
$('.total-num-of-sales').text("");
$(this).parent().find('.num-sales').text("");
//$('.num-sales').text("");
$(minusButton).hide();
}
else if ( theSales > 0) {
$('.total').text("¥"+num);
$('.total-num-of-sales').text(theSales + "份");
$(this).parent().find('.num-sales').text(theSales);
//$('.num-sales').text(theSales);
}
};
$(this).parent().find('.num-sales').text(theSales);
By this way you can get the parent of clicked button and change the value of .num-sales of the selected parent
https://jsfiddle.net/s2u9eb36/ refer this one
You are mixing the elements because of your id and class selectors.
When you select elements through jQuery by class (like $('.num-sales')), jQuery gives you a collection of all elements that match the selector. In your case, that would be both class="num-sales" elements.
Whenever you then call a function (like .html(theSales)), it will apply that function to each element in the collection, that's why your code is affecting more than one element.
You will need to find a way to distinguish one element of the other. There's quite a few options here, but I like doing it by limiting the scope of my selectors. With this I mean I would first find the food-detail div that contains the clicked element, and then find .num-sales etc... only within that element.
Then you can do the following in your button clicks:
$('button').click(function(){
var ID = this.id;
var element = $(this) //make a jQuery object of the clicked button
// finds the first parent element with class food-detail
var container = element.closest('.food-detail');
// find .num-sales within container
var numSales = container.find('.num-sales')
// continue...
});
in short:
when a button is clicked, find the food-detail div the button is in
.find in only that container instead of using selectors on the entire document
Edit: you should really change the id="Add" and id="minus" on your buttons, ids should be unique on the entire document. You can simply add add or minus as a class instead and check for it with element.hasClass('add').

Categories