Ajay Kulkarni Ajay Kulkarni - 1 month ago 6
jQuery Question

getting the current status of bootstrap switch in a table

I implemented bootstrap switch and changed the status to

Active
and
Inactive
. I wanted to capture the status of bootstrap switch after toggling in a table. But whenever I try to capture the status, it just shows
On
always. When bootstrap switch is toggled as
Inactive
, status should be captured as
off
, but it isn't happening.

JSFiddle link: https://jsfiddle.net/4erLr6ak/

HTML CODE:


<p class="lead">Multiple prices</p>
<div class="col-md-2">
<input type="text" id="type" name="type" value="" class="login password-field form-control" placeholder="Type of ticket" />
</div>
<div class="col-md-2">
<select class="form-control" id="multi">
<option value="USD">$ USD</option>
<option value="SGD">$ SGD</option>
<option value="EUR">€ EUR</option>
<option value="AUD">$ AUD</option>
<option value="JPY">¥ JPY</option>
<option value="CHN">¥ CHN</option>
<option value="THB">฿ THB</option>
<option value="MYR">RM MYR</option>
</select>
</div>
<div class="col-md-2">
<input type="number" id="ticketprice" name="price" value="" class="login password-field form-control" placeholder="Price of ticket" />
</div>
<div class="col-md-2">
<input type="checkbox" name="my-checkbox" data-on-text="Active" data-off-text="Inactive" checked>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary" id="confirm">Confirm</button>
</div>
<table class="table table-bordered multtable" style="margin-top: 7%;">
<thead>
<tr>
<th>Type of ticket</th>
<th>Price of ticket</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>


Javascript code:


$('#confirm').click(function(e) {
var type = $('#type').val();
var currency = $("#multi option:selected").val();
var mprice = $('#ticketprice').val();
var status = $("[name='my-checkbox']").val();

$('.multtable').append('<tr><td>' + type + '</td><td>' + currency + ' ' + mprice + '</td><td>' + status + '</td></tr>');

/*Clear the values in text boxes after adding to table*/
document.getElementById("type").value = "";
document.getElementById("ticketprice").value = "";

console.log(e);
})
$("[name='my-checkbox']").bootstrapSwitch();

Answer

to check if the checkbox is checked use:

var status = $("[name='my-checkbox']").is(':checked');

instead of:

var status = $("[name='my-checkbox']").val();

you can use the true/false output to set your value accordingly