Jump to content
alzami

how to uncheck a radio button?

Recommended Posts

i have made two radio buttons.which will show a perticular text in box when clicked.problem is once it's been checked i want to uncheck it if clicked again and when clicked another radio button as well.how can i do that stuff

<!doctype html><html><head><meta charset="utf-8"><title>Untitled Document</title><style>#forms{	width:30px;	height:20px;	border:1px solid black;}</style></head><body><div id="forms"></div><input type="radio" value="player1" onClick="show('forms',1);"><input type="radio" value="player2" onClick="show('forms',2);"><script>function show(el,n){	var m=document.getElementById(el);	m.innerHTML="player"+n;}</script></body></html>

Share this post


Link to post
Share on other sites

If you give them the same name="value" they will be exclusive.

 

http://www.w3schools.com/html/tryit.asp?filename=tryhtml_radio

 

and you can enclose them with a reset button...

<form><input type="radio" name="v1" value="A"/>A<br/><input type="radio" name="v1" value="B"/>B<br/><input type="reset"/></form>

...you avoid the need for a Javascript function with the reset button.

 

If you really want to check and uncheck independently then you might be better off with a checkbox.

 

http://www.w3schools.com/html/tryit.asp?filename=tryhtml_checkbox

Edited by davej

Share this post


Link to post
Share on other sites

Instead of passing a value and reconstructing text to read player1 or player2, read the value from selected radio inputs using 'this' to read any attribute on the selected input for example 'value', 'name', then its just a matter of storing the current value, and if that radio input is click again, because it matches the stored value you force it to clear itself.

var stored_value = "";            function show(el, n) {                var m = document.getElementById(el);                if (n.value != stored_value)                {                    m.innerHTML = n.value;                    stored_value = n.value;                }                else                {                    var parent_form = document.getElementById('myform');                    for(i=0;i<parent_form.elements.length;i++){                    if (parent_form.elements[i].name = n.name){                        parent_form.elements[i].checked=false;                        m.innerHTML = "-";                        stored_value = "";                    }                }                }            }
        <div id="forms">-</div>        <form id="myform">            <label>player1:<input type="radio" value="player1" name="players" onClick="show('forms', this);"></label>            <label>player2:<input type="radio" value="player2" name="players" onClick="show('forms', this);"></label>        </form>
#forms{	min-width:30px;	height:20px;	border:1px solid black;        display: inline-block;        text-align: center;        padding: 0 10px;}
  • Like 1

Share this post


Link to post
Share on other sites

what does this gives us?

parent_form.elements.length

will it work for any html element

lyk if i have a div and it has other elements in it lyk <a>,<img>etc ,will it gives me no.of elements inside that particular div?

Share this post


Link to post
Share on other sites

No, .elements works only for form elements inputs, textarea etc, to list all elements within a div, get the parent div id ref as i did with form, and use getElementsByTagName('*');

 

var parent_html = document.getElementById('mydiv');

 

var all_html = parent_html.getElementsByTagName('*');// universal selector asterisk *

 

alert(all_html.length)

Share this post


Link to post
Share on other sites

