Javascript: Change button text change after click - javascript

I have a simple question about changing the text of a button after the user clicks it.
I would like the button click to cause the text to toggle between two values: "More" and "Less". Note that before the first click, it must have the value "More" and after the click the value "Less":
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
More
</button>
<div class="collapse" id="collapseExample">
<p>Test</p>
</div>

This can be achieved using vanilla javascript via the following:
/*
Fetch the buttom element
*/
const button = document.body.querySelector('[data-target="#collapseExample"]');
/*
Add click event listener where we will provide logic that updates the button text
*/
button.addEventListener('click', function() {
/*
Update the text of the button to toggle beween "More" and "Less" when clicked
*/
if(button.innerText.toLowerCase() === 'less') {
button.innerText = 'More';
}
else {
button.innerText = 'Less';
}
});
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
More
</button>
<div class="collapse" id="collapseExample">
<p>Test</p>
</div>

Basically, you could add an onclick event to the button referencing to a function:
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample" onclick="changeText()">
More
</button>
Then, you prepare the function to change the text:
function changeText () {
if (this.innerText == "More") { // check if text inside is "More"
this.innerText == "Less"; // If so, change to "Less"
} else {
this.innerText == "More";
}
}

Related

How to get all attr value in same class by click() jQuery

I am making a Simon game, but I need to get the "id" (attribute) value. but whenever I click on the different color it still gives me the first attr value which is in this case is green. how many times do I click on the red, blue, or yellow button but it still gives me a green value (the first one). help, please!
//Below code HTML
<div class="container">
<button class="btn green" id="green"></button>
<button class="btn red" id="red"></button><br />
<button class="btn yellow" id="yellow"></button>
<button class="btn blue" id="blue"></button>
</div>
//Below code Jquery
$(".btn").click(function () {
var userChosenColor =$(".btn").attr("id");
console.log(userChosenColor);
});
Reference to the button clicked.
You do not necessarily need jQuery for this.
$(".btn").click(function () {
var userChosenColor = $(this).attr("id");
console.log('jQuery: '+ userChosenColor);
});
/* non jQuery */
const btns = document.querySelectorAll('.btn');
btns.forEach(btn=> {
btn.addEventListener('click', () => {
console.log('JS only: '+btn.id)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<button class="btn green" id="green">1</button>
<button class="btn red" id="red">2</button><br />
<button class="btn yellow" id="yellow">3</button>
<button class="btn blue" id="blue">4</button>
</div>

Keep toggle hide/show after refresh page [duplicate]

I have three toggle buttons and I want to keep toggle state after refresh page.I read many things but dont know how to use them in my case.
This is buttons and divs
<button class="badge badge-danger mb-4 d-flex left" type="button" data-toggle="collapse" data-target="#personal-data" aria-expanded="false" aria-controls="personal-data"></button>
<button class="badge badge-danger mb-4 mr-md-4 ml-md-4" type="button" data-toggle="collapse" data-target="#email-change" aria-expanded="false" aria-controls="email-change"></button>
<button class="badge badge-danger mb-4" type="button" data-toggle="collapse" data-target="#user-history" aria-expanded="false" aria-controls="user-history"></button>
<div class="collapse" id="personal-data">
<div class="form-group col-12">
<div class="col-12">
<div class="collapse" id="email-change">
<div class="col-12">
<div class="collapse" id="user-history">
Use can use below way to keep state after a refresh.
Cookie
LocalStorage
Both of these can store client-side data which will preserve your state.
Provide each collapse element a unique id across the website so there'll be no room for conflict. So based on user action collapse or un-collapses an element you'll update state in storage. Now using bootstrap event and API, you can collapse or un-collapses an element based on storage state.
Here is a working demo:
https://jsfiddle.net/c1ovt5g4/
<button class="badge badge-danger left" type="button" data-toggle="collapse" data-target="#personal-data" aria-expanded="false" aria-controls="personal-data">Personal Data</button>
<button class="badge badge-danger " type="button" data-toggle="collapse" data-target="#email-change" aria-expanded="false" aria-controls="email-change">Email Change</button>
<button class="badge badge-danger" type="button" data-toggle="collapse" data-target="#user-history" aria-expanded="false" aria-controls="user-history">User History</button>
<div class="collapse" id="personal-data"> PERSONAL DATA</div>
<div class="collapse" id="email-change"> EMAIL CHANGE</div>
<div class="collapse" id="user-history">USER HISTORY</div>
$(".collapse").on("hidden.bs.collapse", function() {
localStorage.setItem("coll_" + this.id, false);
});
$(".collapse").on("shown.bs.collapse", function() {
localStorage.setItem("coll_" + this.id, true);
});
$(".collapse").each(function() {
if (localStorage.getItem("coll_" + this.id) == "true") {
$(this).collapse("show");
}
});
I tweaked Object's answer to remove the key from localstorage if hidden. From what I could find, there isn't a need to check if the key exists before attempting to remove. This reduces the amount of items being kept in localstorage.
$(document).ready(function () {
//If shown.bs.collapse add the unique id to local storage
$(".collapse").on("shown.bs.collapse", function () {
localStorage.setItem("coll_" + this.id, true);
});
//If hidden.bs.collaspe remove the unique id from local storage
$(".collapse").on("hidden.bs.collapse", function () {
localStorage.removeItem("coll_" + this.id);
});
//If the key exists and is set to true, show the collapsed, otherwise hide
$(".collapse").each(function () {
if (localStorage.getItem("coll_" + this.id) == "true") {
$(this).collapse("show");
}
else {
$(this).collapse("hide");
}
});
});

All drop-down menus' text content change at the same time instead of updating separately

I have three drop-down menus on my site that I created via Bootstrap.
Ideally, when a user clicks on a drop-down menu and selects one of the inner menu items, the drop-down menu should update its text content to the text content of the selected menu item.
However, for any drop-down menu, if a user clicks on a menu item, all three drop-down menus' text content update instead of only that individual drop-down menu as seen below
My current approach is that the aria-expanded attribute for each drop-down button changes to true if a drop-down is open on a button. If the aria-expanded value of a specific drop-down menu is true, then that button's text content changes to the text content of the selected menu item.
JS
function addPlanesToDropDowns() {
let dropdowns = document.querySelector('.dropdown-menu');
let dropDownButtonOne = document.querySelector('#dropdownMenuButtonOne');
let dropDownButtonTwo = document.querySelector("#dropdownMenuButtonTwo");
let dropDownButtonThree = document.querySelector("#dropdownMenuButtonThree");
dropDownDisabledCheck();
for (let i = 0; i < state.airplaneData.length; i++) {
let dropDownMenuItem = document.createElement('a');
dropDownMenuItem.classList.add('dropdown-item');
dropDownMenuItem.href = '#';
dropDownMenuItem.textContent = state.airplaneData[i].make + " " + state.airplaneData[i].model;
dropDownMenuItem.addEventListener('click', function (event) {
event.preventDefault();
if (dropDownButtonOne.getAttribute('aria-expanded')) {
dropDownButtonOne.textContent = dropDownMenuItem.textContent;
dropDownButtonOne.setAttribute('aria-expanded', false);
}
if (dropDownButtonTwo.getAttribute('aria-expanded')) {
dropDownButtonTwo.textContent = dropDownMenuItem.textContent;
dropDownButtonTwo.setAttribute('aria-expanded', false);
}
if (dropDownButtonThree.getAttribute('aria-expanded')) {
dropDownButtonThree.textContent = dropDownMenuItem.textContent;
dropDownButtonThree.setAttribute('aria-expanded', false);
}
dropDownDisabledCheck();
});
dropdowns.appendChild(dropDownMenuItem);
}
}
HTML
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButtonOne" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Plane 1</button>
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButtonTwo" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Plane 2</button>
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButtonThree" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Plane 3</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<!-- <a class="dropdown-item" href="#">Planes go here</a> -->
</div>
</div>
Despite this, all three drop-down menus update with the same selected menu item text content even though I am only setting the text content on the button element with the specific ID attribute.
This fragment of code dropDownButtonOne.getAttribute('aria-expanded') returns a string, not a boolean value, so either "true" or "false".
As it is a non-empty string, it always evaluates to TRUE. You need to change your condition.
You could check if(dropDownButtonOne.getAttribute('aria-expanded') === "true") for example.

How to detect the click on a button that is inside of a dropdown with jquery

I am having trouble with a very simple thing. I have two buttons inside a dropdown, and I can't detect when the user click on them. The rest of the buttons works well, less this two.
The buttons are:
<div class="btn-group">
<button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown">Nodes</button>
<ul class="dropdown-menu" id="NodeFilters">
<button type='button' class='btn btn-secondary btn-sm' id='allFilter'>All</button>
<button type='button' class='btn btn-secondary btn-sm' id='cleanFilter'>Clean</button>
</ul>
</div>
My function is:
//This function controls if some button is clicked
function btnController(){
$('.btn').click(function(){
let id_btn = $(this).attr("id");
console.log(id_btn);
if(id_btn == 'allFilter' | id_btn == 'cleanFilter'){
alert('sss')
}
});
}
$(document).ready(function() {
btnController();
} );
When I click the rest of the buttons, the console.log(id_btn); prints the id of the button. But when I click these two buttons inside the dropdown, nothing happens. Why is this happening?
Note: When I click these buttons, the dropdown always gets closed.
Can somebody help me? Thank you very much!
Use event delegation like this:
$(function(){
$(document).on('click', '.btn', function(){
let id_btn = $(this).attr("id");
console.log(id_btn);
if(id_btn === 'allFilter' || id_btn === 'cleanFilter'){
alert('sss')
}
})
})

Change Text of button in jQuery or JavaScript

I have a few buttons each with a specific class to differentiate it from other similar buttons. Class name follows the format moreid where id changes with button. I am using following code to change button text:
function changeText(btn){
$('.'+btn).text(function(i, text){
return text === "Show More" ? "Show Less" : "Show More";}
)}
I call this function using changeText(moreid). With this code I get the error:
Error: Syntax error, unrecognized expression: .[object HTMLDivElement]
This is the HTML of button
<button type="button"
class="btn btn-primary btn-lg moreapple"
data-toggle="collapse"
data-target="#moreapple"
onclick="changeText(moreapple)">Show More</button>
The only thing that change from one button to another is moreapple to morenews etc.
How can I change this function to change button text?
Your changeText(btn) tells that, you're passing btn as an argument, so you might have to give this a try
$(btn).text(function(i, text){
return text === "Show More" ? "Show Less" : "Show More";
});
Your markup should be like this unless you've specific requirements
<button type="button"
class="btn btn-primary btn-lg moreapple"
data-toggle="collapse"
data-target="#moreapple"
onclick="changeText(this)">Show More</button>
use $(btn) as it comes from the calling function
changeText()
Fiddle Example
Obviously your Id's would be different depending on your naming convention
Duplicate Question Answer
var status = "less";
function toggleText()
{
var text="Here is some text that I want added to the HTML file";
if (status == "less") {
document.getElementById("textArea").innerHTML=text;
document.getElementById("toggleButton").innerText = "See Less";
status = "more";
} else if (status == "more") {
document.getElementById("textArea").innerHTML = "";
document.getElementById("toggleButton").innerText = "See More";
status = "less"
}
}
You need to update your markup from
<button type="button"
class="btn btn-primary btn-lg moreapple"
data-toggle="collapse"
data-target="#moreapple"
onclick="changeText(moreapple)">Show More</button>
to
<button type="button"
class="btn btn-primary btn-lg moreapple"
data-toggle="collapse"
data-target="#moreapple"
onclick="changeText('moreapple')">Show More</button> <!-- Pass moreapple as string -->

Categories

Resources