1

I have some checkboxes as shown

</tr>
<td style="padding-left: 10px" width="70px">
    <asp:CheckBox ID="ChkDytLek" runat="server" class="llogariDyt" GroupName="Monedha" Text="Lek" CssClass="radioMarginLeft" OnClick="ChkValidate()" />&nbsp;&nbsp; <img src="images/eagle-clipart-albanian-7.jpg" width="24px" height="15px" />
</td>
<td>
    <asp:CheckBox ID="ChkDytCAD" runat="server" GroupName="Monedha" Text="CAD" CssClass="radioMarginLeft" class="llogariDyt" OnClick="ChkValidate()" />&nbsp;&nbsp; <img src="images/CAD.png" width="24px" height="15px" />
</td>
</tr>
<tr>
    <td> </td>
    <td style="padding-left: 10px">
        <asp:CheckBox ID="ChkDytEU" runat="server" GroupName="Monedha" Text="EUR" CssClass="radioMarginLeft" class="llogariDyt" OnClick="ChkValidate()" />&nbsp;&nbsp; <img src="images/eu.png" width="24px" height="15px" />
    </td>
</tr>

But I want to limit the user to select not more than 2 of them. I am using a java Script function, but I cant tell why the function is called but enters only in alert(1) and doesn't get the values of my check boxes. I am calling them the wrong way or something?

function ChkValidate() {

    var NewCount = 0

    if (document.getElementsByClassName("chkDytLek").checked = true) {
        NewCount = NewCount + 1
    }
    alert(2);
    if (document.getElementById("chkDytUSD").checked = true) {
        NewCount = NewCount + 1
    }
    alert(3);
    if (document.getElementById("chkDytEUR").checked = true) {
        NewCount = NewCount + 1
    }

    if (document.getElementById("chkDytCAD").checked = true) {
        NewCount = NewCount + 1
    }

    if (document.getElementById("chkDytCHF").checked = true) {
        NewCount = NewCount + 1
    }

    if (NewCount == 3) {
        alert('Pick Just Two Please')
        document.forms;
        return false;
    }
}
2
  • 1
    if(a = true) does not do what you think it does. It's not checking if a is true, it's assigning the value true to a (and returning the result of the operation, which is also true, so the if() condition will always be satisfied). You want to use if(a === true), or simply if(a). Commented Apr 10, 2018 at 9:11
  • @JeremyThillei changet all the if conditions in alert(1); if (document.getElementsById("chkDytLek").checked == true) { NewCount = NewCount + 1 } but still nothing Commented Apr 10, 2018 at 9:23

8 Answers 8

1

that is because of the single '=' in your if conditions.

if (document.getElementsByClassName("chkDytLek").checked = true)

should be :

if (document.getElementById("chkDytLek").checked == true)
Sign up to request clarification or add additional context in comments.

1 Comment

i changet all the if conditions in alert(1); if (document.getElementsById("chkDytLek").checked == true) { NewCount = NewCount + 1 } but still nothing
0

you can achieve with one condition instead of multiple condition,

function ChkValidate() {
    var countClicks = document.querySelectorAll('input[type="checkbox"]:checked').length

    if(countClicks > 2){
      alert('Pick Just Two Please')
      document.forms;
      return false;
    }
}

2 Comments

using the <INPUT name=ChkDytCHF type=checkbox value=Charity_profile onclick="return itemClicked(3)"> CHF tag is giving me problems with all the rest of code, and still not giving me what i want
@Lara Please check your checkbox whether you have given properly.
0

I would personally use this kind of code (shorter and more elegant) :

let checkboxes = document.querySelectorAll(".checkbox")

ChkValidate = () => {
	let checkedCount = checkboxes
           .filter(checkbox => checkbox.checked) // Keeps only the checked ones
           .length
           
	console.log("checkedCount = ", checkedCount)
  
	if (checkedCount > 2) alert("Pick Just Two Please")
}

checkboxes.forEach(cb => cb.addEventListener("click", ChkValidate)) // Attach click events to nodes
checkboxes = Array.from(checkboxes) // Allows then to use .filter
<input class="checkbox" type="checkbox"/>
<input class="checkbox" type="checkbox"/>
<input class="checkbox" type="checkbox"/>
<input class="checkbox" type="checkbox"/>
<input class="checkbox" type="checkbox"/>
<input class="checkbox" type="checkbox"/>

1 Comment

using the <input class="checkbox" type="checkbox"/> gives me error in this line since i have a method that checks if one specific checkbox is checked or not bool monDytLek = ChkDytLek.Checked;
0

