Javascript Changing button inner text without chaning the icon - javascript

I created the following button, and want to change the inner text "test" to other word.
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button>
I tried below method it can change the word but also deleted the icon.
$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});
Is there any way that can only change the word, but keeping the icon, thanks!

like #Kunal Tanwar said, wrapping the text in a span solves it and using Jquery this is my approach.. assuming the button has an id of test
using the .find() method to find the span child
<button type="button" id="test">
<i class="fa-2x fa-regular fa-floppy-disk"></i>
<span>test<span>
</button>
$('#test').on('click', function(e){
e.preventDefault();
$(this).find('span').text("other");
});
and another option would be to use the decendant selector since the span is a direct child of the button
$('#test').on('click', function(e){
$('#test > span').text('other');
});

I haven't use jQuery since very long so here's an example in vanilla javascript.
const btn = document.querySelector('#test');
btn.addEventListener('click', (e) => {
e.preventDefault();
// selecting span tag -> you can also give it a specific id or class if you want
btn.children[1].innerText = 'other';
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<button type="button" id="test">
<i class="fa-2x fa-regular fa-floppy-disk"></i>
<span>test</span>
</button>

What .text() method does is that it overwrites not only text but HTML as well. The easiest thing to do is move your text inside the <i> so it doesn't get overwitten only what's inside of it. Review the example below and notice that the icon remains -- it's because it's actually a CSS pseudo-element and is always ignored by methods and functions dealing with the DOM.
$('.test').on('click', function() {
$(this).find('i').text(' IT WORKS!')
});
<link href='https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<button class='test' type='button'>
<i class="fa fa-star-o"> TEST</i>
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can also replace this using Regex without adding span or any other element in that button. Here is solution:
$('#test').on('click', function(e){
e.preventDefault();
const regex = /([^>]+)$/;
$(this).html($(this).html().replace(regex,'other'));
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button>
Another solution is to change text inside of <i> element:
$('#test').on('click', function(e){
$(this).find('i').text("Other");
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk">test</i></button>

Related

Alter text in Button after Ajax call

I'm hitting some trouble in trying to change the text in a button after a user clicks on the wishlist link. The Ajax call is working successfully right now and the data is updated correctly in the DB, currently the function displays a notification pop up in the browser when a user clicks on wishlist, but I would like to change the "wishlist" part of the button to "Added to wishlist" after a successful submission.
EDIT:
I have added $("#btn span").text("Added to wishlist");
But it's still not working.
function wish($p_id){
var w_id = $p_id;
var email = $(".wish").data("user");
if(email != 0){
$.ajax({
url:"function.php",
method:"post",
data:{w_id:w_id,email:email},
success: function($wish){
if($wish > 0){
notif({
msg:"Product Already Added to wishlist!!!",
type:"warning",
width:330,
height:40,
timeout:1000,
})
}else{
$("#btn span").text("Added to wishlist");
notif({
msg:"Added to wishlist",
type:"success",
width:330,
height:40,
timeout:1000,
})
}
}
})
}
}
and the HTML part
<a href='$add_wish' id="btn"class='btn btn-default add-to-cart wish' data-user='$s_email' onclick='wish($id)'>
<i class='glyphicon glyphicon-heart'></i> Wishlist
</a>
The issue is that in this code:
$("#btn span").text("Added to wishlist");
your selector is missing the target. It tries to find an element with the ID of "btn", which is fine, but then it tries to look for a <span> element inside that, which doesn't exist.
It's trivial to resolve of course by wrapping the text in the expected <span>:
$("#btn span").text("Added to wishlist");
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='$add_wish' id="btn"class='btn btn-default add-to-cart wish' data-user='$s_email' onclick='wish($id)'>
<i class='glyphicon glyphicon-heart'></i>
<span>Wishlist</span>
</a>
N.B. Note that writing simply
$("#btn").text("Added to wishlist")
is undesirable because it will erase the <i> containing the icon.
Demo (for comparison with above):
$("#btn").text("Added to wishlist");
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='$add_wish' id="btn"class='btn btn-default add-to-cart wish' data-user='$s_email' onclick='wish($id)'>
<i class='glyphicon glyphicon-heart'></i>
Wishlist
</a>
Relevant documentation: https://api.jquery.com/category/selectors/
Identify your button by adding an id and put your text inside a span
<a href='$add_wish' id='my_button' class='btn btn-default add-to-cart wish' data-user='$s_email' onclick='wish($id)'>
<i class='glyphicon glyphicon-heart'></i> <span>Wishlist</span>
</a>
You have to change the innerText of the span, just add the following code after the product is added :
document.querySelector('#my_button span').innerText = 'Added to wishlist';

Using jQuery, can't add behavior on click to buttons created with innerHTML

I have some buttons and I added some behavior on click to all of them with jQuery and they worked fine, but now that those buttons are generated dynamically by changing the innerHTML of the div with a script, the behavior don't work anymore
Here is an example, like this every time I click any of the two buttons, it show an alert with the message 'clicked'.
Fiddle
$('.foo').on('click', function(){
alert('clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="home">
<button class='foo' > Test </button>
<button class='foo' > Test </button>
</div>
But if I insert the buttons by changing the innerHTML of home with the button generate, it does not works anymore
Fiddle
$(".gen").on("click", function(){
$('.home').html(
"<button class='foo' > Test </button>" +
"<button class='foo' > Test </button>");
})
$('.foo').on('click', function(){
alert('clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button class="gen" > Generate </button>
</div>
<div class="home">
</div>
I really don't know what's going on
$('.foo') selects certain elements. .on() adds an event handler to only the selected elements. Any new elements with the "foo" class will not have that handler. Either add them manually to the new elements or better still use a delegate.
Basically, since your "foo" elements do not exist until after you click "generate", the call to .on() adds a handler to nothing.
Here's a solution using jQuery's delegate implementation
$(".gen").on("click", function(){
$('.home').html(
"<button class='foo' > Test </button>" +
"<button class='foo' > Test </button>");
})
$(document).on('click', '.foo', function(){
console.log('clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button class="gen" > Generate </button>
</div>
<div class="home">
</div>

How to change text in "span" that is immediately after "i" using jquery?

I'm trying to change the text on a button in a plugin I am using using jquery.
It's outer html is
<button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour">
<span class="ladda-label">
<i class="ab-hour-icon">
<span></span>
</i>8:00 am
</span>
</button>
It's inner html is
<span class="ladda-label">
<i class="ab-hour-icon">
<span></span>
</i>8:00 am
</span>
Anyone know how I'd change 8:00AM to 9-3AM?
You can use javascript Node.nextSibling that contain immediately text after element.
$(".ab-hour .ab-hour-icon")[0].nextSibling.nodeValue = "9-3AM";
$(".ab-hour .ab-hour-icon")[0].nextSibling.nodeValue = "9-3AM";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour"><span class="ladda-label"><i class="ab-hour-icon"><span></span></i>8:00 am</span></button>
Also you use only javascript
document.querySelector(".ab-hour .ab-hour-icon").nextSibling.nodeValue = "9-3AM";
Do you mean this?
$( "yourbutton" ).html('yourtext');
I would do it like this
$( ".ab-hour span" ).html('9-3AM');
It would be best to change the inner HTML so the span can directly be changed. If that is not an option you could use
$( ".ab-hour span" ).html('<i class="ab-hour-icon"><span></span></i>9-3AM');
Try this
$(".ladda-label").html("<i class=\"ab-hour-icon\"></i>9-3 am");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour">
<span class="ladda-label">
<i class="ab-hour-icon">
</i>8:00 am</span>
</button>
You have to add <span> in jquery code so your icon will remain
$(".ab-hour").html('<span class="ladda-label"><i class="ab-hour-icon"><span></span></i>9-3AM</span>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour">
<span class="ladda-label">
<i class="ab-hour-icon">
</i>8:00 am</span>
</button>

Find element and see if its active/hasClass

I am trying to access a button in my leaflet map. The button is created using a plugin "easy-button".
My main goal is to see if the button has been clicked (is active), I will use it for validation in another function, not shown here.
This is how the html for the button looks like in the browser debugger (I believe the html is created by the plugin?).
Before it's clicked
<button class="easy-button-button leaflet-bar-part leaflet-interactive add-markers-active" title="Vis crosshair">
<span class="button-state state-add-markers add-markers-active">
<span class="fa fa-crosshairs fa-lg"></span>
</span>
</button>
After it's clicked
<button class="easy-button-button leaflet-bar-part leaflet-interactive remove-markers-active" title="Fjern crosshair">
<span class="button-state state-remove-markers remove-markers-active">
<span class="fa fa-undo"></span>
</span>
</button>
This click function access the button and show 'Button was clicked' but the if statement does not pass. I got to the button using Copy CSS path in the browser, but it seem really long.
$("div.leaflet-bar.easy-button-container.leaflet-control > button > span").click(function(){
alert("Button was clicked");
if
($('span').hasClass('fa fa-crosshair fa-lg'))
{
alert('My button has active class')
}
});
Any advice on what I am doing wrong?
This
if($('span').hasClass('fa fa-crosshair fa-lg'))
Will not target the span you are expecting it to.
You wanted
if($('span',this).hasClass('fa fa-crosshair fa-lg'))
To target the child span of the span you clicked on
Run this example, hope it helps:
$(document).ready(function() {
// My example to trigger the click on buttons..
$("button > span > span").click(function(){
alert("Button was clicked");
if (
//$(this).hasClass('fa') && <-- You don't need it, both have it
$(this).hasClass('fa-crosshairs') &&
$(this).hasClass('fa-lg')
) {
alert('My button has active class');
} else {
alert('Ops..');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Unclicked -->
<button class="easy-button-button leaflet-bar-part leaflet-interactive add-markers-active" title="Vis crosshair">
<span class="button-state state-add-markers add-markers-active">
<span class="fa fa-crosshairs fa-lg">click me</span>
</span>
</button>
<!-- Clicked -->
<button class="easy-button-button leaflet-bar-part leaflet-interactive remove-markers-active" title="Fjern crosshair">
<span class="button-state state-remove-markers remove-markers-active">
<span class="fa fa-undo">clicked</span>
</span>
</button>

How to add repetitive div with jQuery?

When I click on the new button with jQuery it adds the div, but it only adds one. When I check from DevTools it constantly creates the same place. But I want it to add another one after that. Can you help me?
HTML code
<div class="text-left" style="margin-bottom: 15px;">
<button type="button" class="add-extra-email-button btn btn-success" disabled><i class="fas fa-plus"></i></button>
</div>
<div class="clone"></div>
Here are the sample js codes
$('.add-extra-email-button').click(function() {
var element = $('.clone');
element.html(
'<div class="clone_edilen_email">' +
'<li>' +
'<a href="javascript:;"> Test' +
'<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' +
'</a>' +
'</li>' +
'</div>'
);
$('.clone_edilen_email').addClass('single-email remove-email');
$('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
$('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
$(document).on('click', '.remove-field-email', function(e) {
$(this).parent('.btn-delete-branch-email').parent('.remove-email').remove();
e.preventDefault();
});
If I understand correctly, you want to add the <div class="clone_edilen_email"> again and again, as soon somebody clicks on the .add-extra-email-button button.
In general, calling element.html('<some_wild_html></some_wild_html>') will always override the full inner content of element with <some_wild_html></some_wild_html>. Also, if the element already contains some other sub-elements, they will got lost. In your given code example, I assume, your intention was to extend the element's html and not replace it.
Here is my suggestion:
$('.add-extra-email-button').click(function() {
var newDiv = $('<div class="clone_edilen_mail"></div>');
newDiv.html('<li><a href="javascript:;"> Test<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i></li>');
$('.clone').append(newDiv); // This is the important clue here!
// afterwards you may insert your residual class stuff
// $('.clone_edilen_email').addClass('single-email remove-email'); <- I would suggest you add these classes already at the begining, where I set the variable "newDiv"
// ...
// $('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
// $('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
// .. your other code may follow here ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clone">I am a clone-div!</div>
<button class="add-extra-email-button">Click Me!</button>
Hope that this might help you!
Try This Method, Append Duplicate Elements and Contents Using jQuery .clone() Method
<!doctype html>
<html>
<head>
<title>jQuery Clone() – Add Elements and its Contents</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
div {
margin:3px;
padding:3px;
border:solid 1px #999;
width:300px;
}
</style>
</head>
<body>
<p>Click the button to clone (make a duplicate) of the DIV element!</p>
<div id="Container">Hello, how was your day!</div>
<p><input type="button" id="Button1" value="Clone it" /></p>
</body>
<script>
$(document).ready(function () {
$('#Button1').on('click', function () {
$('#Container')
.clone()
.appendTo("body");
});
});
</script>
</html>
In your first click function you replace all the content of your div clone so even if you click again you are going to have only one. He is just replacing the old one.
I didn't get what you are trying to do with the second click function.

Categories