@sacred member, Its an old post but I can't thank you enough for taking me two giant steps closer to solving the script problem I'm having. Its the old "single radio button toggle" issue, about which much (mostly acidic) things have been said, but little has been given.The problem is - I wish to permit the user to toggle a single radio button, on or off (clear or not-clear). The result I need is only to have the status of that one radio button available for form mail php to pickup and process along with other form data, and to display that single button properly without changing anything else on the form. Now the one-button toggle appears to be impossible (at least without a lot of complicated js and other hacking behind the scenes), from all I've read. But as a two-button solution, I think your approach is only a few steps away from doing it. I now need to turn off the display of the dummy button and let the remaining target button display normally and respond to the toggle. That will make it appear to the user that there is only a single button, one which they can toggle on or off as they wish. I've stripped the labels from your inner div and tried 'display:none', and other methods both in the css and html with no success. I've been able to blank out the display of all but the target button, but then it wouldn't toggle. I've gotten it to toggle, but then the form display would be junk. Nothing I've tried seems to work.Here's the snippet of the form I'm working with. You can see, I' have two radio buttons to do in this fashion, but for now I've just been trying to get one to work. I think you're very close to an answer, so I thought I'd ask and see if we can't find a good and relatively simple solution. Here's the snippet of my form:(this code is as I used it before adding your script and modifying the html or trying out display:none and other changes. If you view the form you will get an idea of what I'm presenting and what I wish to do).<~- The HTML for Form1 --><div id="form1"> <form id="contact" method="post" name="email" target="_blank" action="/myscript.php" > <input id="email" name="EmailAddr" type="email" value="your email address" <br /><br />

<input id="subscription" name="subscribe" type="radio" value="no" /> <label for="subscribe"> Yes, send me important news.</label><br />

<input id="writer" name="writer" type="checkbox" value="no" /> <label for="writer">Yes, send submission guidelines.</label> <input id="help" name="help" type="checkbox" value="no" /> <label for="help">Yes, send me info on helping Z.</label> <br /><br /> <textarea id="feedback" name="comments" cols="28" rows="5" placeholder="Enter your feedback/comments here"></textarea> <input id="permission" name="permit" type="checkbox" value="no" /> <label for="permit">check if you wish to givepermission<br /> for Z to use in letters to the editor"</label> <input id="sendform1" name="send" class="submit" type="submit" value=" submit " /> </form> </div>/* The supporting CSS */div#form1 { clear:both; width:94%; border:4px solid #DADADA; margin-bottom:2em; }#contact { width:100%; height;auto; padding: 1em; background: #DADADA; border: 2px solid #b22222; }#email { display:inline-block; padding: 1px; font-size: 12px; /* background: url(images/email.png) 5px no-repeat #fff; */ color: black; padding-left:20px; border: 3px solid #b22222; }#subscription { padding:0; margin-right:0; height:1.6em; width:1.6em; background: #DADADA; border: 1px solid #DADADA; text-shadow: none; color: black; }#writer,#help,#permission{ display:inline-block; height:1.4em; width:1.4em; margin:.3em; }#sendform1 { display:inline-block; padding:0em; margin:0.3em; margin-top:1.2em; color:black; height 1em; width:auto; text-align:left; border:px solid green; }#feedback textarea{ padding:0; margin:0; margin-bottom:2em; font-size:1em; font-weight:400; text-align:left; color:blue; } label { max-width:100%; white-space:nowrap; display:inline; color:black; font-weight:bold; font-size:1.1em; text-align:left; }

 

Your Js Script:

<script>

 

var stored_value = "";

function show(el, n) {

var m = document.getElementById(el);

if (n.value != stored_value)

{

m.innerHTML = n.value;

stored_value = n.value;

}

else

{

var parent_form = document.getElementById('form1');

for(i=0;i<parent_form.elements.length;i++){

if (parent_form.elements.name = n.name){

parent_form.elements.checked=false;

m.innerHTML = "-";

stored_value = "";

}

}

}

}

</script>

Edited by red

Share this post


Link to post
Share on other sites

Use name reference on hidden input with same index

            <input type="hidden" value="yes" name="rad1[0]">            <input type="radio" value="no" name="rad1[0]">

IF radio button not selected, the hidden 'yes' value will be sent, IF radio selected it will override hidden value and 'no' will be sent

  • Like 1

Share this post


Link to post
Share on other sites

Toggle radio

        <script type="text/javascript">            var radthis = false; // must match default radio state true if checked, false if not            function dothis(elem) {                (radthis && elem.checked) ? (elem.checked = false) : (elem.checked = true);                radthis = elem.checked;            }        </script>
            <input type="hidden" value="yes" name="rad1[0]">            <input type="radio" value="no" onclick="dothis(this)" name="rad1[0]">
  • Like 1

Share this post


Link to post
Share on other sites

follow-up @sacred member -- I also tried changing the order of the two inputs, using type="hidden" on the dummy, and removing your show function from it. But the target button still fails to show up. I'm thinking the scope of display is built into the radio button and will need some kind of js or other script to turn off the dummy's precedence and permit the target button to display normally.

Share this post


Link to post
Share on other sites

WOW - BINGO! your solution appears to work. I won't know for certain until I install and process with my php, but it's looking good in the preview. I'll let you know if there are any problems with it.You know, Sacred, you deserve to go to the head of the class (or whatever kudos W3Schools bestows). All over the net people say the 'one-toggle button' problem cannot be solved - and then launch into some inane philosophy about the nature of radio buttons or "what do you want to do that for?...' or "use checkboxes' nonsense. Well, there are very good reasons I needed to do it, and you've made it possible. Once thoroughly tested, I think your "one-button solution" should be posted in a bunch of forums and put an end to the arguments. I'm obliged and will credit you on the website when its installed. thanx again.

Share this post


Link to post
Share on other sites

looking good. One small problem remaining. I have two, independent radios that are to be toggled (which means 4 total buttons, each getting its own 'ghost-button' to perform the toggle). However, the second button has to be clicked twice, most times, to get it to respond to the toggle. I suspect it has something to do with initialization of script that both are calling in the onclick command. Perhaps they need separate scripts? Maybe an If/else or case stmt in the script you provided could distinguish which button is making the call and act accordingly. Like I say, js is not in my skill-set, so I don't even know if that's the problem. Here's the setup at this point:The script:

<script type="text/javascript"> var radthis = false; // must match default radio state true if checked, false if not function dothis(elem) { (radthis && elem.checked) ? (elem.checked = false) : (elem.checked = true); radthis = elem.checked; } </script>

The markup: <input id="subscription" name="subscribe[0]" type="radio" value="new subscriber" onclick="dothis(this)" > <label for="subscribe">yes, put me on the Z-notify elist.</label><br /> <input name="subscribe[0]" type="radio" value="ghost-subscriber" style="display:none;"> <br /><br /> <input id="permission" name="permission[0]" type="radio" value="given to use comment" onclick="dothis(this)" /> <label for="permission">click if you will allow The Z to quote or use comment in letters to the editor</label><br /> <input id="permission" name="permission[0]" type="radio" value="ghost-release" style="display:none;" />

Edited by red

Share this post


Link to post
Share on other sites

More complicated, you have store current checked state to selected radio button using html5 data storage which won't work in older browsers (I.E. IE :)), or custom attribute which should work in old and present. Also because you are using hidden radio of same name it is still active, when you check->uncheck the viewable radio button you will end up with the hidden radio button being unchecked and no data from either will be sent. You will have to use javascript to do what the radio buttons originally do, by unchecking all but the one selected that uses the same name.

 

Also 2 identical id references, not good

 

<input id="permission" name="permission[0]" type="radio" value="given to use comment" onclick="dothis(this)" />

<input id="permission" name="permission[0]" type="radio" value="ghost-release" style="display:none;" />

  • Like 1

Share this post


Link to post
Share on other sites

understood. It's fine for me when no data is sent from either button on check->uncheck on the visible one - I simply treat empty data returns as a 'not checked'. I've tested it on all four cases (both-checked/only one-checked/both=unchecked/ and they all return correct data via my fm php. As I said, The only problem I can see is the need to double click the second button if the first has been toggled. And that, I take it, has to do with the script not knowing (preserving) which button the data came from. So I'm still wondering if the simple and most straightforward way to handle that is either an If/else in the script that identifies which button is being toggled (by its name attribute?) or using separate identical functions called by the respective button to be toggled. If that's doable, then I favor the if/else method, since you could also replace the if/else with a case stmt. and set up as many toggle buttons as you wish. I hope I've been clearer than mud in my description - I underscore, I've no java skills under by belt, none. nada, zip.p.s. yes, thanx, I caught the doubled 'id=' and corrected. On the old "browsers issue, it may seem cold but I frankly don't much care about providing for old browsers. Updating them is free and people who don't want to should expect that things may not work. More recent versions, yes. But certainly not IE 6, 7 & blah. I just can't be bothered and I think we're just wasting a lot of time with a bunch of hacks to appease someone's nostalgic fixations. Others may do as they wish, but I've enough trouble trying to build a responsive, fluid layout just for more recent versions. I'm satisfied with that.For Anyone Interested:.Feel free to use my form or parts and the techniques discussed here as you wish. Its public domain as far as I'm concerned. But do credit Sacred Member for his one-button toggle solution. Its the first I've seen that actually did the trick. The label wrapper technique I used to align labels was from someone online, but I can't recall who or where. I much prefer it to the css solutions I've seen - they are simply too specific and require too much fiddling and code to be practical for me. Here I part with the semantic purists. The markup wrapping works on any form that needs label alignment, it only takes an extra line (the <span>), and is easy to do in any context. When css can do that, I'll reconsider (though I do use a little css for borders, font and control sizing and stuff like that) Anyway, here's the form I've got to date, just modify for your needs/content:<div id="form1"> <form id="contact" method="post" name="email" target="_blank" action="put your action target here" > <input id="email" name="EmailAddr" type="email" value="email address (required)" placeholder="email address (required)" size="40" /> <br /><br /> <label for="subscribe" class="label-wrap"> <input id="subscription" class="left" name="subscribe[0]" type="radio" value="new subscriber" onclick="dothis(this)" > <span> yes, put me on the Z-notify email list.</span> </label> <br /> <input name="subscribe[0]" type="hidden" value="add to subscriber list" style="display:none;"> <label for="submission" class="label-wrap"> <input id="submission" class="left" name="submission[0]" type="checkbox" value="guidelines requested" /> <span>yes, send me infomation on submitting articles.</span> </label> <br /> <input name="submission[0]" type="hidden" value="guidelines requested" style="display:none;"> <label for="z-helping" class="label-wrap"> <input id="help" class="left" name="z-helping[0]" type="checkbox" value="info requested" /> <span>yes, send me information on helping Z.</span> </label> <input name="z-helping[0]" type="hidden" value="send info on helping Z" style="display:none;" <br /><br /> <textarea id="feedback" name="comments" cols="28" rows="5" placeholder="Enter your feedback/comments here"></textarea> <br /> <label for="permission" class="label-wrap"> <input id="permission" class="left" name="permission[0]" type="radio" value="given to use comment" onclick="dothis(this)" /> <span>double-click if you permit Z to quote or use your comment in letters to the editor</span> </label> <input name="permission[0]" type="hidden" value="given to quote or use comment" style="display:none;" /> <input id="sendform1" name="send" class="submit" type="submit" value="SUBMIT" /> </form>plus SM's script and whatever extra hidden fields you need for your input.

Edited by red

Share this post


Link to post
Share on other sites

1) For this to work correctly the hidden inputs MUST be placed ABOVE the radio buttons

2) hidden inputsdo not require display: none to hide them, as the type already gives the clue in that they ARE hidden.

       <div id="form1">            <form id="contact" method="post" name="email" target="_blank" action="newEmptyPHPWebPageResponse.php">                <input id="email" name="EmailAddr" type="email" value="email address (required)" placeholder="email address (required)" size="40" />                <br /><br />                <label for="subscribe" class="label-wrap">                    <input  name="subscribe[0]" type="hidden" value="add to subscriber list">                    <input  id="subscription" class="left" name="subscribe[0]" type="radio" value="new subscriber" onclick="dothis(this)" >                    <span> yes, put me on the Z-notify email list.</span>                </label>                <br />                <label for="submission" class="label-wrap">                    <input  name="submission[0]" type="hidden" value="guidelines requested" >                    <input id="submission" class="left" name="submission[0]"  type="radio" onclick="dothis(this)" value="guidelines requested" />                    <span>yes, send me infomation on submitting articles.</span>                </label>                <br />                <label for="z-helping" class="label-wrap">                    <input  name="z-helping[0]" type="hidden" value="send info on helping Z">                    <input id="help" class="left" name="z-helping[0]"  type="radio" onclick="dothis(this)" value="info requested" />                    <span>yes, send me information on helping Z.</span>                </label>                <br /><br />                <textarea id="feedback" name="comments" cols="28" rows="5"                          placeholder="Enter your feedback/comments here"></textarea>                <br />                <label for="permission" class="label-wrap">                    <input name="permission[0]" type="hidden" value="given to quote or use comment" />                    <input id="permission" class="left" name="permission[0]"  type="radio" value="given to use comment" onclick="dothis(this)"  />                    <span>double-click if you permit Z to quote or use your comment in letters to the editor</span>                </label>                <input id="sendform1" name="send"  class="submit" type="submit" value="SUBMIT" />            </form>

