Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show and hide html element on selected option change

In a JSP page, I have a dropdown list. When the first element of the list is selected, I want a text area to show right on click. I'm new to Javascript/Jquery, so I'm obviously missing something in the function (the text area never shows up). Hope someone can help.

This is the HTML:

<tr class="odd gradeX">
    <td class="col-lg-3">
        <div>
            <label>Show text area</label>
            <select id="show" class="form-control" name="show_text_area" onchange="change()">
                <option value="1">YES</option>
                <option value="0">NO</option>
            </select>

        </div>
    </td>
    <td class="col-lg-3">
        <div>
            <label>Text area</label>
            <textarea id="text_area" class="form-control" type="text" name="text_area" placeholder="Write something" rows="5" cols="50" style="display: none"></textarea>
        </div>
    </td>
</tr>

This is the function, on top of the JSP:

<script> function change() {
    var selectBox = document.getElementById("show");
    var selected = selectBox.options[selectBox.selectedIndex].value;
    var textarea = document.getElementById("text_area");
    if(selected === '1'){
        textarea.show();
    }
    else{
        textarea.hide();
    }
});</script>
like image 539
user3673449 Avatar asked Jan 13 '15 12:01

user3673449


1 Answers

You have mistake at the end of your function - remove the last );

Finally it should be:

<select id="show" class="form-control" name="show_text_area" onchange="change(this)">


function change(obj) {


    var selectBox = obj;
    var selected = selectBox.options[selectBox.selectedIndex].value;
    var textarea = document.getElementById("text_area");

    if(selected === '1'){
        textarea.style.display = "block";
    }
    else{
        textarea.style.display = "none";
    }
}
like image 89
alvery Avatar answered Sep 22 '22 07:09

alvery