views:

55

answers:

2

I have a bunch of optional "write-in" values for a survey I'm working on.

These are basically a radio button with a textbox within the answer field - the idea being that you would toggle the button and write something into the box.

What I'd like to do is have the radio button toggled whenever a user clicks in the text field - this seems like a use-case that makes a lot of sense.

Doing this:

<input type="radio" id="radiobutton"><label for="radiobutton">Other: <input type="text" id="radiobutton_other"></label>

works fine in Chrome (and I am guessing, other WebKit browsers as well), but there are weird selection issues in Firefox, so I'm assuming its a non-standard practice that I should stay away from.

Is there a way to replicate this functionality without using JavaScript? I have an onclick function that will work, but we're trying to make our site usable for people who might have NoScript-type stuff running.

+1  A: 

Putting an input inside a label actually has a slightly different meaning. It doesn't make the input itself a label, it implicitly associates the label with the input in the same way as if they were linked by a for/id.

However, this only happens when the label doesn't already have a for attribute to override that (see HTML4 s17.9: “When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element's contents.”). It is unclear according to spec what should happen when both containment and for are present.

(And also it doesn't work in IE, which makes the point moot in practical terms.)

No, you'll need some scripting for this.

<input type="radio" id="radiobutton">
<label for="radiobutton_other">Other:</label>
<input type="text" id="radiobutton_other">

<script type="text/javascript">
    var other= document.getElementById('radiobutton_other');
    other.onchange=other.onkeyup= function() {
        if (this.value!=='')
            document.getElementById('radiobutton').checked= true;
    };
</script>
bobince
A: 

It (an input inside a label) validates just fine as HTML 4.01. One potential issue I can see with your code is that both radio elements have the same ID in your example. Element IDs must be unique in HTML and XHTML documents and you should use the name attribute instead to identify a radio group.

If you are still having trouble after changing this, you will have to move the input outside of the <label> element and use scripting.

Andy E
Both elements do not have the same id.
John Hartsock
@John Hartsock: Whoops :-) misread the second element's id.
Andy E