document.getElementById() not working as intended with multiple ids - javascript

I have an issue with document.getElementById(). Basically I have different forms each one with a different id and I'm using a bit of Javascript to replace some classes and add dinamically file name after upload.
That should be really easy, but I don't know why even if the ids are totally unique I get a weird behavior: whatever is the form in which I submit a file javascript will apply changes always on the first of them.
function spinnerLoad(){
document.getElementById('file-name[[${id}]]').textContent = this.files[0].name;
document.getElementById('spinner[[${id}]]').classList.replace('fas', 'spinner-border');
document.getElementById('spinner[[${id}]]').classList.replace('fa-file-upload', 'spinner-border-sm');
document.getElementById('uploadForm[[${id}]]').submit()
}
/*I'm using Bootstrap for my styling rules*/
/*${id} variable is server-side and it's there to make unique each form, I'm using Thymeleaf template engine*/
<form th:id="'uploadForm'+${id}" method="post" enctype="multipart/form-data" th:action="#{/upload/{id} (id=${id})}">
<label for="file-upload" class="btn btn-outline-success">
<span th:id="'spinner'+${id}" class="fas fa-file-upload"></span> <b>Upload file:</b> <i th:id="'file-name'+${id}">No file selected</i>
</label>
<input id="file-upload" type="file" name="multipartFile" accept="application/pdf" style="display: none" th:onchange="spinnerLoad()"/>
</form>
I googled the problem but I didn't manage to find a specific answer to my issue, so that's why I'm here bothering you.
I hope someone can help my figure this out, thank you.

You get a lot of repeating code and that can be hard to maintain. Here I placed the event listener on the the parent <div> to all the buttons. Then I need to test if is a button. And there is no need for an id for each button.
Actually, if you are just replacing a class name you don't even need to do the test (if()), because replace() will only do the replacement when the old value is present. This should be fine:
buttons.addEventListener('click', e => {
e.target.classList.replace('btn-success', 'btn-danger');
});
But here is the full example with the test:
var buttons = document.getElementById('buttons');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
e.target.classList.replace('btn-success', 'btn-danger');
}
});
.btn-success {
background-color: green;
}
.btn-danger {
background-color: red;
}
<div id="buttons">
<button class="btn-success">Button 1</button>
<button class="btn-success">Button 2</button>
<button class="btn-success">Button 3</button>
</div>

You're missing the css that would make this work, but otherwise your example is functional. However, it can be done more simply by working on the buttons as a class instead of individually.
var btns = document.getElementsByClassName("btn");
var addDanger = function(){
this.classList.replace('btn-success', 'btn-danger')
};
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', addDanger, false);
};
.btn {height:20px; width: 50px;}
.btn-success {background-color:green}
.btn-danger {background-color:red}
<button id="btn1" class="btn btn-success"></button>
<button id="btn2" class="btn btn-success"></button>
<button id="btn3" class="btn btn-success"></button>

Related

How to add onClick attribute to a button with JS?

