SxChoc SxChoc - 6 months ago 10
HTML Question

Amend 'text' of element by class name

I'm stuck on something that I think should be dead simple (show's what I know!).

In HTML I've got:

<a class="removeQuantity"> - </a>
<span class="quantity"> 1 </span>
<a onclick="addQuantity('2')"> + </a>


and in my script I've got the function:

function addQuantity(iQuant) {
iQuant = parseInt(iQuant);
$(this).prevAll('.quantity').text(iQuant.toString());
}


So what I'm trying to do is change the value contained the with the class of quantity from 1 to the value passed into the function (2) but nothing seems to be working.

Could someone point me in the right direction please?

Thanks,
C

Answer

The issue is that when you assign an event handler using an on* attribute it does not set the scope to the current element, therefore this refers to the window, not the element which raised the event. To fix this you can pass the element reference directly to the function, like this:

<a onclick="addQuantity(2, this)"> + </a>
function addQuantity(iQuant, el) {
    $(el).prevAll('.quantity').text(iQuant);
}

Note that in the above example I passed an integer directly to the function to avoid having to cast its type.

As a better alternative you could attach your event handlers using unobtrusive JS. Given you tagged the question with jQuery, here's how to do that:

<a class="quantity-amend" data-quantity="2"> + </a>
$('.quantity-amend').click(function(e) {
    e.preventDefault();
    $(this).prevAll('.quantity').text($(this).data('quantity'));
});

I can't use unobtrusive (I think!) as the the section of the page that I'm in gets reloaded when a quantity change is confirmed.

In this case you can use a delegated event handler:

$(document).on('click', '.quantity-amend', function(e) {
    e.preventDefault();
    $(this).prevAll('.quantity').text($(this).data('quantity'));
});