Dan
Dan

Reputation: 1000

jQuery toggle classes between buttons in Bootstrap Button Group; set one and unset the other where other is not set

I have a two button Bootstrap button group (True/False) buttons and want to unset/unclick one when the other is clicked - when True is clicked, True is active with a class; and False becomes unclicked and set with another class.

Here is the HTML page I am testing with:

<html>
    <head>
        <title>Button Test</title>
        <link href="public/css/bootstrap/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
        <script src="public/js/bootstrap/bootstrap.js" type="text/javascript"></script> 
        <style>
            .squareUpButton {
                border-radius:0px;
            }
            .resolveButtonOff {
                background-color: #FFFFFF;
                border: 1px solid #00953a;
                color: #00953a !important;
                font-size: 8pt;
                padding: 7px;
            }
            .resolveButtonOn {
                background-color: #00953a;
                border: 1px solid #00953a;
                color: #FFFFFF !important;
                font-size: 8pt;
                padding: 7px;
            }
            .trueFalseButtonOff {
                background-color: #FFFFFF;
                border: 1px solid #005980;
                color: #005980 !important;
                font-size: 8pt;
                padding: 7px;
            }
            .trueFalseButtonOn {
                background-color: #005980;
                border: 1px solid #005980;
                color: #FFFFFF !important;
                font-size: 8pt;
                padding: 7px;
            }
            .remedyButtonR:not (:last-child) {
                border-right: none;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-sm-2">
                    <div class="btn-group" style="width:100%">
                        <button id="house_Rules_True_Button" type="button" class="btn squareUpButton trueFalseButtonOff" style="width:50%;">TRUE</button>
                        <button id="house_Rules_False_Button" type="button" class="btn squareUpButton trueFalseButtonOff" style="width:50%;">FALSE</button>
                    </div>
                    <div class="btn-group" style="width:100%">
                        <button id="house_Rules_Resolved_Button" type="button" class="btn squareUpButton resolveButtonOff" style="width:99.5%;">RESOLVED</button>
                    </div>
                    <input name="house_Rules">
                </div>
            </div>
        </div>
    </body>
    <script>
        $("button[id$='_Resolved_Button'").on('click', function () {
            // Get the field value...
            var fieldName = $(this).prop("id");
            console.log("button_Resolved_Button - fieldName = " + fieldName);
            var fieldIndex = fieldName.indexOf("_Resolved");
            console.log("button_Resolved_Button - fieldIndex = " + fieldIndex);
            fieldName = fieldName.substring(0, fieldIndex);
            console.log("button_Resolved_Button - fieldName = " + fieldName);
            var fieldID = "input[name='" + fieldName + "']";
            console.log("button_Resolved_Button - fieldID = " + fieldID);
            var currentValue = $(fieldID).val();
            console.log("button_Resolved_Button - currentValue = " + currentValue);

            if(currentValue == "resolved") {
                // Set to nothing...
                $(fieldID).val("");
            } else {
                // Set the field...
                $(fieldID).val("resolved");
            }

            $(this).toggleClass("resolveButtonOff resolveButtonOn");
        });

        $("button[id$='_True_Button'").on('click', function () {
            // Get the field value...
            var fieldName = $(this).prop("id");         
            var fieldIndex = fieldName.indexOf("_True");
            fieldName = fieldName.substring(0, fieldIndex);
            console.log("button_True_Button - fieldName = " + fieldName);
            var fieldID = "input[name='" + fieldName + "']";
            console.log("button_True_Button - fieldID = " + fieldID);
            var currentValue = $(fieldID).val();
            console.log("button_True_Button - currentValue = " + currentValue);

            // Need to check the value...
            if(currentValue == "" || currentValue == null) {
                // Just toggle...
                $(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
                // Set the field...
                $(fieldID).val("true");
            }
            if(currentValue == "true") {
                // Just toggle...
                $(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
                // Set to nothing...
                $(fieldID).val("");
            }
            if(currentValue == "false") {
                // Unclick/unset the False button...
                var buttonID = $(this).prop("id");
                var otherButtonID = buttonID.replace("True", "False");
                console.log("button_True_Button - otherButtonID = " + otherButtonID);
                $(otherButtonID).removeClass("trueFalseButtonOn");
                $(otherButtonID).addClass("trueFalseButtonOff");
                //$(buttonID).click();
                // Set the field...
                $(fieldID).val("true");
                // Toggle the class...
                $(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
            }
            if(currentValue == "resolved") {
                // Do nothing?
            }
        });

        $("button[id$='_False_Button'").on('click', function () {
            // Get the field value...
            var fieldName = $(this).prop("id");
            var fieldIndex = fieldName.indexOf("_False");
            fieldName = fieldName.substring(0, fieldIndex);
            console.log("button_True_Button - fieldName = " + fieldName);
            var fieldID = "input[name='" + fieldName + "']";
            console.log("button_False_Button - fieldID = " + fieldID);
            var currentValue = $(fieldID).val();
            console.log("button_False_Button - currentValue = " + currentValue);

            // Need to check the value...
            if(currentValue == "" || currentValue == null) {
                // Just toggle...
                $(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
                // Set the field...
                $(fieldID).val("false");
            }
            if(currentValue == "true") {
                // Unclick/unset the False button...
                var buttonID = $(this).prop("id");
                buttonID = buttonID.replace("True", "False");
                var otherButtonID = buttonID.replace("False", "True");
                console.log("button_True_Button - otherButtonID = " + otherButtonID);
                $(otherButtonID).removeClass("trueFalseButtonOn");
                $(otherButtonID).addClass("trueFalseButtonOff");
                // Set the field...
                $(fieldID).val("false");
                // Toggle the class...
                $(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
            }
            if(currentValue == "false") {
                // Just toggle...
                $(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
                // Set to nothing...
                $(fieldID).val("");
            }
            if(currentValue == "resolved") {
                // Do nothing?
            }
        });     
    </script>
</html>

I created a JSFiddle:

https://jsfiddle.net/dzeller44/k27r39xL/

I found a few posts, but they did not help me solve the problem:

Javascript / JQuery Toggle Active Class between 2 buttons on a button group

Toggling class in group of buttons

Any help would be great.

Upvotes: 0

Views: 1193

Answers (2)

mathius1
mathius1

Reputation: 1391

You are toggling 2 classes that are not there initially so when you click one button it will apply the toggle on both. I replaced your toggle method with this:

$("#toggleHolder button").removeClass("trueFalseButtonOn trueFalseButtonOff");
  $(this).addClass("trueFalseButtonOn");
  currentValue = $(this).text();
  $(this).siblings("button").addClass("trueFalseButtonOff");

JSFiddle

I also added an ID 'toggleHolder' to your outer div holding the buttons so we can call the buttons easier. The code removes the classes 'trueFalseButtonOn' and 'trueFalseButtonOff' from BOTH buttons. Then adds the ON class to the clicked button and the OFF class to the clicked buttons siblings

Upvotes: 0

Nimitt Shah
Nimitt Shah

Reputation: 4597

You are doing unnecessary code.. Just add

$(".trueFalseButtonOn").removeClass("trueFalseButtonOn");
$(this).addClass("trueFalseButtonOn");

lines to your both true and false button click event.

In below snippet, I have added new code and commented your code.

$("button[id$='_Resolved_Button'").on('click', function () {
			// Get the field value...
			var fieldName = $(this).prop("id");
			console.log("button_Resolved_Button - fieldName = " + fieldName);
			var fieldIndex = fieldName.indexOf("_Resolved");
			console.log("button_Resolved_Button - fieldIndex = " + fieldIndex);
			fieldName = fieldName.substring(0, fieldIndex);
			console.log("button_Resolved_Button - fieldName = " + fieldName);
			var fieldID = "input[name='" + fieldName + "']";
			console.log("button_Resolved_Button - fieldID = " + fieldID);
			var currentValue = $(fieldID).val();
			console.log("button_Resolved_Button - currentValue = " + currentValue);

			if(currentValue == "resolved") {
				// Set to nothing...
				$(fieldID).val("");
			} else {
				// Set the field...
				$(fieldID).val("resolved");
			}
			
			$(this).toggleClass("resolveButtonOff resolveButtonOn");
		});
	
		$("button[id$='_True_Button'").on('click', function () {
			// Get the field value...
			var fieldName = $(this).prop("id");			
			var fieldIndex = fieldName.indexOf("_True");
			fieldName = fieldName.substring(0, fieldIndex);
			console.log("button_True_Button - fieldName = " + fieldName);
			var fieldID = "input[name='" + fieldName + "']";
			console.log("button_True_Button - fieldID = " + fieldID);
			var currentValue = $(fieldID).val();
			console.log("button_True_Button - currentValue = " + currentValue);
			
      $(".trueFalseButtonOn").removeClass("trueFalseButtonOn");
      $(this).addClass("trueFalseButtonOn");
				$(fieldID).val("true");
			// Need to check the value...
			/*if(currentValue == "" || currentValue == null) {
				// Just toggle...
				$(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
				// Set the field...
				$(fieldID).val("true");
			}
      
			if(currentValue == "true") {
				// Just toggle...
				$(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
				// Set to nothing...
				$(fieldID).val("");
			}
			if(currentValue == "false") {
				// Unclick/unset the False button...
				var buttonID = $(this).prop("id");
				var otherButtonID = buttonID.replace("True", "False");
				console.log("button_True_Button - otherButtonID = " + otherButtonID);
				$(otherButtonID).removeClass("trueFalseButtonOn");
				$(otherButtonID).addClass("trueFalseButtonOff");
				//$(buttonID).click();
				// Set the field...
				$(fieldID).val("true");
				// Toggle the class...
				$(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
			}
			if(currentValue == "resolved") {
				// Do nothing?
			}*/
		});
	
		$("button[id$='_False_Button'").on('click', function () {
			// Get the field value...
			var fieldName = $(this).prop("id");
			var fieldIndex = fieldName.indexOf("_False");
			fieldName = fieldName.substring(0, fieldIndex);
			console.log("button_True_Button - fieldName = " + fieldName);
			var fieldID = "input[name='" + fieldName + "']";
			console.log("button_False_Button - fieldID = " + fieldID);
			var currentValue = $(fieldID).val();
			console.log("button_False_Button - currentValue = " + currentValue);
			
      $(".trueFalseButtonOn").removeClass("trueFalseButtonOn");
      $(this).addClass("trueFalseButtonOn");
				$(fieldID).val("false");
			// Need to check the value...
			/*if(currentValue == "" || currentValue == null) {
				// Just toggle...
				$(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
				// Set the field...
				$(fieldID).val("false");
			}
			if(currentValue == "true") {
				// Unclick/unset the False button...
				var buttonID = $(this).prop("id");
				buttonID = buttonID.replace("True", "False");
				var otherButtonID = buttonID.replace("False", "True");
				console.log("button_True_Button - otherButtonID = " + otherButtonID);
				$(otherButtonID).removeClass("trueFalseButtonOn");
				$(otherButtonID).addClass("trueFalseButtonOff");
				// Set the field...
				$(fieldID).val("false");
				// Toggle the class...
				$(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
			}
			if(currentValue == "false") {
				// Just toggle...
				$(this).toggleClass("trueFalseButtonOff trueFalseButtonOn");
				// Set to nothing...
				$(fieldID).val("");
			}
			if(currentValue == "resolved") {
				// Do nothing?
			}*/
		});
.squareUpButton {
				border-radius:0px;
			}
			.resolveButtonOff {
				background-color: #FFFFFF;
				border: 1px solid #00953a;
				color: #00953a !important;
				font-size: 8pt;
				padding: 7px;
			}
			.resolveButtonOn {
				background-color: #00953a;
				border: 1px solid #00953a;
				color: #FFFFFF !important;
				font-size: 8pt;
				padding: 7px;
			}
			.trueFalseButtonOff {
				background-color: #FFFFFF;
				border: 1px solid #005980;
				color: #005980 !important;
				font-size: 8pt;
				padding: 7px;
			}
			.trueFalseButtonOn {
				background-color: #005980;
				border: 1px solid #005980;
				color: #FFFFFF !important;
				font-size: 8pt;
				padding: 7px;
			}
			.remedyButtonR:not (:last-child) {
				border-right: none;
			}
<html>
	<head>
		<title>Button Test</title>
		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
		<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
		<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
		<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
	</head>
	<body>
		<div class="container">
			<div class="row">
				<div class="col-sm-2">
					<div class="btn-group" style="width:100%">
						<button id="house_Rules_True_Button" type="button" class="btn squareUpButton trueFalseButtonOff" style="width:50%;">TRUE</button>
						<button id="house_Rules_False_Button" type="button" class="btn squareUpButton trueFalseButtonOff" style="width:50%;">FALSE</button>
					</div>
					<div class="btn-group" style="width:100%">
						<button id="house_Rules_Resolved_Button" type="button" class="btn squareUpButton resolveButtonOff" style="width:99.5%;">RESOLVED</button>
					</div>
					<input name="house_Rules">
				</div>
			</div>
		</div>
	</body>
</html>

You can also test it on fiddle. https://jsfiddle.net/nimittshah/k27r39xL/7/

Happy coding :)

Upvotes: 1

Related Questions