First thing chkDytLek is not class in your code It is an Id and also single = used for assign not for comparing

Replace code and assign correct classes and Id's

document.getElementById("chkDytLek").checked == true

Note -> getElementById will give a single dom element because Id is unique in Dom getElementsByClassName will give you an array so you need to check like this for class

document.getElementsByClassName("someclass").checked = true

If you want above functionality with class name then check this

https://stackoverflow.com/a/14967895/6236938

http://jsfiddle.net/4mYbD/3/

3 Comments

yes it is a mistake a forgot to correct before posting the code, i replaced it with alert(1); if (document.getElementsById("chkDytLek").checked == true) { NewCount = NewCount + 1 } but still nothing. how is using getElementsByClassName identifying which check box is checked and which not? that was the reason i am trying to use getElementById
Ok if you want do with getElementsByClassName then you can do with array index's As I mentioned above getElementsByClassName will return array
I update my answer with some link I will suggest you to do this with class not by id.
0

function ChkValidate() {
  var aCheckboxes = document.querySelectorAll('input[type="checkbox"]');
  var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
  
  if (count === 2) {
    for (var i = 0; i < aCheckboxes.length; i++) {
      if (!aCheckboxes[i].checked) {
        aCheckboxes[i].disabled = true;
      }
    };
  } else {
    for (var i = 0; i < aCheckboxes.length; i++) {
      aCheckboxes[i].disabled = false;
    };
  }
}
<input type="checkbox" onChange="ChkValidate();" />
<input type="checkbox" onChange="ChkValidate();" />
<input type="checkbox" onChange="ChkValidate();" />
<input type="checkbox" onChange="ChkValidate();" />

1 Comment

using the <input class="checkbox" type="checkbox"/> gives me error in this line since i have a method that checks if one specific checkbox is checked or not bool monDytLek = ChkDytLek.Checked;
0
document.getElementById("checkBoxparent").addEventListener("change", ChkValidate);
var checkBoxentry = []
function ChkValidate(e) {
    checkBoxentry.push(e.target.getAttribute("id"));
    if(checkBoxentry.length >= 3){
      alert("Please select only two");
      e.target.checked = false;
    }

3 Comments

Please add this id "checkBoxparent" to table tag in HTML file.
you mean this way? <table id="checkBoxparent" border="0" > because still not working. should i change something in my check boxes tag also?
It will be great if u can share your code atleast checkbox container i mean either entire form or table code
0

Issue is with you condition check expression. = is for assigning values from right to left for eg. var x = 10; here 10 is being assigned to x and for comparision == is used for eg. if (x == y), here you're comparing if x equals y

function changed(e){
  var message = e.target.checked ? ' is checked' : ' is unchecked';
  switch(e.target.id){
     case 'CheckBox1': alert(e.target.id + message); break;
     case 'CheckBox2': alert(e.target.id + message); break;
     case 'CheckBox3': alert(e.target.id + message); break;
     case 'CheckBox4': alert(e.target.id + message); break;
  }
}
<input type="checkbox" id="CheckBox1" onClick="changed(event)" />
<input type="checkbox" id="CheckBox2" onClick="changed(event)" />
<input type="checkbox" id="CheckBox3" onClick="changed(event)" />
<input type="checkbox" id="CheckBox4" onClick="changed(event)" />

and because

javascript is case sensitive that means hello and Hello are different to it, and that's exactly where your issue lies.

if (document.getElementById("chkDytLek").checked == true) {
   /* your code */
}

should be changed to

if (document.getElementById("ChkDytLek").checked == true) {
   * your code */
}

the parameters should be exactly in same case as they actually are.

4 Comments

i followed your suggestion but still nothing
@Lara i edited and explained the scenario, please have a look
using the <input class="checkbox" type="checkbox"/> gives me error in this line since i have a method that checks if one specific checkbox is checked or not bool monDytLek = ChkDytLek.Checked;
forget the inputs that should not be confused with, since you're using .aspx. As long as you're giving the proper id's the javascript should serve the purpose.
0

After searching and researching i found that the solution was pretty simple. In the check box tag i needed to add a client ID as Static and than the Java Script function worked perfectly.

<asp:CheckBox ID="ChkDytLek" runat="server" class="llogariDyt"                                
                                GroupName="Monedha" Text="Lek" CssClass="radioMarginLeft" onClick="ChkValidate()" ClientIDMode="Static" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.