SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How do I check if a checkbox is checked?

    Hi everybody,
    I want to be able to use javascript to check if a checkbox is selected. If my checkbox has the following html code

    Code:
    <input type="checkbox" name="cbox1" id=\"cbox1" checked="yes">
    However when I use this, I always get null, even when the box is checked.

    Code:
    var cbox1=document.getElementById(cbox1);
    alert(cbox1);
    Thanks in advance.

  2. #2
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,509
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)
    Try googling for 'javascript checkbox'.

  3. #3
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,631
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Why the \ at id=\"cbox1"? Typo?

    Anyway, it is the .checked status you want to test - it will be either true (1) or false (0).
    Ian Anderson
    www.siteguru.co.uk

  4. #4
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by siteguru View Post
    Why the \ at id=\"cbox1"? Typo?

    Anyway, it is the .checked status you want to test - it will be either true (1) or false (0).

    Hi siteguru, I the \ character is from my php code, I just pasted it incorrectly.

    I have tried this and it does not work.

    Code:
    var cbox1=document.getElementById(cbox1).checked;
    alert(cbox1);
    This is not valid?

  5. #5
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    document.getElementById expects a string parameter.
    It's not clear if this code is running in global scope, but names of global variables must not conflict with IDs.

    Code:
    var cb1 = document.getElementById( "cbox1" );
    alert( cb1.checked );
    Tab-indentation is a crime against humanity.

  6. #6
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Logic Ali, that works


Bookmarks

Posting Permissions

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