I don't know why checkValidity() method is not checking if my input is true or false. My program said that checkValidity() is not a function... My program was working but the checkValidity() debug my program.
I tried to make a program that adds data in tables and checks that the input is valid or invalid. Every time you click the process button, data gets added to a table and the reset will erase the input and clears the table.
My professor familiarize me in using the checkValidity() method to ensure the input is valid. I don't know if my program has an error or the browser does not support the checkValidity method?
I use latest version of Chrome. Can Everyone check my code if there's an error and teach me how to implement checkValidity method?
<!DOCTYPE html>
<html lang="en">
<head><title>Sales Person</title>
<!-- Latest compiled CSS -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Optional theme -->
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4">
<form name="myform" onsubmit="validateForm return false;">
<div class="row">
<div class="form-group">
<label for="name">Sales Person:</label>
<input type="text" id = "name" placeholder="Enter Your Name" required><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 1:</label>
<input type="number" id = "product1" placeholder="Enter Product 1"><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 2:</label>
<input type="number" id = "product2" placeholder="Enter Product 2" ><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 3:</label>
<input type="number" id = "product3" placeholder="Enter Product 3" ><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 4:</label>
<input type="number" id = "product4" placeholder="Enter Product 4" ><br/>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="product1">Product 5:</label>
<input type="number" id = "product5" placeholder="Enter Product 5" ><br/>
</div>
</div>
<div class="row">
<div class="col-md-3">
<input type="submit" class="btn btn-default" onclick="Process()" value="Submit">
</div>
<div class="col-md-3">
<input type="reset" class="btn btn-default" onclick="erase()" value="Reset">
</div>
</form>
</div>
<div class="col-md-8" id="sales_table">
</div>
</div>
</div>
<script>
"use strict";
var table = "";
var table_header = "";
var table_body = "";
var table_footer = "";
table_header += "<table class= table table-bordered>";
table_header += "<tr>";
table_header += "<th class='text-center'>Name</th>";
table_header += "<th class='text-center'>Product 1</th>";
table_header += "<th class='text-center'>Product 2</th>";
table_header += "<th class='text-center'>Product 3</th>";
table_header += "<th class='text-center'>Product 4</th>";
table_header += "<th class='text-center'>Product 5</th>";
table_header += "<th class='text-center'>Total Sale Product</th>";
table_header += "<th class='text-center'>Commissions</th>";
table_header += "<tr>";
table_footer += "</table>";
function Process()
{
var sales_table = document.getElementById("sales_table").value;
var name=document.getElementById("name").value;
var product1=parseInt(document.getElementById("product1").value);
var product2=parseInt(document.getElementById("product2").value);
var product3=parseInt(document.getElementById("product3").value);
var product4=parseInt(document.getElementById("product4").value);
var product5=parseInt(document.getElementById("product5").value);
var sales_table = document.getElementById("sales_table");
var total;
var commissions;
if(isValid(name,product1,product2,product3,product4,product5)){
total = product1+product2+product3+product4+product5;
commissions = total * .30;
table_body += "<tr>";
table_body += "<td>"+name+"</td>";
table_body += "<td class='text-center'>" + product1.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product2.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product3.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product4.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + product5.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + total.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + commissions.toFixed(2) + "</td>";
table_body += "</tr>";
table = table_header + table_body + table_footer;
sales_table.innerHTML = table;
}
}
function isValid (name,product1,product2,product3,product4,product5) {
try{
if(name.checkValidity==false){
throw name.validationMessage
}
if(product1.checkValidity==false){
throw product1.validationMessage
}
if(product2.checkValidity==false){
throw product2.validationMessage
}
if(product3.checkValidity==false){
throw product3.validationMessage
}
if(product4.checkValidity==false){
throw product4.validationMessage
}
if(product5.checkValidity==false){
throw product5.validationMessage
}
}
catch(err){
alert(err);
return false;
}
return true;
}
function erase()
{
document.getElementById("name").value="";
document.getElementById("product1").value="";
document.getElementById("product2").value="";
document.getElementById("product3").value="";
document.getElementById("product4").value="";
document.getElementById("product5").value="";
document.getElementById("sales_table").innerHTML="";
}
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
It looks like checkValidity is a method added in the HTML5 specification for input fields: Constraints validation.
You need to keep the reference of the input element, not the value itself:
var name=document.getElementById("name");
var product1=document.getElementById("product1");
var product2=document.getElementById("product2");
var product3=document.getElementById("product3");
var product4=document.getElementById("product4");
var product5=document.getElementById("product5");
Then, you can invoke the checkValidity method later on in your isValid function ;)
if (!name.checkValidity()) {
throw name.validationMessage;
}
// etc.
And you need to adapt the content of your if statement:
total = parseInt(product1.value) + parseInt(product2.value) + parseInt(product3.value) + parseInt(product4.value) + parseInt(product5.value);
commissions = total * .30;
table_body += "<tr>";
table_body += "<td>"+name.value+"</td>";
table_body += "<td class='text-center'>" + parseInt(product1.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product2.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product3.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product4.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + parseInt(product5.value).toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + total.toFixed(2) + "</td>";
table_body += "<td class='text-center'>" + commissions.toFixed(2) + "</td>";
table_body += "</tr>";
checkValidity is a method.
Normaly you call methods with () at the end like> method().
e.g. for product3 product3.checkValidity()==false
Related
I would like to print the contents of a pop up modal window and nothing else on the main page.
I've tried linking a button on the popup window to run the command window.print(); but this just prints a blank page.
I'm assuming that this is because I have not actually called the main content to be printed, but they are in javascript and I simply don't know how to do this.
How can I only print the contents of the pop up window?
The print button is here:
<div id="scheduleModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title_logindetail"></h4>
</div>
<div class="modal-body_logindetail">
</div>
<div id="printarea2">
<div class="modal-footer">
<a class="btn btn-primary" href="javascript:void(0);" onclick="printArea2('printableArea')" >Print</a>
<button type="button" class="btn btn-default" data-dismiss="modal"><?php echo $this->lang->line('cancel'); ?></button>
</div>
</div>
</div>
</div>
</div>
This is what I want to print:
$(document).on('click', '.schedule_modal', function () {
$('.modal-title_logindetail').html("");
$('.modal-title_logindetail').html("<?php echo $this->lang->line('login_details'); ?>");
var base_url = '<?php echo base_url() ?>';
var student_id = '<?php echo $student["id"] ?>';
var student_first_name = '<?php echo $student["firstname"] ?>';
var student_last_name = '<?php echo $student["lastname"] ?>';
$.ajax({
type: "post",
url: base_url + "student/getlogindetail",
data: {'student_id': student_id},
dataType: "json",
success: function (response) {
var data = "";
data += '<div class="col-md-12">';
data += '<div class="table-responsive">';
data += '<p class="lead text text-center" style="font-size:60px;">' + student_first_name + ' ' + student_last_name + '</p>';
data += '<table class="table table-hover">';
data += '<thead>';
data += '<tr>';
data += '<th class="text text-center" style="font-size:40px;">' + "<?php echo $this->lang->line('user_type'); ?>" + '</th>';
data += '<th class="text text-center" style="font-size:40px;">' + "<?php echo $this->lang->line('username'); ?>" + '</th>';
data += '<th class="text text-center" style="font-size:40px;">' + "<?php echo $this->lang->line('password'); ?>" + '</th>';
data += '</tr>';
data += '</thead>';
data += '<tbody>';
$.each(response, function (i, obj) {
data += '<tr>';
data += '<td class="text text-center" style="font-size:30px;"><b>' + firstToUpperCase(obj.role) + '</b></td>';
data += '<input type=hidden name=userid id=userid value=' + obj.id + '>';
data += '<td class="text text-center" style="font-size:30px;">' + obj.username + '</td> ';
data += '<td class="text text-center" style="font-size:30px;">' + obj.password + '</td> ';
data += '</tr>';
});
data += '</tbody>';
data += '</table>';
data += '<b class="lead text text-danger" style="font-size:20px;"> ' + "<?php echo $this->lang->line('login_url'); ?>" + ': ' + base_url + 'site/userlogin</b>';
data += '</div> ';
data += '</div> ';
$('.modal-body_logindetail').html(data);
$("#scheduleModal").modal('show');
}
});
});
function firstToUpperCase(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
</script>
<script>
function printArea2(areaID) {
var printContent = document.getElementById("printarea2");
var WinPrint = window.open('', '', 'width=1100,height=650');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
assuming you want to print div with class $(".modal-title_logindetail")
change your print button to
<a class="btn btn-primary" href="javascript:void(0);" onclick="printArea2();" >Print</a>
try this
function printArea2() {
var contents = document.getElementsByClassName("modal-title_logindetail").innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write('<html><head><title>DIV Contents</title>');
frameDoc.document.write('</head><body>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
return false;
}
I have created a Crud application and have a data() which accepts Json
user = {name: name, age: age, email: email, dob: do}
as input.
When I call the editUser(), the array index is not being taken.
but when I pass the array index statically through the console, the function works as it should.
How should I correct the mistake?
I also have an updateUser() which also faces the same problem.
function read(users) {
var html = "<table border='1|1' class=\"table container\">";
var userhtml = document.getElementById('user');
userhtml.innerHTML = '';
var t = Object.keys(users[0]);
for (var i = 0; i <= 0; i++) {
html += "<tr>";
html += "<th>" + t[0] + "</th>";
html += "<th>" + t[1] + "</th>";
html += "<th>" + t[2] + "</th>";
html += "<th>" + t[3] + "</th>";
html += "<th>" + " Edit" + "</th>";
html += "<th>" + "Delete" + " </th>";
html += "</tr>"
for (var j = i; j < users.length; j++) {
html += "<tr>";
html += "<td>" + users[j].name + "</td>";
html += "<td>" + users[j].age + "</td>";
html += "<td>" + users[j].email + "</td>";
html += "<td>" + users[j].dob + "</td>";
html += "<td>" + "<a href='#' onclick='editUser()'>Edit</a>" + "</td>";
html += "<td>" + "<a href='#' onclick='deleteUsers()'>Delete</a>" + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("user").innerHTML = html;
}
}
function editUser(index) {
debugger;
var userhtml1 = document.getElementById('edit');
userhtml1.innerHTML = '';
for (var i = 0; i < users.length; i++) {
if (i == index) {
userhtml1.innerHTML += ' <div class="user"> Name :<input id="EditName" type="text" value ="' + users[i].name + '"><br />' +
'Age :<input id="EditAge" type="text" value="' + users[i].age + '"> <br /> ' +
'Email :<input id="EditEmail" type="text" value="' + users[i].email + '"> <br /> ' +
'DOB :<input id="EditDOB" type="text" value="' + users[i].dob + '"> <br /> ' +
'<button class="edit" onclick="updateUser()">Update</button>';
} else {
userhtml1.innerHTML += '';
}
}
}
function updateUser(index) {
debugger;
var updatename = document.getElementById('EditName').value;
var updateage = document.getElementById('EditAge').value;
var updateemail = document.getElementById('EditEmail').value;
var updatedob = document.getElementById('EditDOB').value;
if (updatename == '' || updateemail == '' || updateage == '' || updatedob == '') {
alert("Please Fill the Fields!");
}
else {
users[index].name = updatename;
users[index].email = updateemail;
users[index].age = updateage;
users[index].dob = updatedob;
read(users);
}
}
<form action="#" onsubmit="data(name, age, email, dob)">
<!--data(name, age, email, dob)-->
<!--onsubmit="return validate()"-->
<div class="form-group">
<label class="form-text">Name :</label>
<input type="text" id="Name" placeholder="Enter Name" class="form-control" " />
<span id="ErrorName " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Age :</label>
<input type="text " id="Age " placeholder="Enter Age " class="form-control " />
<span id="ErrorAge " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Email :</label>
<input type="text " id="Email " placeholder="Enter Email " class="form-control " />
<span id="ErrorEmail " class="text-danger " />
</div>
<div class="form-group ">
<label class="form-text ">Password :</label>
<input type="password " id="Password " placeholder="Enter Password " class="form-control " />
<span id="ErrorPassword " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Confirm Password :</label>
<input type="password " id="ConfirmPassword " placeholder="Confirm Password " class="form-control " onblur=" " />
<span id="ErrorConfirmPassword " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Date of Birth :</label>
<input type="date " id="DOB " class="form-control " />
<span id="ErrorDOB " class="text-danger "></span>
</div>
<div class="form-group col-lg-12 text-center ">
<input type="submit " id="Submit " class="btn btn-success " />
</div>
</form>
<div class="container " id="user ">
</div>
<br />
<div class="form-group " id="edit ">
</div>
You just forgot to pass the argument. Try this please:
// Change this line
html += "<td>" + "<a href='#' onclick='editUser()'>Edit</a>" + "</td>";
// For this one
html += "<td>" + "<a href='#' onclick='editUser("+j+")'>Edit</a>" + "</td>";
Also, note that your for statement only executes once.. you can just remove it leaving the code inside untouched.
// This executes only once, no matter what.
for (var i = 0; i <= 0; i++) { // <-- remove this
// your code..
} // <-- remove this
// Because it would be the same as just doing:
// your code..
Edit for the updateUser problem:
// For the updateUser problem, note that I added the i variable for the call:
userhtml1.innerHTML += ' <div class="user"> Name :<input id="EditName" type="text" value ="' + users[i].name + '"><br />' +
'Age :<input id="EditAge" type="text" value="' + users[i].age + '"> <br /> ' +
'Email :<input id="EditEmail" type="text" value="' + users[i].email + '"> <br /> ' +
'DOB :<input id="EditDOB" type="text" value="' + users[i].dob + '"> <br /> ' +
'<button class="edit" onclick="updateUser('+i+')">Update</button>';
I'm trying to create a questions with answer or
multiple choice in CodeIgniter, I create the choice using jQuery and now I don't know how to get all value from text input.
can someone help me for this case??
This code:
var choices = [{
id_soal: 'choice1'
}, {
id_soal: 'choice2'
}, {
id_soal: 'choice3'
}];
var html = '';
var i;
for (i = 0; i < choices.length; i++) {
html += '<div class="row">',
html += '<div class="col-xs-8 col-md-4>',
html += '<div class="input-group">',
html += '<span class="input-group-addon" style="background:green"><i class="fa fa-question-circle"></i> Soal' + (i + 1) + '</span>',
html += '<input type="text" name="Question' + i + '" id="Question' + i + '" class="Question form-control" placeholder="Question" required>',
html += '</div></div></div></br>',
html += '<div class="row">',
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon">A</span>',
html += '<input type="text" name="A_jawaban' + i + '" id="A_jawaban' + i + '" class="form-control A_jawaban" placeholder="Result" required>',
html += '</div></div>'
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> B</span>',
html += '<input type="text" name="B_jawaban' + i + '" id="B_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div>',
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> C</span>',
html += '<input type="text" name="C_jawaban' + i + '" id="C_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div></div><br>';
html += '<div class="row">',
html += '<div class="col-xs-4 col-md-6">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> D</span>',
html += '<input type="text" name="D_jawaban' + i + '" id="D_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div>'
html += '<div class="col-xs-4 col-md-6">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> E</span>',
html += '<input type="text" name="E_jawaban' + i + '" id="E_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div></div><br>';
}
$('.judul').html(html);
$('#tambah').click(function(event) {
console.log('THIS CHOICES',choices)
var results = $('.Question').serializeArray();
console.log('FOR QUESTIONS',results)
var resultsAnswearA = $('.A_jawaban').serializeArray();
console.log('FOR QUESTIONS',resultsAnswearA)
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div name="judul" class="judul"></div>
<button id="tambah" name="tambah" class="btn btn-warning"><i class="icon-pencil5"></i> Tambah</button>
UPDATE
wow sorry for my question above, I forgot and just realized I got the answer to use query selector. just check the code
Try:
var allInputsValue = {};
$(".judul input").each(function(){
//Add each input value to all inputs
allInputsValue[allInputsValue.length] = {
"name":$(this).attr("name"),
"value":$(this).val()
};
});
console.log(allInputsValue);
I have a problem.
here is my php & HTML:
<?php
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$sub_lapangan."',1,$row->IDLapangan);");
}
?>
<HTML><BODY>
<div class="row">
<div class="form-group" id="sub_lapangan">
<div class="col-lg-3"><label>Nama Sub-Lapangan :</label></div>
<div class="col-lg-2">
<input type="text" name="sub_lapangan" class="form-control" required>
</div>
<div class="col-lg-1">
<a onclick="tambahSubBaru()" class ="btn btn-info"> <i class="fa fa-plus"></i></a>
</div>
</div>
</div>
<div id="sembunyisub">
</div>
</BODY></HTML>
Here is my script:
var count = 0;
function tambahSubBaru() {
count += 1;
if (count > 15) {
alert("Maksimal Untuk Tambah Sub Lapangan adalah 15 Sub Lapangan");
}
else {
$('#sembunyisub').append(
'<div class="row" id="barisbarusub' + count + '">'
+ '<div class="form-group">'
+ '<div class="col-lg-3">'
+ '</div>'
+ '<div class="col-lg-2">'
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan" required>'
+ '</div>'
+ '<div class="col-lg-1">'
+ '<a class ="btn btn-warning" onclick="hapusSub(' + count + ')"> <i class="fa fa-trash"></i></a>'
+ '</div>'
+ '</div>'
+ '</div>'
);
}
}
function hapusSub(row) {
$('#barisbarusub' + row).remove();
}
Here is the pic:
So the scenario is, when i click the "plus" button, it will show up the second textbox. I want to insert them into database. but when i try to insert, the SECOND textbox is succedded to insert in database. but the FIRST textbox doesn't insert to database.
How can i insert the FIRST textbox?
to show up the second textbox, i use .append in javascript.
help me please. I aprreciated the answer. many thank you. :)
You have to loop through your fields in PHP. Therefore you have to create an Array-input-element with [] after the name.
HTML:
<input type="text" name="sub_lapangan[]" class="form-control" required> <!-- Add [] to your field name for creating an Array-->
JS:
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan[]" required>' //The same in you dynamic input field
PHP: Loop through you fields (Array)
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$fields = $_POST['sub_lapangan']; //Your Array
foreach($fields as $field => $value) {
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$value."',1,$row->IDLapangan);");
}
}
Try this:
'INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES("'.$sub_lapangan.'","1","'.$row->IDLapangan.'")'
I have an app with 3 buttons, the 3 buttons make an AJAX call to retrieve some data and redraw a table with the data. However when clicked the button should be kept highlighted so the user knows which data they are viewing.
This is the JS code that calls the Web API method:
iniciativasEstrategicas.GetVistaActividades = function (filtro) {
var idObjetivoValue = sessionStorage.idObjetivoValue;
$('#tab_vista1').html('<br><br><br><img class="loadImage" src="Images/loader.gif" />');
$.ajax({
url: 'IniciativasEstrategicasWebPart/GetVistaActividades',
type: 'POST',
data: {
idObjetivo: idObjetivoValue,
filtro: filtro
},
success: function (data) {
drawVistaActividades(data);
},
error: function (data) {
showErrorMessage(data);
}
});
}
This is the method that draws the data:
function drawVistaActividades(data) {
resetBreadCrumb();
var html = "";
for (var i = 0; i < data.length; i++) {
html += template.rowVistaActividades
.replace("{0}", data[i].nombreActividad)
.replace("{1}", data[i].iniciativaName)
.replace("{2}", data[i].fechaVencimiento)
.replace("{3}", data[i].fechaRealTerminacion)
.replace("{4}", data[i].responsables);
}
$("#tab_vistaActividades").html("<br>" + "<br>" + template.tableVistaActividades.replace("{0}", html));
}
This is the table template that I use to draw the data, and the buttons are there
tableVistaActividades: "<div>" +
"<div>" +
"<div class=\"btn-group\" role=\"group\" aria-label=\"Basic example\">" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('A tiempo')\">A tiempo</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Atrasadas')\">Atrasadas</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Pendientes')\">Pendientes</button>" +
"</div>" +
"</div>" +
"<table class='table'>" +
"<thead>" +
"<tr>" +
"<th>" +
"Actividad" +
"</th>" +
"<th>" +
"Iniciativa" +
"</th>" +
"<th>" +
"Fecha propuesta" +
"</th>" +
"<th>" +
"Fecha real terminación" +
"</th>" +
"<th>" +
"Responsables" +
"</th>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"{0}" +
"</tbody>" +
"</table>" +"<div>",
and the row template
rowVistaActividades: "<tr>" +
"<td>" +
"{0}" +
"</td>" +
"<td>" +
"{1}" +
"</td>" +
"<td>" +
"{2}" +
"</td>" +
"<td>" +
"{3}" +
"</td>" +
"<td>" +
"{4}" +
"</td>" +
"</tr>",
As you can see in this page.
We are using the same Bootstrap button code and in that page the button remains highlighted when clicked.
This should solve your problem, basically you need to add "active" to selected option and remove "active" from siblings which was previously selected.
$(".btn-group > .btn").click(function(){
$(this).addClass("active").siblings().removeClass("active");
$(this).addClass("active");
});
As #taTrifynor said in the comment, you should simply use Button groups with input type="radio", read about it. For example:
JSFiddle
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked="checked"/>Button 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"/>Button 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"/>Button 3
</label>
</div>
Or I don't understand what do you want.