Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm trying to make a from where some text fields are hidden by default and will be show only when specific option from <option > box is selected.

I've done this using jquery but the way I made it is really very poor. I need to set the all child text area's or option box's values to blank when any parent option is changed.

So I'm using this jquery to get it done

$('#parent').change(function() {
    if ($(this).val() == 'child1') {
        $('#child1').show() ;
        $('#child2').hide() ;
        $('#child2').val(''); 
        and so on. 

I 3 levels of parent child and I have to repeat this for every parent and child. So my html head section is looking very bad.

Here is a http://jsfiddle.net/Js8DF/ for the complete script. Somebody please tell me how can I get the job done nicely and more elegantly.

share|improve this question

migrated from stackoverflow.com Sep 18 '12 at 23:36

2 Answers

I would group SELECT and INPUT a little more thought through. You can add classes to groups like for example everything that has to do with speed can have a class="speed" then you can for instance:

$('.speed').hide().val('');

or by type

$('input[type="text"]').val('');

These kind of optimizatons will shorten your code.

share|improve this answer

wow, I cannot minify your code as I don't know what is the logic behind your toggling, but you can use classes and data-* attributes or values of option tags for selecting the target elements:

$('#aSelectElem').change(function(){
    $('.specificElements').val('').hide();
    $('#'+ this.value).val('').show()
})

Using classes makes selecting and hiding the elements easier.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.