-1

I've added an icon to a button like this:

Before adding Item

When user adds item into the cart, the button becomes After adding Item

I'm trying to update text of the button whenever the user adds an item to the cart. It is able to update the text but the icon goes missing.

This is the html.

<div class="wrapper">
<button class="btn btn-primary" id="btnView" data-toggle="modal" data-target="#myModal"><i class="fa fa-cart-plus"></i> 0 Item(s) in cart</button>
            </div>

This is the css for the wrapper

.wrapper { 
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    float: right; /* if you had floats before? otherwise inline-block will behave differently */
}

When the user add an item into the cart, I'm updating the text

$('#btnView').text( aItems.length + ' Item(s) in cart' );

Can I update the text while maintaining the icon? Am I missing something?

Thanks guys!

Andrew
  • 7
  • 6
  • 1
    Did you check the update button in the dev tools? By adding value to `.text()`, it replaces all the content inside the button with the value you added, so it removes `` as well. It is more or less the same as `.html()` when added with a value – Carl Binalla Jul 24 '19 at 09:17
  • More info about the difference of `.text()` and `.html()` [here](https://stackoverflow.com/questions/1910794/what-is-the-difference-between-jquery-text-and-html) if you are interested – Carl Binalla Jul 24 '19 at 09:18
  • i did it read up. I'm new to javascript stuff...thanks for the links – Andrew Jul 26 '19 at 01:21

1 Answers1

2

Try below code:

$('#btnView').html(`<i class="fa fa-cart-plus"></i> ${aItems.length} Item(s) in cart`);
user
  • 568
  • 5
  • 19
  • Hi there, I've tried the example you advised. Unfortunately, its still not working. It doesnt recognise the ${aItems.lenght} as a variable or code so its appearing as text. – Andrew Jul 25 '19 at 03:21
  • Make sure that you are enclosing the string passed to html function in back-ticks and not single quotes. – user Jul 25 '19 at 06:22
  • omg Thanks! Its working now. Thank you so much! I've learnt something new :) – Andrew Jul 26 '19 at 01:15
  • oh , I just ticked it. Sorry about that. I'm new to stackoverflow when it comes to my own posts haha. didnt know i had to click that. Take care buddy. – Andrew Jul 29 '19 at 01:06