alert something whenever a checkbox is selected or checked - javascript

I've tried making a function that is triggered by whenever a checkbox inside a table is checked but that didn't work well. I've tried making a function located in a $(document).ready but it didn't also work.
this is my html code
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
this is my function
$(document.ready)(function () {
$("#row input:checked'").each(function(){
$('#select').click(function(){
alert('clicked');
});
});
My main goal is counting the selected checkboxes and not allowing the user to check more than 3. But for now I'm trying to make a function that would recognize whenever a checkbox is selected
});

Your DOM ready should be $(document).ready(function(){...
You shouldn't bind click to each checkbox by iterating through only checked ones
Bind using event delegation, and then check the state on click.
As per your question, your problem is to disallow user to check more than three checkboxes.
You could do that by doing a length of all checked inputs, and then overriding new checks if the length exceeds three:
Demo: http://jsfiddle.net/abhitalks/uERSd/1/
// bind click to all input of type checkbox inside #row via delegation
$("#row").on("click", "input[type='checkbox']", function() {
// check the length i.e. total number of inputs which are currently checked
var tot = $("#row input[type='checkbox']:checked").length;
if (tot > 3) {
// disallow new checks if three are already checked
this.checked = false;
}
});

To recognize whenever checkbox is selected, you can use:
$("#select").change(function() {
if(this.checked) {
alert('clicked');
}});

Try this : Here document.ready syntax is corrected and jquery modified to get total count of checked checkboxes inside td with id='row'
$(document).ready(function(){
$("#row input[type='checkbox']").click(function(){
var count = $("#row input[type='checkbox']:checked").length;
alert("total checked checkbox is : "+count);
});
});

This code will work
$(document).ready(function() {
$("#select").change(function() {
if(this.checked) {
alert('checked');
}});
});

Your HTML
<table class="tableTable">
<tr id="tableTr">
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
<td id='row1'><input type='checkbox' name='helloname' value="helloval" id='select1'> hello1 </td>
<td id='row2'><input type='checkbox' name='helloname' value="helloval" id='select2'> hello2 </td>
<td id='row3'><input type='checkbox' name='helloname' value="helloval" id='select3'> hello3</td>
</tr>
</table>
JQUERY
$(document).ready(function(){
$("#tableTr").on("click", "input[type='checkbox']", function() {
var count = $("#tableTr input[type='checkbox']:checked").length;
if (count > 3) {
this.checked = false;
alert("only 3 items can be checked");
}
});
});

Related

How to ensure at least one checkbox is selected from the table on button click using jQuery in MVC?

<tbody>
#if (ViewBag.fileVMList != null)
{
#foreach (var item in ViewBag.fileVMList)
{
<tr>
<td> #item.fileName </td>
<td><input type="checkbox" class="chkCheckBoxId" value="#item.id" name="id"/> </td>
</tr>
}
}
</tbody>
<script>
//trigger on button click
var ConfirmRestore = function()
{
if ($('.chkCheckBoxId').prop('checked') == true) {
$('#myModal').modal('show');
}
else
alert("Please select record to restore!");
}
</script>
The above code represents the portion of a table with 5 records and each record has a checkbox in Index.cshtml file (MVC). There is one master button and on the button click, the ID of the selected checkbox will be passed to the controller form the view for DELETION. If it is null, an error message should be displayed and empty values should NOT be passed! I want to ensure that at least one checkbox is selected on the button click event.
This is what I have tried so far but it is only checking for the first checkbox ONLY, how to check for all the checkbox?
Please use following script on button click event to check atleast on checkbox checked.
$("#btnSubmit_Id").click(function () {
var checked_checkboxes = $("#tblElement_Id input[type=checkbox]:checked");
if (checked_checkboxes.length == 0) {
alert("Please select record to restore!");
}
$('#myModal').modal('show');
});
</script>

loop using JavaScript based in html id

if i have a table with an infinite which has an input type checkbox. Each check box is marked with an id eg. #det1, #det2 , #det3 how would i write my JS loop to check if that certain checkbox is checked to perform the function on it, without writing out each id ,because this id is also incremented based on the product uploader so for each product uploaded it will just add 1 to the id,at the end i could sit with allot of id's.
javascript that works adding the id manually:
$('#details1, #details2').on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});
So that works but because have so many id's based on my tr's i would just like to do a loop and check if that id exist (it could be id = #details999) and if it does do function on.change.
(for each product ill upload the id adds 1 to it eg. product1 = #details1 , product2 = #details2, etc...)
There might be a better way of implementing the idea but as im newbie i am open to any suggestions.
What i tried:
for (var i = 0; i < ?; i++) {
$('#details'+ i).on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
})
}
i know ? means nothing but i realized i cant set a limit to that also don't want a infinite loop so i'm kind of stuck.
Add a common class to the select elements and use that to target them
<input type="checkbox" id="details1" class="details-checkbox">
<input type="checkbox" id="details2" class="details-checkbox">
<input type="checkbox" id="details3" class="details-checkbox">
and then use
$('.details-checkbox').on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});
I would use event delegation:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
$('table').on('change', 'input[type="checkbox"]', function(e) {
var row = $(this).closest('tr').next('tr');
$(row).toggle($(this).prop('checked'));
})
tr.hidden { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr><td>1</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 1</td></tr>
<tr><td>2</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 2</td></tr>
<tr><td>3</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 3</td></tr>
<tr><td>4</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 4</td></tr>
</tbody>
</table>
$('input:checkbox[id*=details ]').on('change',function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});

