SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    javascript: find a checkbox

    Hello,

    Could you please help me debug the below code?

    I have a few input whose names I know. I want to make sure they're checked.

    Code:
    function test(name) {
    	var chkBox = document.getElementsByName(name);
    		if(chkBox != "undefined"){
    				if(chkBox.checked == false) {
    					chkBox.checked = true;
    				}
    		}
    }
    Is getElementsByName reliable (cross-browser, fast?) or should I use getElementById?

    Cheers.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by rhgiant View Post
    Is getElementsByName reliable (cross-browser, fast?) or should I use getElementById?
    The most appropriate way is to get the form field from the form elements collection.

    For example:

    Code javascript:
    function test(chkBox) {
        ...
    }
     
    function buttonHandler () {
        var form = this.form;
        test(form.elements['checkbox1']);
    };
     
    var form = document.getElementById('testform');
    form.elements.testbutton.onclick = buttonHandler;
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Paul,

    It seems though that my test() function isn't working properly.... Is there a mistake in my code?

    And also, what if there's no way I can know the form id, but I still know which fields I should trigger?

    I really want to thank you for your help. It's awesome! I'm learning a lot.


  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by rhgiant View Post
    It seems though that my test() function isn't working properly.... Is there a mistake in my code?
    Let's take look at a test page the demonstrates the problem.

    Quote Originally Posted by rhgiant View Post
    And also, what if there's no way I can know the form id, but I still know which fields I should trigger?
    You might be in for a heap of trouble then, because field names are allowed to be duplicated multiple times on the page.
    For example, an email field in the sign in form at the top of the page, the email field in the registration form in the main part of the page, and the email field in the subscription part near the bottom are all completely valid identical names on one page.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, I followed your advice. Does that look goo dto you? It works, at least.

    http://jsfiddle.net/rhgiant/ZJFUU/1/

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by rhgiant View Post
    Ok, I followed your advice. Does that look goo dto you? It works, at least.

    http://jsfiddle.net/rhgiant/ZJFUU/1/
    Some tidying up that can occur is to remove the name attribute from the form. The name attribute should only be used on elements within a form that are intended to be submitted.
    Another tidy-up is to remove the id attribute from the input field, because it's a bad habit to scatter around id attributes when they're not being used.

    Also, do you see the duplication in the following?

    Code:
    if(myForm.elements[retrivedChekboxName].checked == false) {
        myForm.elements[retrivedChekboxName].checked = true;
    Assigning myForm.elements[retrivedChekboxName] to a variable can help tidy that up.

    Code javascript:
    var checkbox = myForm.elements[retrivedChekboxName];
    if (checkbox.checked === false) {
        checkbox.checked = true;

    Notice also that the coercive equality has been replaced with the strict equality. It's a bad habit to use the coercive one, as it has several unintended consequences.
    Also, a space has been placed between the if keyword and the condition parenthesis. It's when calling a function that you have no space between the function name and the parenthesis. With keywords you place a space between them to help improve the readability of the code.

    Finally, we now have three separate var satements.

    Code:
    var retrivedChekboxName = 'checkbox1';
    var myForm = document.getElementById('test');
    var checkbox = myForm.elements[retrivedChekboxName];
    Those really should be defined in just the one var statement instead, such as this:

    Code javascript:
    var retrivedChekboxName = 'checkbox1',
        myForm = document.getElementById('test'),
        checkbox = myForm.elements[retrivedChekboxName];

    After all of that it's looking a lot better.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah. Thank you so much. Great, great help.

    Just one more question: how do you get <label> being tied to a field if you don't put an id on that field? I thought that the for attr had a match with the id.


  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by rhgiant View Post
    Just one more question: how do you get <label> being tied to a field if you don't put an id on that field? I thought that the for attr had a match with the id.
    Now that IE6 is considered to be dead, you don't have resign yourself to using explicit association. You have implicit association at your disposal where you wrap the label around the field itself as well.

    HTML Code:
    <label>Username: <input name="username"></label>
    The 1999 specifications for HTML 4.01 show a similar implicit association example.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oh, great to know

    I'm running into a strange problem, though.

    My code wouldn't work once I leave jsFiddle. I cam with a very simple version of what I'm trying to do. This works in jsFIddle, but the exact same version doesn't work in firefox.

    Here's the fiddle: http://jsfiddle.net/rhgiant/FKCcS/

    And here is my .html page (as I said, loaded in FF). The error I get (fro Firebug) is that testForm is null.

    Code:
    <!doctype html>
    
    <html lang="en">
    
    	<head>
    	
    		<title>Js Test</title>
    		
    		<script>
    			var testForm = document.getElementById("testForm");
    			testForm.elements["testCheck"].checked=true;
    		</script>
    
    
    	</head>
    
    	<body>
    			
    			<form action="#" id="testForm" method="post">
    
    				<input type="checkbox" name="testCheck">
    
    			</form>
    
    
    	</body>
    
    </html>
    I have tried to find for about 2 hours what could go wrong, didn't come up with anything... Maybe you can see what is wrong, Paul?


  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    The fiddle code is wrapped in an onload event. You don't have to do that though. Just move your script to the end of the body and you'll be fine.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  11. #11
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're the kind of person that makes me say the internet is a great invention!


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
  •