For multiple radios using same function

        <script type="text/javascript">            window.onload = init;            function init()            {                var parent_form = document.getElementById('contact');                for (i = 0; i < parent_form.elements.length; i++)                {                    if (parent_form.elements[i].type === "radio")                    {                        if (parent_form.elements[i].checked === true)                        {                            parent_form.elements[i].setAttribute('data-boolean', true);                        }                        else                        {                            parent_form.elements[i].setAttribute('data-boolean', false);                        }                    }                }            }            function dothis(elem) {                var convert = elem.getAttribute('data-boolean') === "true" || elem.getAttribute('data-boolean') === true;                convert === true && elem.checked ? (elem.checked = false) : (elem.checked = true);                elem.setAttribute('data-boolean', elem.checked);            }        </script>
  • Like 1

Share this post


Link to post
Share on other sites

Yes, I see. Not that I know spit about js, but I coded in C and Pascal and Lillith & such, and the structures are familiar. I'll light it up tomorrow and see how it works (you've been right on the money so far, so I've no doubt it does the trick). Don't quite understand why the order of the hidden/visible button declarations should be important, but I take your word they are. &ya, display:none redundant. A habit from the old days (real old days) when I coded critical VLIS systems on which people's lives depended. We'd reassert global statements all over the place just to be damn sure that some random glytch happened, it didn't propogate. I should drop it, but some habits are hard to break :) ran in to a strange little anomaly about floats that may/may not interest you. I'm going to post it on my other post on 'dropped floats' -- foxy helped me with the last one. either or both of you may know what's 'bugging' me on the new wrinkle. So thanks again. I do think you should publish the toggle solution widely. a lot of people seemed to puzzle it and give up. later. (my profile looks the same, boring cameo of a nobody - that's me!

Share this post


Link to post
Share on other sites

 

Don't quite understand why the order of the hidden/visible button declarations should be important

 

Because input values are read top to bottom, the hidden value will always be collected, the related radio value only when checked, they use the name value name='whatever[0]' ('whatever', with index ref of 0, like an array index ref), meaning when radio is checked it will override/overwrite the value from previous element using same name='whatever[0]'.

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×