SitePoint Sponsor

User Tag List

Results 1 to 19 of 19
  1. #1
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    checking for a single or multiple radio buttons

    Hello, I have the following javascript code:

    Code JavaScript:
    for (var i=0; i < myRadio.length; i++)  {
    		if (myRadio[i].checked)  {
    			myChecked = 1;			
    		}
    	}	
    	if (myChecked == 1) {
    		return true;	
    	} else {
    		alert("Choose one radio Button!");
    		return false;
    	}
    This works fine when I have more than 1 radio button. However for just a single radio button it does not work. I don't know how many radio buttons I will have since they are being created from a mysql query.

    I'm very bad with javascript, so how should I amend the code so that it also works with only one radio button? I just need to check if they are trying to submit the form without selecting any radio buttons.

    Thanks.
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  2. #2
    SitePoint Evangelist Maujor's Avatar
    Join Date
    Mar 2005
    Location
    Rio de Janeiro - Brazil - South America
    Posts
    409
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:
    Code JavaScript:
    for (var i=0; i < myRadio.length; i++)  {
            if (myRadio[i].checked)  {
    			break;     
            } else {
            	alert("Choose one radio Button!");
        		break;
    		}
    }
    Mauricio Samy Silva
    http://www.maujor.com/

  3. #3
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The problem is, and I should have said this before, that when there is only 1 button, I get a javascript error saying that myRadio.length is undefined!
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  4. #4
    SitePoint Evangelist Maujor's Avatar
    Join Date
    Mar 2005
    Location
    Rio de Janeiro - Brazil - South America
    Posts
    409
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So I need know how are you setting myRadio.
    Is myRadio something like
    Code JavaScript:
    var myRadio = document.getElementsByTagName("input");
    or what is it?
    Mauricio Samy Silva
    http://www.maujor.com/

  5. #5
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's the whole thing:

    Code JavaScript:
    function checkForm(myForm) {
    	var myRadio = myForm.transChoice;
    	var myChecked = 0; // initialize the variable we'll use to test for checks	
    	for (var i=0; i < myRadio.length; i++)  {
    		if (myRadio[i].checked)  {
    			myChecked = 1;			
    		}
    	}	
    	if (myChecked == 1) {
    		return true;	
    	} else {
    		alert("Choose one radio Button!");
    		return false;
    	}
    }

    transChoice is the name of the radio buttons.
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  6. #6
    SitePoint Evangelist Maujor's Avatar
    Join Date
    Mar 2005
    Location
    Rio de Janeiro - Brazil - South America
    Posts
    409
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What is this?:
    Code JavaScript:
    var myRadio = myForm.transChoice;
    Have a look at:
    Example: http://jsbin.com/uhefu/
    Source: http://jsbin.com/uhefu/edit
    Mauricio Samy Silva
    http://www.maujor.com/

  7. #7
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm bad with javascript, this code was sent to me and it works for multiple buttons. But from what I understand:

    myForm is the form itself, sent to the function by the onSubmit event. Then transChoice, like I said, is the name of the radio buttons. So myRadio should be a variable with the object for that radio button...
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  8. #8
    SitePoint Evangelist Maujor's Avatar
    Join Date
    Mar 2005
    Location
    Rio de Janeiro - Brazil - South America
    Posts
    409
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Weird!
    Sorry! I've tried but am unable to figure out a fix.
    Mauricio Samy Silva
    http://www.maujor.com/

  9. #9
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by pata View Post
    Code JavaScript:
    for (var i=0; i < myRadio.length; i++)  {
        if (myRadio[i].checked)  {
        myChecked = 1;			
    }
        ...

    This works fine when I have more than 1 radio button. However for just a single radio button it does not work. I don't know how many radio buttons I will have since they are being created from a mysql query.
    When there is only one radio button, the myRadio variable will be the single string value for that radio button. When there are multiple radios buttons then myRadio will be an array of strings.

    You need to make sure that myRadio is an array before it gets to the for loop.

    Code javascript:
    if (!myRadio.length) {
        myRadio = [myRadio];
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  10. #10
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As usual Paul, you have the solution, thanks a million.
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  11. #11
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello again friends, things just got a little more complicated. Turns out the same form I am using to choose a default radio button now also needs to be used to save data (without choosing a radio button).

    So I have 2 submit buttons, named differently and act upon the php code depending on which submit button they chose, the one for choosing a default via the radio buttons or the one for saving the data in the text field.

    So the question is, how can I check which button they clicked on to submit the form and then trigger my radio button checking magic if it was that one, or not trigger anything at all if it was the other submit button.

    Cheers.
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by pata View Post
    So the question is, how can I check which button they clicked on to submit the form
    You can give each submit button a name

    Code html4strict:
    <p>
        <input type="submit" name="add" value="Add">
        <input type="submit" name="save" value="Save">
    </p>

    Then you can check from PHP if those actions have been set

    Code php:
    if (isset($_POST['add'])) {
        // do add stuff
    }
    if (isset($_POST['save'])) {
        // do save stuff
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  13. #13
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    no, no that part I have already working, I mean in the javascript. I need the chooseDefault button to trigger the javascript check, but not the save button.
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  14. #14
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    As you haven't specified what html code you're working with, I'll make some assumptions that you're doing things the right way.

    I'll assume that your form has a unique identifer, and that you are assigning events via javascript.

    The sample HTML code is:

    Code html4strict:
    <form id="myForm">
        ...
        <p>
            <input type="submit" name="chooseDefault" value="Choose Default">
            <input type="submit" name="save" value="Save">
        </p>
    </form>

    When the form is submitted, you place code that related to both submit buttons in the standard onsubmit event for the form

    Code javascript:
    form.onsubmit = function () {
        // code relating to both submit buttons here
    }

    For code that relates only to the one button, you assign that to the onclick event for that button itself.

    For example, this allows the chooseDefault button to check if things validate(), and if successful it then triggers the form submit event.

    The success values are retained and returned, in case a return value of false is required to prevent things from carrying on.

    Code javascript:
    form.elements.chooseDefault.onclick = function () {
        var success = validate();
        if (success) {
            success = this.form.onsubmit();
        }
        return success;
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  15. #15
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    In fact, on reflection I have realised that you can simplify things even further than that.

    The chooseDefault onclick event automatically submits the form if it's allowed, you you only need to return the false return from the validate function to prevent the from submitting.

    Code javascript:
    var form = document.getElementById('myForm');
    form.onsubmit = function () {
        // code relating to both submit buttons here
    }
    form.elements.chooseDefault.onclick = function () {
        return validate();
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  16. #16
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by pmw57 View Post
    form.elements.chooseDefault.onclick = function () {
    return validate();
    }
    [/highlight]
    Not sure I fully understand. This bit of code doesn't go in the header of the document, it goes elsewhere?

    Right now the form element has this:

    Code HTML4Strict:
    <form id='MultiTranslations' method='POST' action='$self' onSubmit = 'return checkForm(this);'>
    So, you are correct, either button would trigger that checkForm() function.

    Maybe I should just remove that and have the chooseDefault button trigger that function? Of course, in trying to do this, I have to rewrite the checkForm() function so that it identifies the whole form itself by ID since I won't be able to do the checkForm(this) trick...
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  17. #17
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, this seems to have done the trick, now why didn't I think of that before?

    I replaced function form as follows:

    Code JavaScript:
    function checkForm() {
    	var myRadio = document.getElementById('MultiTranslations').transChoice;
     
    ...

    and then this function only gets called by the onClick method of the chooseDefault button.

    Seems to work. I have no other validation at the moment, when they hit the other submit button, but if I did, I guess I could just put another function to be called by that button the same way, in the onClick method.

    Sound right?
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com

  18. #18
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by pata View Post
    Not sure I fully understand. This bit of code doesn't go in the header of the document, it goes elsewhere?
    Yes, preferably these scripts are placed just before the </body> tag. It's a common practice now, which both speeds up the page loading, and allows you to easily attach events on to page elements.

    Using inline scripting events is a big no-no, as they tend to be harder to maintain. In a similar way, in-page CSS is best moved up to a centralised place near the start of the head.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  19. #19
    SitePoint Evangelist
    Join Date
    May 2002
    Location
    Barcelona, Spain
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello again,

    Things have, of course, evolved now. Customer now wants an empty text field that people can, if they wish, fill out and choose as default.

    So now I need code to make the radio button for that field only be selectable if it is not empty. That would be great. Failing that, since it sounds quite complicated, I would need code to check that if the radio button that corresponds to that field is checked, then that field cannot be empty.

    But, now that I think about it, this won't work because if the field is empty, meaning there is no value, then I can't make that value the default because it is not in the database yet, so I don't have a key for it. Of course, I could always do some PHP magic that if the radio button that was checked does not have a key in it (the radio button values are the key for that entry in the DB) then we know they are choosing the new value, so assign it to the DB, get a key and put that into the default.

    Could be.

    Sorry for the rambling, does that make sense? I know this is not the PHP forum, so I'm not asking for help with that bit, I'll figure it out, but I'm including it here just in case I'm being undercaffeinated and stupid.
    Used to prefer PHP.
    Now I prefer Maya but stuck with PHP
    bruji.com


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
  •