CheckBoxList Items using JavaScript - javascript

I have a checkoxlist with a couple of items and an all option. The user can select all and I want this to check off all the options and if they uncheck all it will uncheck all options.
I have accomplished this with the following code.
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
alert(chkBoxCount[0].checked);
for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = chkBoxCount[0].checked //state;
}
return false;
}
</script>
cblAffiliation.Attributes.Add("onclick", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")
The issue is that if I select any of the boxes it loops through and then sets them to whatever the all option is. I am having trouble figuring out the best way to get around this.
I want to avoid using a checkbox next to the checkboxlist, then I have to make that line up with the checkboxlist.

Simply check to see if the box clicked was the all option. If it was, then go ahead and change the rest of the boxes. If it isn't, then check all the options to see if they are all checked so you can update the 'All' checkbox.
EDIT
You might want to use onChange, instead of onClick, onClick will probably be called before the value on the given checkbox is changed.
Code not checked, please forgive syntax problems.
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
var clicked = this;
alert(chkBoxCount[0].checked ? 'All is Checked' : 'All is not Checked');
alert(clicked == chkBoxCount[0] ? 'You Clicked All' : 'You Didn't click All');
var AllChecked = true; // Check the all box if all the options are now checked
for(var i = 1;i < chkBoxCount.length; i++)
{
if(clicked == chkBoxCount[0]) { // Was the 'All' checkbox clicked?
chkBoxCount[i].checked = chkBoxCount[0].checked; // Set if so
}
AllChecked &= chkBoxCount[i].checked; // AllChecked is anded with the current box
}
chkBoxCount[0].checked = AllChecked;
return false;
}
</script>
cblAffiliation.Attributes.Add("onchange", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")

I think this code will help you.
<script type="text/javascript">
function check(checkbox)
{
var cbl = document.getElementById('<%=CheckBoxList2.ClientID %>').getElementsByTagName("input");
for(i = 0; i < cbl.length;i++) cbl[i].checked = checkbox.checked;
}
</script>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="check(this)" />
<asp:CheckBoxList ID="CheckBoxList2" runat="server">
<asp:ListItem>C1</asp:ListItem>
<asp:ListItem>C2</asp:ListItem>
</asp:CheckBoxList>

<asp:CheckBox ID="checkAll" runat="server" Text="Select/Unselect" onclick="CheckAll();" />
<asp:CheckBoxList ID="chkTest" runat="server" onclick="ClearAll();">
<asp:ListItem Text="Test 1" Value="0"></asp:ListItem>
<asp:ListItem Text="Test 2" Value="1"></asp:ListItem>
<asp:ListItem Text="Test 3" Value="2"></asp:ListItem>
</asp:CheckBoxList>
<script type="text/javascript">
function CheckAll() {
var intIndex = 0;
var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
for (intIndex = 0; intIndex < rowCount; intIndex++)
{
if (document.getElementById('checkAll').checked == true)
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
document.getElementById("chkTest" + "_" + intIndex).checked = true;
}
}
else
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
document.getElementById("chkTest" + "_" + intIndex).checked = false;
}
}
}
}
function ClearAll(){
var intIndex = 0;
var flag = 0;
var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
for (intIndex = 0; intIndex < rowCount; intIndex++)
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if(document.getElementById("chkTest" + "_" + intIndex).checked == true)
{
flag=1;
}
else
{
flag=0;
break;
}
}
}
if(flag==0)
document.getElementById('checkAll').checked = false;
else
document.getElementById('checkAll').checked = true;
}
</script>

