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 obvi
Use jQuery.
Remove onchange="change()"
function from
<select id="show" class="form-control" name="show_text_area" onchange="change()">
Look for change event, on your select element.
$('#show').on('change', function () {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if(valueSelected == 1){
$("#text_area").show();
} else {
$("#text_area").hide();
}
});
Fiddle
you can use jquery also.
$('#show').val();
if( $('#show').val() == "1")
{
$('#text_area').show();
OR
$("#text_area").css("visibility", "visible");
}else
{
$('#text_area').hide();
OR
$("#text_area").css("visibility", "hidden");
}
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";
}
}
Your function is correct, but js Element class have no show() and hide() methods. You can implement it using prototype. As an example
Element.prototype.hide(){
this.style.display = "hidden";
}
Element.prototype.show(style){
style = style ? style : "block";
this.style.display = style;
}
But better use jquery or something like this.
You can do also using jQuery as follows.
$("#show").change(function(){
if($(this).val()=="1")
{
$("#text_area").show();
}
else
{
$("#text_area").hide();
}
});
Demo
you can do this in jQuery.....like " $(document).ready(function(){
var seletVal=$('#show option:selected').val();
if(selectVal=='1')
$('#textareaId').show();
else
$('#textareaId').hide();
});
"