Jquery click function using a dynamic value

I have a list of checkboxes which generate tables when checked. Each table has an All checkbox which when clicked selects all the options of the table. The all checkboxes are all referred to by the same class but have different IDs depending on the table. I am trying to write a code to get the ID of the generated table and use this ID in my select_all function which would allow the ALL checkbox to only affect its respective table's options.
What I currently have
ALL Checkbox
<div class="Row">
<div id="topRow">
<input type="checkbox" name="tbl" class="tblall" id="all<?php echo $tables_index;?>" value="" />
<p >ALL</p>
</div>
ALL Function
$(function () {
$(document).on("click", (".tblall"), function () {
var className = $("input:checkbox[name='tbl2']").attr('class');
if (this.checked) {
// Iterate each checkbox
$('.' + className).each(function () {
this.checked = true;
});
} else {
$('.' + className).each(function () {
this.checked = false;
});
}
});
});
What I have tried
I tried to store the ALL checkbox ID in a variable and the use this variable to refer to the checkbox in my function like below:
some function (){
var allID = $(".tball").attr('id');
store allID;
}
$(function () {
var allID = window.sessionStorage.getItem("allID");
$(document).on("click", ("#"+ allID), function () {
This was not successful as it didn't even select all options of any table.
I also thought if writing a function that fetches the ID and calling the function when the DOM is loaded :
function all_Id() {
var allID;
if ($("input:checkbox[name='tbl[]']:checked")) {
allID = $("input:checkbox[name='tbl']").attr('id');
}
return allID;
}
$(document).ready(function () {
all_Id();
});
$(document).ajaxComplete(function () {
all_Id();
});
What's the best way to achieve what I want?
I guess you need something like this:
$(".tblall").on('change', function () {
$(this).closest('table').find(':checkbox').prop('checked', this.checked);
});
instead of click apply the change event.
when change event happens traverse up to the parent table (as you mentioned).
find the checkboxes with :checkbox selector.
then apply the property checked if .tball is checked.
this.checked returns boolean as true if checked false if unchecked.
A short example is here:
$(".tblall").on('change', function() {
$(this).closest('table').find(':checkbox').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td><input type='checkbox' class='tblall' />.tblall</td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
</table>
Try this : find all tbl2 checkboxes inside div and make check / uncheck
$(function () {
$(document).on("change", ".tblall", function () {
$(this).closest(".Row").find("input:checkbox[name='tbl2']").prop('checked',$(this).is(':checked'));
});
});
You can try using JQuery's parent-child selector.
So, if you give each table a unique id, then you can select all checkboxes of a certain class like this:
$("#table1 > .checkbox-class").each(function () {
this.checked = true;
});
Hope that helps.
You could try using jQuery Closest function.
If you have a table enclosing the checkboxes, the you can use closest to find the "nearest" table tag to your checkbox.
Once you have the handle to the table, everything else would seem easy, I suppose.

Get elements from Parent Row of checked checkboxes

I have the following row in a table.
<tr class="data_rows" ng-repeat='d in t2'>
<td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td>
<td class="tds"><a href='perf?id={{d.ID}}'>{{d.ID}}</a></td>
<td class="tds">{{d.HostOS}}</td>
<td class="tds">{{d.BuildID}}</td>
<td class="tds">{{d.Description}}</td>
<td class="tds">{{d.User}}</td>
<td class="tds">{{d.StartTime}}</td>
<td class="tds">{{d.UniqueMeasure}}</td>
<td class="tds">{{d.TotalMeasure}}</td>
</tr>
Here's the HTML for button that will invoke the function to collect the ids from checked check boxes and store them.
<div id='compButtonDiv' align='center' style="display: none;">
<input id='cButton' type='button' value='compare selections' onclick='submitSelection()' style= "margin :0 auto" disabled>
</div>
The data is in t2 which consists of an array of length 15-20.
What i want to do is get the value of ID i.e, {{d.ID}} of the 2 checked check boxes so that i can store them in a variable and pass them as query parameters to URL using `location.href = url?param1&param2'
Here's the javascript:
function keepCount(obj){
debugger;
//var count=0;
if(obj.checked){
obj.classList.add("checked");
}else{
obj.classList.remove("checked");
}
var count = document.getElementsByClassName("checked").length;
var cBtn = document.getElementById('cButton');
//alert(count);
if(count == 2){
cBtn.disabled = false;
}
else if(count < 2){
cBtn.disabled= true;
}
else{
cBtn.disabled= true;
alert("Please Select two sets for comparison. You have selected: " + count);
}
}
function submitSelection(){
// what should be the code here??
location.href= "existingURL?a&b";
}
Now can someone please tell me how to get the id's?? I need to extract ID from the checkboxes that are checked(on the click of button whose code i've mentioned above'.
Thanks.
-Ely
Firstly when we use angularjs we tend to depend less and less on DOM manipulation.
For this reason, what you can do is to attach ngModel to the checkbox.
Like:
<input class='checkBoxInput' ng-model='d.isChecked' type='checkbox' onchange='keepCount(this)'>
What this does is, it attaches the variable (in your case the property of item in the list) to the check box. If it is checked it is true, if unchecked, initially it will be undefined, later on checking and then unchecking it will be false.
Now, when you submit, just loop over the original list in the function and check the values of d.isChecked (true/falsy values). Then you can add the necessary items in a separate list for submission.
The only concern is when checking the list on submission , check if(d.isChecked), so that it ignores the falsy values(false/undefined).

Get a table cell value where I have a checkbox checked

I´m new in JQuery and I have a trouble. I want to read a specific cell value from a table row where I have a checkbox. I have an event that handles the checkbox checked event. This is my code:
$("#businesses input:checkbox").change(function (
var $this = $(this);
if ($this.is(":checked")) {
//Here I want to read a value from a column in a row where is the checkbox
} else {
//Here I want to read a value from a column in a row where is the checkbox
}
});
I have a table called "businesses" and it has this format
<table id="businesses">
<tr>
<th>Select Value</th>
<th>Value</th>
</tr>
<tr>
<td><input type="checkbox" class="selectedService" title="Seleccionar" /></td>
<td>125</td>
</tr>
<tr>
<td><input type="checkbox" class="selectedService" title="Seleccionar" /></td>
<td>126</td>
</tr>
</table>
What I want to do, is that when I select a checkbox, get the value field of its row.
If I press the first checkbox I want to get 125.
Thanks!!!
Starting from your checkbox (this in the event handler function), you need to go up to the containing <td> element, across to the next <td> element, then get its text:
$('#businesses input:checkbox').change(function(e) {
if(this.checked) {
var value = parseInt($(this).closest('td').next('td').text(), 10);
// above will convert it from a string to an integer
}
else {
// same as above? Seems redundant
}
});
Use siblings() of the parent:
$this.closest('td').siblings().text();
If this is not the only other <td> siblings() would return all of the rest so use appropriate selector to filter them.
You could access it with:
$this.parent().next().text();
Try this...
$("#businesses input:checkbox").on ('change', function (e)
if ($(this).is(":checked")) {
$( e.target ).closest("td").text();
} else {
//Here I want to read a value from a column in a row where is the checkbox
}
});
Greetings.

Categories