www.webdeveloper.com
Results 1 to 7 of 7

Thread: Problem with dynamic limit on checkboxes

  1. #1
    Join Date
    May 2007
    Posts
    8

    Post Problem with dynamic limit on checkboxes

    Hi guys,

    i'm having a little trouble with a script. I'm not that good at javascripting/jquery etc., so i'm gonna need your help.

    I'm building a website where registered users can place messages in different categories. What i'm trying to do is to give a user after registration on my site the opportunity to choose how many categories and which categories they can post in. So it looks a bit like this:

    Register.php---------------

    * Number of categories: [input field with standard value set as 3 with id='cat'] (+) (-)

    *Choose your categories ( [] = checkbox with name='ckb' and id=cat name(cat1,cat2, etc))
    [] cat 1 [] cat 4
    [] cat 2 [] cat 5
    [] cat 3 [] cat 6

    Register.js (included in index.php)-----------------

    Code:
    window['aant'] = document.getElementById('cat').value //Global variable
    
    function add(name) {
    	if (name == 'cat') {
    		
    	if (document.getElementById(name).value < 12) {
    		var value = parseInt(document.getElementById(name).value);
    		var newvalue;
    		newvalue = value + 1;
    		document.getElementById(name).value = newvalue;
    		window['aant'] = parseInt(newvalue);
    		
    	}	
    	
    	}
    }
    
    function checkboxlimit(checkgroup, limit){
    	var checkgroup=checkgroup
    	var limit=window['aant']
    	for (var i=0; i<checkgroup.length; i++){
    		checkgroup[i].onclick=function(){
    		var checkedcount=0
    		for (var i=0; i<checkgroup.length; i++)
    			checkedcount+=(checkgroup[i].checked)? 1 : 0
    		if (checkedcount>limit){
    			alert("You can only select a maximum of "+limit+" checkboxes")
    			this.checked=false
    			}
    		}
    	}
    }
    So the global variable window['aant'] is set to the value that the inputfield of number of cats standard has (but it doesn't work, that value doesn't get assigned to that global variable). If you click the + sign after 'number of categories', the global variable should get a +1, so that the limit on the checkboxes get raised by one too.

    But i can't get it to work. The getelementbyid doesn't work in the first place with the global variable. But even if i give it a standard number, for instance 3, then the limit on checkboxes doesn't get changed, it stays on 3. It has to be a getelementbyid because the number isn't always 3, it can be a different value if you choose another package in a earlier step in the registration process.

    Maybe the problem is that the limit on checkboxes can't get changed without ajax or something. I've tried to implement jquery, but i really don't know much about it. Can anybody give me some advice?

  2. #2
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    862
    My first thoughts when looking at this are that you are trying to use an array variable named 'window' which is the problem. window is essentially reserved for the window object in javascript and so you can't really assign custom variables to it(as far as I know, or not without some weird prototype/custom code).
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  3. #3
    Join Date
    May 2007
    Posts
    8
    Quote Originally Posted by Sup3rkirby View Post
    My first thoughts when looking at this are that you are trying to use an array variable named 'window' which is the problem. window is essentially reserved for the window object in javascript and so you can't really assign custom variables to it(as far as I know, or not without some weird prototype/custom code).
    Ok thanks for your reply but i thought that window['name'] was a form of a global variable. And, it works if i assign a fixed value to it. But i can't assign a value from the input text field to it.

    And even if it works, if i give window['aant'] the value '3', the limit on checking checkboxes will be 3, but i can't change that limit with the script. So the limit of 3 will work, but if i click on the + sign to increase the limit than it still says sorry, you're only allowed to check 3 boxes.

  4. #4
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    862
    You are correct on the 'global variables' part as I just took some time to google it. It seems we learn something new every day.

    As for your code, one thing I notice is you are missing several semi-colons which is bad for code in general. But I could easily assume the code you pasted here might be less 'perfect' when compared to your actual page code and even then won't be a big enough deal to worry about since apparently the functions are executing normally.

    And so it brings me to my last idea which is the fact that if this code is placed BEFORE the <input id="cat"> in your HTML code then it will always fail to grab the value as the element doesn't exist when that code is executed. So if that script is placed in the <head> area of the webpage it won't successfully set the variable. But if you have placed it in a <script> tag near the end of your document(or simply after the cat element is created) then I'm currently at a loss as to why it doesn't work. It is usually hard to debug code when it's taken out of context as there are many things that remain unknown.

    Finally, since you say even after manually setting the value it doesn't seem to increase, I would suggest doing a little self-debugging using the alert(); command in javascript. Place an alert(); after any or all of the variables(each line) in the code to call back the variable step by step and see how it changes. You are essentially looking for a specific point where the code fails to grab or set something. Once you pinpoint this it gets a lot easier to solve it.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  5. #5
    Join Date
    Nov 2010
    Posts
    1,047
    maybe I don't understand what you are trying to do here, but I'm struggling to see the need for global variables. Here is how I would do what I imagine you are trying to do, maybe it will help:

    Code:
    <html>
    <head>
    </head>
    <body>
    <div id="display">
    <input type="text" id="limit" value="3"/>
    <input type ="checkbox" id="cat1" onclick="checkLim()">
    <input type ="checkbox" id="cat2" onclick="checkLim()">
    <input type ="checkbox" id="cat3" onclick="checkLim()">
    <input type ="checkbox" id="cat4" onclick="checkLim()">
    <input type ="checkbox" id="cat5" onclick="checkLim()">
    <input type ="checkbox" id="cat6" onclick="checkLim()">
    <script language = "javascript">
    function checkLim() {
    count=0;
    var els=document.getElementsByTagName("input");
    for (var i = 0; i < els.length; i++) {
    if ((els[i].type=="checkbox")&&(els[i].checked==true)){
    count++
            }
        }
    lim=Number(document.getElementById("limit").value);
    if (count>lim){
    alert("you have checked too many boxes!")
    		}
    	}
    </script>
    </body>
    </html>

  6. #6
    Join Date
    May 2007
    Posts
    8
    Quote Originally Posted by xelawho View Post
    maybe I don't understand what you are trying to do here, but I'm struggling to see the need for global variables. Here is how I would do what I imagine you are trying to do, maybe it will help:

    Code:
    <html>
    <head>
    </head>
    <body>
    <div id="display">
    <input type="text" id="limit" value="3"/>
    <input type ="checkbox" id="cat1" onclick="checkLim()">
    <input type ="checkbox" id="cat2" onclick="checkLim()">
    <input type ="checkbox" id="cat3" onclick="checkLim()">
    <input type ="checkbox" id="cat4" onclick="checkLim()">
    <input type ="checkbox" id="cat5" onclick="checkLim()">
    <input type ="checkbox" id="cat6" onclick="checkLim()">
    <script language = "javascript">
    function checkLim() {
    count=0;
    var els=document.getElementsByTagName("input");
    for (var i = 0; i < els.length; i++) {
    if ((els[i].type=="checkbox")&&(els[i].checked==true)){
    count++
            }
        }
    lim=Number(document.getElementById("limit").value);
    if (count>lim){
    alert("you have checked too many boxes!")
    		}
    	}
    </script>
    </body>
    </html>
    Thank you, that's exactly what I was trying to accomplish! It's much more easy than I thought.

    The only thing that I'm missing now is that the last checked box that was not allowed to tick stays checked. I tried to fix it with this.checked = false, but no result. Which I don't understand, because it still is in the function and the function is being called by the onclick at one checkbox. So the this property should work in my opinion...

    *edit: found the solution. I've put the if(count>lim) into the for loop and added els[i].checked = false; into it, like this:
    Code:
    <script type="text/javascript">
    function checkLim() {
    count = 0;
    var els = document.getElementsByTagName("input");
    var lim = Number(document.getElementById("cat").value);
    for (var i = 0; i < els.length; i++) {
    	if ((els[i].type=="checkbox")&&(els[i].checked==true)){
    	count++;
    		if (count>lim){
    		els[i].checked = false;
    		alert("Je kunt maximaal "+lim+" vakjes aanvinken. Als je meer categorieeŽn wilt gebruiken, verhoog dan het aantal categorieŽn.");
    		}
        }
    }
    }
    </script>
    And now it works. Still not sure what you were meaning by 'els', but that doesn't matter, it works. Thanks for your help!
    Last edited by dherre65; 11-17-2011 at 05:25 AM.

  7. #7
    Join Date
    Nov 2010
    Posts
    1,047
    no problem. "els" in case you are interested returns a list of all the elements with an "input" tag. els is just a name - it could be kablooeys and it would work the same.

    the if statement further narrows down the search, looking only for inputs that are checkboxes AND that are checked.

    your
    Code:
    if (count>lim){
    		els[i].checked = false;
    will be fine if you only have checkboxes as checkable inputs on your page. If you have radio buttons (which will also enter the list as inputs and can have a checked state) you might get unpredictable results. I think (but am unsure) that radio buttons are the only other inputs that can be checked...

    if you have other inputs after your collection of checkboxes, your code is likely to throw an error because it will be trying to uncheck text inputs and select boxes, which can't be done, obviously.

    but then you know how complicated your code is - if none of that applies you will be fine.

    hope that helps.
    Last edited by xelawho; 11-17-2011 at 09:43 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles