开发者

Displaying form inputs using jquery

I want write jquery code that will show form inputs after a checkbox is checked. This is how I have formated the form inputs. What is the开发者_JS百科 best way of doing this?

    echo '<li class="checkbox_item">'. form_label('Number of bedrooms','bedrooms'). form_checkbox('bedrooms','yes'). form_error('bedrooms').'</li>';
    echo '<li class="input_item" id=no_rooms>'. form_label('Number of bedrooms','bedrooms'). form_input('bedrooms'). form_error('bedrooms').'</li>';

    echo '<li class="checkbox_item">'. form_label('Number of bathfooms','bathrooms'). form_checkbox('bathrooms'). form_error('bathrooms').'</li>';
    echo '<li class="input_item">'. form_label('Number of bathfooms','bathrooms'). form_input('bathrooms'). form_error('bathrooms').'</li>';


You could do:

//hide all inputs
$('.input_item').hide()

//when a checkbox is ticked, hide/unihde next li 
$('.checkbox_item input').click(function(){
    $(this).closest('li').next('.input_item').toggle($(this).is(':checked'));
});

working fiddle http://jsfiddle.net/ttyx8/1/

EDIT (i added a selector to next so that the code is better)


I think the best way to do is to use the "change()" event and "toggle()" function. You can bind the "change()" event to the checkbox, once triggered, "toggle" the display of the target element.

Example in the following have one checkbox, once checked, an input field will display. Once unchecked, the input field will hide.

<html>
<head>
<script type='text/javascript' 
      src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'>
</script>

<script type='text/javascript'>
$(document).ready(function(){
    $('#selectroom').change(function(){
        $('#chooseroom').toggle();
    });
});

</script>

</head>
<body>
<p>
 Select bedrooms <input type='checkbox' id='selectroom'/>
</p>
<p id='chooseroom' style='display:none;'>
 How many bedrooms? <input type='text' name='roomnumber'/>
</p>
</body>

</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