Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Dec 2008
    Posts
    117
    Thanks
    14
    Thanked 0 Times in 0 Posts

    jquery: how to make variables from values

    Hi,
    I wonder if i can turn values into variables...

    for instance this is the html,


    Code:
    <input type="checkbox" id="var_1" class="categories"/>
    <input type="checkbox" id="var_2" class="categories"/>


    it is fine if i declare the variable manually like this below,

    Code:
    if ($('#var_1').attr('checked')) {
    		var_1 = 1;
    		}else{
    		var_1 = '';
    		}
    	
    	if ($('#var_2).attr('checked')) {
    		var_2 = 1;
    		}else{
    		var_2 = '';
    		}
    but i think it is a bit too much to declare variable one by one when i have a long list of checkboxes.

    I thought i could use each() to generate the variables automatically when it has detected other checkboxes in the list.

    Code:
    $(".categories").each(function () {
        	       var $this = $(this);
    		var id = $this.attr('id');
    		if ($("#"+id).attr('checked')) {
    		var id = id;	
    		id = 1;
    		}else{
    		var id = id;	
    		id = '';
    		}
    	});
    but it wont work at all - i think the variables have not been made from values from the code above...

    is that a possible to do that??

    thanks,
    Lau
    Last edited by lauthiamkok; 08-21-2009 at 04:27 AM.

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,460
    Thanks
    11
    Thanked 600 Times in 580 Posts
    Code:
    $(".categories").each(function (b,a) {
     if(a.id) window[a.id]=a.checked?1:"";
    });
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • #3
    Regular Coder
    Join Date
    Dec 2008
    Posts
    117
    Thanks
    14
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by rnd me View Post
    Code:
    $(".categories").each(function (b,a) {
     if(a.id) window[a.id]=a.checked?1:"";
    });
    thank you very much. it works now


  •  

    Posting Permissions

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