function checkparent(id) {
var parentid = id;
var Control = document.getElementById(parentid).getElementsByTagName("input");
if (parentid.indexOf("List") != -1) {
parentid = parentid.replace("List", "");
}
if (eval(Control).length > 0) {
if (eval(Control)) {
for (var i = 0; i < Control.length; i++) {
checkParent = false;
if (Control[i].checked == true) {
checkChild = true;
}
else {
checkChild = false;
break;
}
}
}
}
if (checkParent == true && document.getElementById(parentid).checked == false) {
document.getElementById(parentid).checked = false;
checkParent = true;
}
else if (checkParent == true && document.getElementById(parentid).checked == true) {
document.getElementById(parentid).checked = true;
checkParent = true;
}
if (checkChild == true && checkParent == false) {
document.getElementById(parentid).checked = true;
checkParent = true;
}
else if (checkChild == false && checkParent == false) {
document.getElementById(parentid).checked = false;
checkParent = true;
}
}
function CheckDynamic(chkid) {
id = chkid.id;
var chk = $("#" + id + ":checked").length;
var child = id + "List";
if (chk != 0) {
$("[id*=" + child + "] input").attr("checked", "checked");
}
else {
$("[id*=" + child + "] input").removeAttr("checked");
}
checkparent(id);
}

Related

javascript add and delete section of html dynamically

I am trying to add and delete sections of HTML on the click of Add or delete button. The first 3 times I click the add button it adds more sections as expected and deletes the section as well when delete is clicked. But the problem is when I delete any row after that the AddMore Rows function doesn't work and no more rows are added.
Here is the code for Adding more rows
var hasHsa3 = false;
var hasHsa4 = false;
var hasHsa5 = false;
function addMoreRows() {
// console.log("A: "+hasHsa3 + " " + hasHsa4 + " " + hasHsa5);
if(!hasHsa3 && !hasHsa4 && !hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(hasHsa3 && !hasHsa4 && !hasHsa5)
{
hsaNum = 4;
hasHsa4 = true;
}
else if(hasHsa3 && hasHsa4 && !hasHsa5)
{
hsaNum = 5;
hasHsa5 = true;
console.log(hsaNum);
$("#addMore_1").attr("disabled", true);
}
else if(!hasHsa3 && hasHsa4 && hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(!hasHsa3 && hasHsa4 && !hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(!hasHsa3 && !hasHsa4 && hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(hasHsa3 && !hasHsa4 && hasHsa5)
{
hsaNum = 4;
hasHsa4 = true;
}
else if(hasHsa3 && hasHsa4 && hasHsa5)
{
$("#addMore_1").attr("disabled", true);
// document.getElementById("addMore_1").disabled = true;
console.log("button is disabled");
}
console.log("B: "+hasHsa3 + " " + hasHsa4 + " " + hasHsa5 + "\n");
hsaBlock ++;
hsaIds.push(hsaNum);
Here is the function for deleting the rows once Delete button is clicked.
function removeRow(removeNum,hsaNum)
{
// Remove from array
var index = hsaIds.indexOf(hsaNum);
if (index > -1) {
hsaIds.splice(index, 1);
if(hsaNum == 3)
{
hasHsa3 = false;
}
else if(hsaNum == 4)
{
hasHsa4 = false;
}
else if(hsaNum == 5)
{
hasHsa5 = false;
}
}
updateHSATable();
$('.hsaBlock'+removeNum).remove();
};
I don't know what your actual code so from what I understood I think you try to do something like below. For adding element I use appendChild() and for deleting element I used removeChild(). hope this helps.
function add(){
var node = document.createElement("LI");
var len = document.querySelectorAll("ul li")
var textnode = document.createTextNode(len.length+1);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
function delete1(){
var len = document.querySelectorAll("ul li");
if(len.length>0){
len[0].parentElement.removeChild(len[len.length-1]);
}
}
<button onclick="add()">Add</button>
<button onclick="delete1()">Delete</button>
<ul id="myList">
<li>1</li>
<li>2</li>
</ul>

JavaScript Function with multi-parameters

how to send this with eval as paramters for javascript function ?
<asp:RadioButton runat="server" id="rd" ClientIDMode="AutoID" onclick='<%# String.Format("OnCheckChange(\"{0}\", \"{1}\");", this, Eval("BookID"))%>' />
this way doesn't work and here my function which always return
Cannot read property 'parentNode' of undefined
function OnCheckChange(rb,idm ) {
//logic for exclusive setting the radio button that was last clicked.
var table = document.getElementById('ListTable');
var radiobtn = table.getElementsByTagName('input');
for (k = 0; k < radiobtn.length; k++)
{
if ((radiobtn[k].type == 'radio') && (rb.id == radiobtn[k].id))
{
radiobtn[k].checked = true;
}
else
radiobtn[k].checked = false;
}
//Book id against the selected radio button.
var hdfield = rb.parentNode.parentNode.cells[0].getElementsByTagName('input');
if (hdfield[0].type == 'hidden')
document.getElementById("hdnField").value = idm;
//enabling /disabling buttons on the basis of checkin /checkout
if (rb.parentNode.parentNode.cells[6].innerHTML == 'Checked In') {
document.getElementById('btnCheckIn').disabled = false;
document.getElementById('btnCheckOut').disabled = true;
}
else if (rb.parentNode.parentNode.cells[6].innerHTML == 'Checked Out') {
document.getElementById('btnCheckOut').disabled = true;
document.getElementById('btnCheckIn').disabled = false;
}
}
if i send this without eval its work

Jquery shift generated button values in circular manner

i am trying to make something fancy like this create button and shift values, so far i have reached till here FIDDLE
$("#submit").click(function() {
var n = $('#txtinp').val();
if ($.isNumeric(n)) {
//alert(n);
var btns = $('#btns');
for (var i = 1; i <= n; i++) {
btns.append('<input type="button" id="b' + i + '" value="' + i + '"/>');
}
} else {
alert("enter a number");
}
$("input[type='button']").click(function(e) {
var idClicked = e.target.id;
//alert($(this).attr("value"));
if (idClicked == 'b1' && $(this).attr("value") == 1) {
$(this).prop('value', n);
var lastBtn = 'b' + n;
for (var i = n; i > 1; i--) {
$('#b' + i).prop('value', i - 1);
}
} else {
var lastBtn = 'b' + n;
for (var i = n; i >= 1; i--) {
if ('b' + i == 'b1' && 'b' + n == n) {
$('#b' + i).prop('value', i);
} else {
$('#b' + i).prop('value', i - 1);
}
}
}
});
});
I am able to shift only once if clicked on very first created button, but the function or event does not work on second and further clicks. I have no prior Jquery experience, what is that i am doing wrong here?
please do not down vote if the question is too stupid.
thanks in advance
Here's one possible solution:
$(document).ready(function() {
$("#submit").click(function() {
var n = $('#txtinp').val();
if ($.isNumeric(n)) {
var btns = $('#btns').empty();
for (var i = 1; i <= n; i++) {
btns.append($('<button>').text(i));
}
} else {
alert("enter a number");
}
$("#btns button").click(function(e) {
var buttons = $('#btns button');
buttons.each(function () {
var currentValue = parseInt($(this).text());
var newValue = currentValue - 1;
if (newValue === 0) {
newValue = buttons.length;
}
$(this).text(newValue);
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtinp" />
<input type="button" id="submit" value="Submit" />
<div id="btns">
</div>

How to detect whether an html input object is a button or not?

I am working on trying to pull the inputs from a form, excluding buttons, but not radio buttons. I am getting my inputs via the .find() method of the form element. I have the inputs, but am unable to restrict them to just inputs other than the submit button or a similar button. I have tried the jquery .is(), .type(), both with no luck any suggestions/ references would be helpful as I have not found anything to help as of yet. Here is the code I am using to pull the forms.
var inputs = formList.find(":input");
if (inputs ? inputs.length > 0 : false)
{
for(j = 0;j < inputs.length; j++)
{
console.log("input: " + inputs[j]);
if (inputs[j].name != "")
{
webForms.push({"inputName": inputs[j].name});
}else if (inputs[j].id != "")
{
webForms.push({"inputName": inputs[j].id});
}
}
}
Like I said, I have tried the .is and .type with no luck. Here is an example of how I was using .is()
var formList = $("form");
var formName = $("form").attr("name");
if (formList != null ? formList.length > 0 : false)
{
if (formList.length < 2)
{
if (formList.attr("name") ? formList.attr("name") != "" : false)
{
//alert("form name is not null");
//alert("form name: " + formList.attr("name"));
var webForms = [];
//alert("formList name: " + formList[i]);
var inputs = formList.find(":input");
if (inputs ? inputs.length > 0 : false)
{
for(j = 0;j < inputs.length; j++)
{
console.log("input: " + inputs[j]);
if (inputs[j].name != "")
{
if(inputs[j].is(":button"))
{
console.log(inputs[j].name + " is a button");
}
webForms.push({"inputName": inputs[j].name});
}else if (inputs[j].id != "")
{
if(inputs[j].is(":button"))
{
console.log(inputs[j].name + " is a button");
}
webForms.push({"inputName": inputs[j].id});
}
}
}
//alert(JSON.stringify(webForms));
jsonForm.forms[jsonForm.forms.length - 1].name = formList.attr("name");
//alert("json form name: " + JSON.stringify(jsonForm));
jsonForm.forms[jsonForm.forms.length - 1].inputs = webForms;
//alert("name: " + jsonForm.forms[jsonForm.forms.length - 1].name);
}
}
Any help here is appreciated.
You can use the following code to get the input elements which aren't buttons or inputs with a type attribute of "submit".
var inputs = formList.find(':input:not(button, [type="submit"])');
Here is a live demonstration.
the problem is inputs[i] returns a dom element reference not a jQuery wrapper object so its does not have the is method you can use
inputs.eq(i).is(':button')
I would recommend to use .each() loop to iterate over the jQuery object than using a loop
var inputs = formList.find(":input");
inputs.each(function () {
var $input = $(this);
console.log("input: " + this);
if (this.name != "") {
if ($input.is(":button")) {
console.log(this.name + " is a button");
}
webForms.push({
"inputName": this.name
});
} else if (this.id != "") {
if ($input.is(":button")) {
console.log(this.name + " is a button");
}
webForms.push({
"inputName": this.id
});
}
})
This could even be simplified to
var inputs = formList.find(":input");
inputs.each(function () {
var $input = $(this);
console.log("input: " + this);
var name = this.name || this.id;
if (name != "") {
if ($input.is(":button")) {
console.log(name + " is a button");
}
webForms.push({
"inputName": name
});
}
})

How to submit form only one check box is selected using java script

on edit button click a want to submit form only if one check box checked,don't submit when 0 or more than 2 check box checked
my below code is not working
$("#editbtn_id").click(function () {
var cnt = 0;
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
});
if (ischecked) {
checkbox_value += $(this).val();
cnt = cnt + 1;
if (cnt == 0 || cnt > 1) {
alert(cnt);
alert("Please select one Test case");
return false;
}
}
return false;
});
HTML
<form action="/editSingletest/{{ testcase.id }}" method="post" onsubmit="return" >
<input type="checkbox"/>
</form>
You can achieve this by following code
$("#editbtn_id").click(function(){
var cnt=0;
var checkbox_checked_count = 0;
var form_submit = false;
$(":checkbox").each(function () {
if($(this).is(":checked")) {
checkbox_checked_count++
}
});
if(checkbox_checked_count == 1) {
form_submit = true;
}
else if(checkbox_checked_count > 1) {
alert("Please select one Test case");
}
alert(form_submit)
$("form").submit();
});
Check working example here in this fiddle
Your counter is in the wrong loop, should be something like this:
$("#editbtn_id").click(function(){
var cnt=0;
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked){
checkbox_value += $(this).val();
cnt=cnt + 1 ;
}
});
if(cnt==0 || cnt > 1){ ... }
});
try this
$("#editbtn_id").click(function (e) {
if($('form input[type="checkbox"]:checked').length == 1){
$('form').submit();
}
else{
e.preventDefault();
}
});
for 'form' use your form selector

Categories

Resources