isbjorn
isbjorn

Reputation: 63

Show 2nd div when radio button checked

Im trying to make a contact form where people will check either "one way" ticket or "roundtrip".

The first "one way" is checked when user reach the contact form and one(1) date field is shown, but if "roundtrip" is checked i want a 2nd date field to be shown with a return date.

Any ideas?

Upvotes: 0

Views: 2584

Answers (2)

user1093284
user1093284

Reputation:

You would need to use javascript and on-event handlers to accomplish that, as such dependent/binding functionality doesn't come with the regular html form elements (To avoid confusion: same goes for it's potential children).

This answer will give you a pretty good hint how to do it as it answers a question related to a similar problem/request: https://stackoverflow.com/a/5137316/1093284

Update:

As you don't seem very experienced, here's a most simplistic example:

<!-- include jquery.js library first  (http://jquery.com/) -->
<script src="jquery.js"></script>

<!-- then work the magic -->
<script>
$(document).ready(function(){

    $('#inputB').hide;

    $('#checkboxA').click(
        function(e){
                $('#inputA').show;
                $('#inputB').hide;
        });
    $('#checkboxB').click(
        function(e){
                $('#inputB').show;
                $('#inputA').hide;
        });
});
</script>

And if you're fit enough to go pro with jQuery, check the other answer here on this page at https://stackoverflow.com/a/11743381/1093284

Last but not least, I think the answer here at https://stackoverflow.com/a/11743482/1093284 provides the best solution, as it's small and does not require a full-blown 32kb javascript library. On the other hand, inline javascript is actually a no-go. Whatever... it's the users that count and they will prefer a quicker-loading page over nicely coded stuff behind the curtains.

Upvotes: 0

Fabian
Fabian

Reputation: 301

Simply observe the onchange event for the radio button. When it reaches you can check weather single trip or round trip is selected and then show / hide the div with the return date fields.

<!DOCTYPE html>
<head>
<script>
    function hdl_change(e) {
        document.getElementById('date2').style.visibility = 
            e.checked && e.id == 'opt_2' ? 'visible' : 'hidden';
    }
</script>
</head>
<body>
<form name="myForm">
  <input id="opt_1" type="radio" name="trip" value="oneway" onchange="hdl_change(this)"> One way<br>
  <input id="opt_2" type="radio" name="trip" value="round" onchange="hdl_change(this)"> Roundtrip<br>
</form>
<div id="date1"> date 1 stuff ...</div>
<div id="date2" style="visibility:hidden">  date 2 stuff ...</div>
</body>
</html>

Upvotes: 1

Related Questions