How can I add onClick attribute to this button using JS?
<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt">BUY NOW</button>
You can do it using Jquery:
"your element".addEventListener('click', function(){
alert('hey');
}, false);
you can use the JS function .addEventListener(), Here you'll find a well done explenation of It.
What I sugger you to do is to add an Id to your button tag and then use the document.getElementById() (if you don't know what this JS function does read this) to find your button and apply to It the .addEventListner() function to add a click behaviour.
I made a simple code example below, take a look at It and let me know if this answer is what you're searching for.
document.getElementById('myButton').addEventListener('click', () => {
document.getElementById('myButton').classList.toggle('toggled');
});
button {
width: 100px;
height: 50px;
background: #ccc;
border: 0;
outline: 0;
}
button:hover {
cursor: pointer
}
button.toggled {
background: red;
}
<html>
<head></head>
<body>
<button type=submit id="myButton">
CLICK ME
</button>
</body>
</html>
If you want to do it in js, you will have to either use .addEventListener() function or .onClick() function that are triggered whenever the button is clicked
you can also use the .onClick inside of your html
<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt" onClick="function_name">BUY NOW</button>
sidenote: if you want to access the button element inside your javascript you can add an Id to your button tag and then use the document.getElementById() or use let var = document.getElementByClass() but be aware to use var[0] to access the button element in case you filtered it by class

How would you write this jQuery code that binds a clicked element to functions in JavaScript?

I have being trying to solve a problem of how to bind a clicked element to functions using JavaScript, and after many days finally found a solution here provided by #JerdineSabio. My original problem was asked at Stackoverflow and it had to do with a single JavaScript script handling many buttons and performing speech recognition. The code that binds the clicked button to the functions is written in jQuery and involves using function(e) . The jQuery statement takes 3 parameters, but in JS the equivalent expression only takes two (the event (eg. the clicking) and the function). I've looked up the usual references I depend upon but haven't found a way to write it in Javascript. I have solved the scripting problem; so I just want to find an answer to this question in case I might want to use JS only in the future, as I tend to rely on JS more than jQuery, and I also read about function(e) before and watched a video on Youtube about it, but I still did not quite understand what "e" is and what it does.
The jQuery script below works as it should. The code changes the color of the button that's next to it. Once again, this involves multiple buttons but there is only one script for them all.
I have tried:
document.addEventListener("click", myFunction);
function myFunction(e) {
this.previousElementSibling.setAttribute("style", "background-color: gold") ...
....};
and I've tried a few more things, but I can't make the function work correctly no matter what I try.
The HTML is:
<div class="container">
<button id="first" type="button" class="btn btn-danger"></button>
<button id="first" type="button" class="btn btn-warning"></button>
</div>
The jQuery is:
$(document).ready(function(){
$(document).on("click", "#first", function(e) {
$(this).siblings().css("background-color", "gold");
});
});
You can do in many ways by adding onclick function to the button then target them by id or class name
First by the id (ofc must have unique id) then you gonna put :-
function btnClicked(clicked_btn) {
let btn = document.getElementById(clicked_btn)
btn.style.backgroundColor = 'red'
}
<div class="container">
<button id="first" onClick='btnClicked(this.id)' type="button" class="vtn btn-danger">press1</button>
<button id="second" onClick='btnClicked(this.id)' type="button" class="btn btn-warning">press2</button>
</div>
second by class name :- but you have more than class name so we gonna add split() function to target one of them like so
function btnClicked(clicked_btn) {
let btn = document.querySelector('.' + (clicked_btn.split(' ')[1]))
btn.style.backgroundColor = 'red'
}
<div class="container">
<button id="first" onClick='btnClicked(this.className)' type="button" class="btn btn-danger">press1</button>
<button id="second" onClick='btnClicked(this.className)' type="button" class="btn btn-warning">press2</button>
</div>
You can try this way:
<script>
window.addEventListener('load', () => {
var buttons= document.querySelectorAll('#first');
for (var i = 0; i < buttons.length; i++)
buttons[i].addEventListener("click", myFunction);
});
function myFunction(e) {
siblings(e.target).forEach((element, index) => {
element.setAttribute("style", "background-color: gold")
});
};
function siblings(elem) {
let siblings = [];
if (!elem.parentNode)
return siblings;
let sibling = elem.parentNode.firstElementChild;
do {
if (sibling != elem)
siblings.push(sibling);
} while (sibling = sibling.nextElementSibling);
return siblings;
};
</script>
Basic event delegation requires you to have to figure out what was clicked is the element you are looking for. Using matches() makes that easy.
function delegatedClick(selector, callback) {
function fnc(event) {
if (event.target.matches(selector)) {
callback.call(event.target, event);
}
}
document.addEventListener("click", fnc);
}
delegatedClick(".foo button", function() {
console.log(this.id);
});
.foo button {
color: green;
}
<div class="foo">
<button type="button" id="b1">Yes</button>
</div>
<div class="foo">
<button type="button" id="b2">Yes</button>
</div>
<div class="bar">
<button type="button" id="b3">No</button>
</div>
<div class="foo">
<button type="button" id="b4">Yes</button>
</div>
Now toggling the siblings
var wrapper = document.querySelector(".foo");
var buttons = wrapper.querySelectorAll("button")
wrapper.addEventListener("click", function (event) {
var clickedButton = event.target.closest("button");
clickedButton.classList.remove("goldbg");
buttons.forEach(function (btn) {
if (btn !== clickedButton) {
btn.classList.add("goldbg");
}
});
});
.foo button.goldbg {
background-color: gold;
}
<div class="foo">
<button type="button" id="b1">1</button>
<button type="button" id="b2">2</button>
<button type="button" id="b3">3</button>
<button type="button" id="b4">4</button>
</div>

Button styling bug

I want to receive information from my users using buttons, so i created two sections for that. When the user clicks a button i need it to change its style so the user will see a difference in what they clicked even when they click another button in the other section. The problem is that when another button is clicked the other section looses its style (so the user wouldn't know what he previously clicked). I pasted the html code of the part with the problem(below)
<div>
<p><strong>Network</strong></p>
<button class="btn25" onclick = "gfg_Run()">
MTN
</button>
<button class="btn25">
Glo
</button>
<button class="btn25">
9 Mobile
</button>
<button class="btn25">
Airtel
</button>
</div>
<div>
<p><strong>Data</strong></p>
<button class="btn25">
1Gb
</button>
<button class="btn25">
2Gb
</button>
<button class="btn25">
3Gb
</button>
<button class="btn25">
5Gb
</button>
<button class="btn25">
10Gb
</button>
</div>
i need it to change its style so the user will see a difference
Create a class called active and then set the buttons to use that class when the user selects them.
The problem is that when another button is clicked the other section looses its style
The issue is that you need to separate out each group. I added a class on the parent div that distinguishes the two groups: "data" or "speed". The button background will change to blue for each of the groups because it is limited to that class in the query as ".data" does here:
document.querySelectorAll('.data .btn25');
Here is an example snippet showing the basic technique.
const dataChoices = document.querySelectorAll('.data .btn25');
dataChoices.forEach(function(choice) {
choice.addEventListener('click', function() {
removeClass(dataChoices);
this.classList.add('active');
});
});
const speedChoices = document.querySelectorAll('.speed .btn25');
speedChoices.forEach(function(choice) {
choice.addEventListener('click', function() {
removeClass(speedChoices);
this.classList.add('active');
});
});
function removeClass(dataGroup) {
dataGroup.forEach(function(choice) {
choice.classList.remove('active');
});
}
.active {
background-color: lightblue;
}
div {
float: left;
margin-right: 10px;
}
<div class="data">
<p><strong>Data</strong></p>
<button id="1" class="btn25">1Gb</button>
<button id="2" class="btn25">2Gb</button>
<button id="3" class="btn25">3Gb</button>
<button id="4" class="btn25">5Gb</button>
<button id="5" class="btn25">10Gb</button>
</div>
<div class="speed">
<p><strong>Speed</strong></p>
<button id="1" class="btn25">1Mbps</button>
<button id="2" class="btn25">2Mbps</button>
<button id="3" class="btn25">3Mbps</button>
<button id="4" class="btn25">5Mbps</button>
<button id="5" class="btn25">10Mbps</button>
</div>
I have an alternate way to do this, but honestly Christopher Taleck's answer is perfectly fine as well, I just had a different conception of how to solve the problem and figured that would be informative for others facing a similar situation.
Here is a link to a JSFiddle with a working example: JSFiddle
Here is the complete code, an explanation of everything is provided below:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Button Practice</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="network-container">
<h2>Network</h2>
<button type="button" class="btn25">MTN</button>
<button type="button" class="btn25">Glo</button>
<button type="button" class="btn25">9 Mobile</button>
<button type="button" class="btn25">Airtel</button>
</div>
<div class="speed-container">
<h2>Speed</h2>
<button type="button" class="btn25">1Mbps</button>
<button type="button" class="btn25">2Mbps</button>
<button type="button" class="btn25">3Mbps</button>
<button type="button" class="btn25">5Mbps</button>
<button type="button" class="btn25">10Mbps</button>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
script.js
function ButtonContainer(element) {
this.element = element;
this.selectedButton = null;
this.element.addEventListener('click', function(e) {
if (e.target.type !== 'button') return;
if (this.selectedButton) this.selectedButton.classList.remove('active');
e.target.classList.add('active');
this.selectedButton = e.target;
});
}
const networkContainer = new ButtonContainer(document.querySelector('.network-container'));
const speedContainer = new ButtonContainer(document.querySelector('.speed-container'))
style.css
.active {
background-color: #9AD58E;
}
GENERAL CODE EXPLANATION
First, I would suggest removing this call to gfg_Run() from the .html file:
// index.html
<button class="btn25" onclick = "gfg_Run()">
And creating a separate file to hold your JS. Then, you can just link that file like so, right before the closing <body> tag (I created a file called script.js for this purpose):
// index.html
<script type="text/javascript" src="script.js"></script>
Also, I would suggest adding a descriptive class based on the type of buttons that each <div> holds, like so:
// index.html
<div class="network-container">
------ rest of the container ------
<div class="speed-container">
------ rest of the container ------
To handle the change of style on the button click, you can create a class that is added to the clicked button. I will use .active as that is a pretty common convention. This can be in a style.css file that you link from the head of the HTML document:
// style.css
.active {
background-color: #9AD58E;
}
In that script.js file, my approach would be to create a constructor function that represents the container that holds the buttons:
// script.js
function ButtonContainer(element) {
this.element = element;
this.selectedButton = null;
this.element.addEventListener('click', function(e) {
if (e.target.type !== 'button') return;
if (this.selectedButton) this.selectedButton.classList.remove('active');
e.target.classList.add('active');
this.selectedButton = e.target;
});
}
ButtonContainer CONSTRUCTOR FUNCTION EXPLANATION
We set the ButtonContainer up with two properties, element and selectedButton. element represents the DOM element which contains the buttons (in our case, a <div>), and the selectedButton represents the last <button> in this <div> that was clicked.
The eventListener will fire whenever the <div> is clicked anywhere inside it's borders. We only want to handle clicks on a <button> element within this <div>, so we exit the listener if the target of the event was not a button with the line below:
if (e.target.type !== 'button') return;
Next, we want to see of there is already a selectedButton in this <div>, and if so, we need to remove the .active class from it so we don't have two buttons in the same <div> that have colored backgrounds:
if (this.selectedButton) this.selectedButton.classList.remove('active')
Finally, we set the .active class on the <button> that triggered the event, and set the selectedButton property of this ButtonContainer object to that button, so that we can keep track of the currently selected button in this <div>:
e.target.classList.add('active');
this.selectedButton = e.target;
Then simply create two instances of the ButtonContainer that represent the <div> elements containing each group of buttons (each <div> should have a class representing the type of buttons it holds):
const networkContainer = new ButtonContainer(document.querySelector('.network-container'));
const speedContainer = new ButtonContainer(document.querySelector('.speed-container'));
In this way, you don't have to loop through the buttons and add event listeners to each, you simply allow each container to handle it's own button events. I like this approach because we seem to be treating the buttons like two separate groups, and this logically mirrors that.

Button in div not working

Initially my div (with the button inside) is hidden, when I press a button I make 10 clones of that div.
I want to be able to use each of the buttons seperatly (they all have the same attributes and class). At the moment I cannot use the any of the buttons.
<div class="search-result">
<h3>Titel(year)</h3>
<button class="btn btn-warning btnFavorite">Favorite</button>
<button id="btnArkiv" class="btn btn-warning btnFAvorite">Arkiv</button>
</div>
$(".btnFavorite").on("click", function(){
alert("hej");
var input = $("#search").val();
saveFavorite(favoriteMovie);
});
Method to clone the div x times.
for(movie in search){
console.log(search[movie].Title);
favoriteMovie = search[movie].Title;
$(".search-result:first").clone().appendTo(".search").find('h3').text(search[movie].Title);
$('#your_element').attr('id','the_new_id');
}
I've replaced the input elements with actual buttons and delegated the event to the body, so that newly inserted movie buttons automatically use the same event handler. The div cloning function can also use some updates, but it should work and that's not the question. :)
You might have to update any function that uses the value as well, since it's a data-value attribute now. Hope it helps.
PS: I don't usually use jQuery, so untested and there might be syntax errors.
<div class="search-result">
<h3>Titel(year)</h3>
<button data-value="Favoritfilm" class="btn btn-warning btnFavorite">buttonText</button>
<button id="btnArkiv" data-value="Arkiv" class="btn btn-warning">buttonText</button>
</div>
$("body").on("click", ".btnFavorite", function() {
alert("hej");
var input = $("#search").val();
saveFavorite(favoriteMovie);
});
It seems that you are using click event without using the right ID.
$(".btnFavorite") here you need to use the right ID, which is related to the button you are going to activate. In this case "btnArkiv".
var movieList = [
{
'ID': 1,
'title': 'Movie 1',
'year': 1988
},
{
'ID': 2,
'title': 'Movie 2',
'year': 2017
}
];
$(".btnFavorite").on("click", function(){
alert("hej");
var input = $("#search").val();
saveFavorite(favoriteMovie);
});
$(".btnAdd").click(function() {
for(index in movieList){
$(".list").append("<div class='search-result' data-id=" + movieList[index].ID + "><h3>" + movieList[index].title + " (" + movieList[index].year + ")</h3><button class='btn btn-warning btnFavorite' data-action='favoritize-id-" + movieList[index].ID + "'>Favorite Movie " + movieList[index].ID + "</button></div>");
}
});
.search-result {
background-color: #EEE;
padding: 20px;
margin: 15px 0;
}
.search-result h3 {
display: inline-block;
}
.search-result button {
display: inline-block;
margin: 0 0 0 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-warning btnAdd">Show Movie List</button>
<div class="list"></div>
According to the docs for .on this is why you are finding that only your first set of buttons work after cloning the result 10 times:
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated events to attach event handlers.
You can read more about it here: http://api.jquery.com/on/.
Since there isn't much information to go on, one way you can make all of your buttons use the same event handler is by using event delegation as CBroe mentioned in the comments.
Check out the snippet I have here with all the buttons working.
$(".search").on("click", function(e) {
if ($(e.target).hasClass('btnFavorite')) {
alert('hej');
}
});
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>
In the snippet, I put a listener on the parent container and then check that the clicked target is the correct button before alerting.

How to make a button visible by clicking another button?

How can I make the button save visible when I click the edit button? This is my code so far, but it happends nothing. I'm working in a jsp
<INPUT TYPE="BUTTON" VALUE="Edit" ONCLICK="btnEdit()" class="styled-button-2">
<INPUT TYPE="BUTTON" VALUE="Save" ONCLICK="btnSave()" class="styled-button-2" style="visibility:hidden;" id="save">
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementsById("save").style.visibility="visible";}
}
</script>
DEMO
It is considered bad practice to add onclick in your html, and you miss-spelled a method. You should equally avoid adding your css in your html as well.
HTML:
<INPUT TYPE="BUTTON" VALUE="Edit" class="styled-button-2" id="edit">
<INPUT TYPE="BUTTON" VALUE="Save" class="styled-button-2" id="save">
JS:
var edit = document.getElementById("edit");
var save = document.getElementById("save");
edit.onclick = function() {
save.style.visibility = "visible";
}
CSS:
#save {
visibility: "hidden";
}
Must be a long day.
You have a misspelling.
Not right
document.getElementsById
Right Way
document.getElementById
document.getElementById("save").style.visibility="visible";
use getElementById not getElementsById
Probably a simple error, but you wrote getElementsById not getElementById, which meant you were trying to get more than one element, when infact you only need to get the "save" button.
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
{document.getElementById("save").style.visibility="visible";}
}
</script>
Side note: You may want to tidy your code:
<SCRIPT LANGUAGE="JavaScript">
function btnEdit()
{
document.getElementById("save").style.visibility="visible";
}
</script>

Categories