Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Toggle attribute's value?

Tags:

jquery

So I'm creating a cost calculator in jQuery and PHP. I use the following snippet to toggle a button, so user will see what is checked.

$("[data-button='5']").click(function(){
        $("[data-button='5'] .status").attr("src" , "hintalaskurikuvat/greenstatus.png");
        $("[data-button='5']").toggleClass("selected");

        });

But however, it won't toggle the image, I know that. Is there a simple way to toggle between hintalaskurikuvat/greenstatus.png and hintalaskurikuvat/redstatus.png as the src for [data-button='5']?


2 Answers

Here is what I did to have it available as an extension of JQuery (just add this to your *.js file):

(function($) {

$.fn.toggleAttr = function(attribute, value) {
/// <summary>
///     Toggles on/off provided attribute for any tag/element 
/// </summary>
/// <param name="attribute" type="object">
///    Name of attribute to add or remove, eg: checked=""
/// </param> 
/// <param name="value" type="object">
///    Value of the attribute to add or remove, eg: ="checked"
/// </param> 
    if($(this).attr(attribute)){
        $(this).removeAttr(attribute,value);
    }
    else{
        $(this).attr(attribute,value);
    } 
};
})(jQuery);

and simple way of using it:

$('.someclass').toggleAttr('checked', 'checked');
like image 75
matendie Avatar answered Jul 03 '26 02:07

matendie


You could do something like this:

var sel = $("[data-button='5']");
sel.find('.status').attr("src", sel.hasClass('selected') ? "greenstatus.png" : "redstatus.png");
like image 45
Steven Hunt Avatar answered Jul 03 '26 03:07

Steven Hunt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!