Change Text of button in jQuery or JavaScript - 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 -->

Related

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')
}
})
})

Javascript how to identify button clicked

I have a page with many articles. Each article has a delete button. How can I identify the button clicked for the article?
Currently I have this:
<button type="button" id="delete-article" class="btn btn-small btn-danger">Delete</button>
$('#delete-article').on('click', function(e) {
console.log('Test delete article');
});
This logs 'Test delete article' according to the number of articles on the page.
You can attach the event on button and use this object to refer the currently clicked button:
$('button').on('click', function(e) {
console.log(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="delete-article" class="btn btn-small btn-danger">Delete</button>
<button type="button" id="delete-article-2" class="btn btn-small btn-danger">Delete</button>
You can use your event variable to get the target of the event (that is, the element responsible) and from there get its id, like this:
let btnId = event.target.id;
However, for that to work properly you should assign unique ids to your buttons. If you want to provide other data (or you don't want to use id) you can append custom attributes, like data-value or similar, and use it like this:
let myValue = event.target.getAttribute('data-value');
You need to establish relation between article and corresponding button, one way to implement is by using HTML5 data attribute.
assign data-articleId to article id in button element and when you click the button you can access which button was clicked by using Jquery .data() function.
<button type="button" data-articleId='123' class="btn btn-small btn-danger delete-article">Delete</button>
$('.delete-article').on('click', function(e) {
$(this).data('articleId'); //will return 123;
console.log('Test delete article');
});
If all the buttons have this markup
<button type="button" id="delete-article" class="btn btn-small btn-danger">Delete</button>
Then the DOM sees them as just one button, you should find a way to attach unique ids to your buttons
You can get an object of clicked button then you can get any details from that object like an index or whatever you want.
$('#delete-article').click(function(){
console.log($(this));
console.log($(this).index());
});
You can directly achieve it by using the JavaScript.
document.addEventListener('click',(e)=>{
console.log(e.target.id)
})
<button type="button" id="delete-article1" class="btn btn-small btn-danger">Delete1</button>
<button type="button" id="delete-article2" class="btn btn-small btn-danger">Delete2</button>
<button type="button" id="delete-article3" class="btn btn-small btn-danger">Delete3</button>
<button type="button" id="delete-article4" class="btn btn-small btn-danger">Delete4</button>
<button type="button" id="delete-article5" class="btn btn-small btn-danger">Delete5</button>
<button type="button" id="delete-article6" class="btn btn-small btn-danger">Delete6</button>
<button type="button" id="delete-article7" class="btn btn-small btn-danger">Delete7</button>

Javascript: Change button text change after click

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";
}
}

Find any sibling that has matching class

I have a toolbar with buttons. Only one button has the class 'btn-info' for instance to indicate it is currently selected.
But it may not be 'btn-info', it could be btn-anything.
If I click any of the buttons in the tool bar I want to know what the matching class is on which ever button is selected.
I have tried:
$('.btn-toggle-group .btn').click(function(){
var selectedClass = $(this).siblings('button[class^="btn-"]').prop('class')
$('.btn-toggle-group .btn').removeClass('btn-info btn-primary btn-danger btn-success btn-warning btn-default')
})
And...
$('.btn-toggle-group .btn').click(function(){
var selectedClass = $(this).parent().find('[class^="btn-"]').prop('class')
$('.btn-toggle-group .btn').removeClass('btn-info btn-primary btn-danger btn-success btn-warning btn-default')
})
But to no avail.
How can I achieve this? The solution in Jquery or pure Javascript is fine (Javascript is preferred as it is native and faster).
<div class="btn-group btn-toggle-group">
<button type="button" class="btn btn-info">Current</button>
<button type="button" class="btn">Deleted</button>
</div>
Try using * instead of ^
$(this).siblings('button[class*="btn-"]').prop('class');
I think you just need to switch to .attr('class') instead of .prop('class'). DOM elements have properties className and classList; you could also use those if preferred.

How to use bootstrap toggle buttons?

I have a toggle buttons:
<div class="btn-group btn-group-vertical btn-block no-padding" data-toggle="buttons-checkbox">
<button type="button" class="btn btn-block full-width">button1</button>
<button type="button" onclick="admLayer();" class="btn btn-block full-width">button2</button>
</div>
When i press button2 i call admLayer() function. All works fine but like simple button. How to send to function when button pressed or unpressed?
UPDATE
I try use http://www.larentis.eu/bootstrap_toggle_buttons/ :
<script>
$('#btn-group btn-group-vertical btn-block no-padding').toggleButtons({
onChange: function ($el, status, e) {
console.log($el, status, e);
}
});
</script>
But its not work.
Whats can be wrong?
You are mistakenly selecting the div on the basis of Id, If you want to select the div, you should do something like this :-
<script>
$(".btn-group").toggleButtons({
onChange: function ($el, status, e) {
console.log($el, status, e);
}
});
</script>
Classes are selected with Dot('.') and ids are selected with Hash('#').
Thanks

Categories

Resources