Button in div not working - javascript

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.

Related

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

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>

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>

How to toggle show and hide for two forms present in the same div?

I have two forms present in a div, form1 is visible when the page loads, and if I click the next button form1 is hidden and form2 is shown, which is working as expected.
Now I want to achieve the reverse of above scenario which is on click of a back button, form2 should be hidden and form 1 is shown.
Here's javascript code I have so far..
function switchVisible() {
document.getElementById("disappear").innerHTML = "";
if (document.getElementById('newpost')) {
if (document.getElementById('newpost').style.display == 'none') {
document.getElementById('newpost').style.display = 'block';
document.getElementById('newpost2').style.display = 'none';
} else {
document.getElementById('newpost').style.display = 'none';
document.getElementById('newpost2').style.display = 'block';
}
}
}
So basically I am looking for a way to achieve toggle functionality for two forms present in the same div using javascript and setting their display property.
Use a variable stepCount and then according to the value of count display appropriate form.
Like initialise the stepCount with 0, then on click of next increment it by 1 and check condition if stepCount is 1 show second form
Similarly from there if back button is pressed decrement the stepCount by 1 and check condition if stepCount is 0 show first form
Do all this on click of appropriate button click event
Make two button elements
<button id="next"></button>
<button id="back"></button>
You can use jquery (or plain javascript) for this, but I personally prefer jquery.
$("#next").click(function {
$("#newpost").hide();
$("#newpost1").show();
});
$("#back").click(function {
$("#newpost").show();
$("#newpost1").hide();
});
(Here 'newpost' and 'newpost1' are the id's of the two form elements)
You can use a similar format if you want to use plain javascript.
Add this
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</head>
You can also use link button and provide URL for particular form in this and hide back link button when click on back that time show only Next button.
e.g.
Next
Previous
$("#btnNext").click(function {
$("#btnNext").hide();
$("#btnPrevious").show();
});
$("#btnPrevious").click(function {
$("#btnPrevious").show();
$("#btnNext").hide();
});
You can use toggle function to show hide div.
$('#newpost2').hide();
$("#Toggle").click(function() {
$(this).text(function(i, v) {
return v === 'More' ? 'Back' : 'More'
});
$('#newpost, #newpost2').toggle();
});
.one {
height: 100px;
width: 100px;
background: #eee;
float: left;
}
.two {
height: 100px;
width: 150px;
background: #fdcb05;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='Toggle' class='pushme'>More</button>
<div class="one" id='newpost'>
<p>Show your contain</p>
</div>
<div class="two" id='newpost2'>
<p>Hide your contain</p>
</div>
This fiddle for button disappear:
$("#next").click(function()
{
$("#next").hide();
$("#back").show();
});
$("#back").click(function() {
$("#back").show();
$("#next").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="button" id="next" value="Next"/>
<input type="button" id="back" value="Back"/>
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="switchVisible();">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="previousVisible();" >BACK</button>
simply use this jquery:
function switchVisible()
{
$("#newpost").hide();
$("#newpost2").show();
}
function previousVisible()
{
$("#newpost").show();
$("#newpost2").hide();
}
your updated fiddle
Or you may do like this:
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="form(1);">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="form(2);" >BACK</button>
function form(a)
{
if(a==1)
document.getElementById("newpost").style.display="none";
else
document.getElementById("newpost2").style.display="block";
}

Identify the Click Event in bootstrap touch spin

I am little bit confusion to find the click event in the class using jquery.
my question is how to identify whether I click touchspin down or up
I am using bootstrap touch spin.
<button type="button" class="btn btn-default bootstrap-touchspin-down">-</button>
<input type="number" value="18" onchange="calculatetotal(3)" style="width: 100%; padding: 0px; display: block;" class="ex_limit form-control" readonly="" id="qty3">
<button type="button" class="btn btn-default bootstrap-touchspin-up">+</button>
I Want to calculate some process in when Up botton clicked and some process in down button click.
Here I try to Identify the button using class.
$('.btn, .btn-default, .bootstrap-touchspin-down').click(function(){
alert("down!");
});
Please help me to do this task.
$('[class*="bootstrap-touchspin-"]').click(function(event) {
var $this = $(this);
if ($this.hasClass('bootstrap-touchspin-down')) {
alert('down');
} else if ($this.hasClass('bootstrap-touchspin-up')) {
alert('up');
}
});
Alternatively:
$('.bootstrap-touchspin-down').click(function(event) {
alert('down');
});
$('.bootstrap-touchspin-up').click(function(event) {
alert('up');
});
better and easy way is to handle change event like given below
$('input[name=\'cart-quantity\']').on("change",function(event){
alert("hi")
})

Iterate throughout div using jQuery

I have a button, I need to get a status i.e. to check weather its male or female, below is my code.
<!-- GENDER BUTTON -->
<div class="btn-group gender_guest" tabindex="0">
<a class="btn active btn-default btn-success gender" onclick="genderClicked(this,'female${status.index}')" id="male${status.index}">Male</a>
<a class="btn btn-default gender" onclick="genderClicked(this,'male${status.index}')" id="female${status.index}">Female</a>
</div>
My script
function genderClicked(clickedObj, id) {
$('#' + id).removeClass("active");
$('#' + id).removeClass("btn-success");
$(clickedObj).addClass("active");
$(clickedObj).addClass("btn-success");
}
This script works fine,its purpose is to just change color.I need another method to know which gender is selected...
Inside my JavaScript page I need to set in to a variable what is the gender, my onclick and id is used to pass the value to change the color when it gets clicked.So without touching that I need to set the value to that variable.
Since you are using jQuery, use the class selector to add an event.
I commented the JS, to explain what it does.
$('.gender').on('click', function(e) {
// prevent that the anchor is triggered
e.preventDefault();
// remove the classes from a links
$('.gender_guest a').removeClass('active btn-success');
// add the classes to the clicked one
$(this).addClass('active btn-success');
// get the gender */
var gender = $(this).attr('id');
// returns male.... or female...
});
/* only for demonstration */
.active{ border: 2px solid blue }
.btn-success { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- GENDER BUTTON -->
<div class="btn-group gender_guest" tabindex="0">
<a class="btn active btn-default btn-success gender" id="male${status.index}">Male</a>
<a class="btn btn-default gender" id="female${status.index}">Female</a>
</div>
function genderClicked(clickedObj, id) {
..
var gender = "male";
if( id == "female${status.index}" ){
gender = "female";
}
console.log(gender);
}

Categories