Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch value for clicked button from group of buttons in jQuery

I'm trying to make a website using asp.net mvc 4 & jQuery 1.9.1 where I want to insert boolean values (Y or N) in textbox for the corresponding button pressed. It works for a single button, but it's not working for group of buttons. Here are my codes,

$(document).ready(function () {
    var isClicked = 0;
    $('.btn').click(function () {
        if (isClicked == 0) {
            isClicked = 1;
            $(this).toggleClass('color-blue color-green');
            $(this).next('.assignCheck').val('Y');
        } else if (isClicked == 1) {
            isClicked = 0;
            $(this).toggleClass('color-green color-blue');
            $(this).next('.assignCheck').val('N');
        }
    });
});

JSFiddle Demo

How can I make the buttons work individually?

like image 668
Shihan Khan Avatar asked Dec 10 '25 20:12

Shihan Khan


1 Answers

uYou can use data- attributes with button to store if its click value is 1 or zero and use that value to update the respective textbox

Live Demo

Html

<button class="btn color-blue" data-clicked="0">ONE</button>
<input type="text" class="assignCheck" /><br><br>
<button class="btn color-blue" data-clicked="0">TWO</button>
<input type="text" class="assignCheck" /><br><br>
<button class="btn color-blue" data-clicked="0">THREE</button>
<input type="text" class="assignCheck" />

JQuery

$(document).ready(function () {        
    $('.btn').click(function () {
        var isClicked = $(this).data("clicked");        
        if (isClicked == 0) {
            isClicked = 1;
            $(this).toggleClass('color-blue color-green');
            $(this).next('.assignCheck').val('Y');
        } else if (isClicked == 1) {
            isClicked = 0;
            $(this).toggleClass('color-green color-blue');
            $(this).next('.assignCheck').val('N');
        }
        $(this).data("clicked", isClicked);
    });
})
like image 73
Adil Avatar answered Dec 13 '25 10:12

Adil



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!