Issue
its my first post :) I want to select an option of the combobox, and depend of this option y want to print one label or other one. For example if I selected option->dni the label would be DNI: or if I selected option->nombre the label would be Nombre:
<div class="campos">
<div class="campo">
<form:label path="buscarPor">Buscar Por:</form:label>
<div>
<select name="buscarPor" id="buscarPor">
<option value="dni">DNI</option>
<option value="nombre">Nombre</option>
<option value="Departamento">Departamento</option>
<option value="Área de Conocimiento">Área de Conocimiento</option>
</select>
</div>
<script type="text/javascript">
function cargarLabel(){
var seleccionado = $(this).val();
if(seleccionado == 'dni'){
$('#seleccion').html('<div class="campo">'+'<form:label path="seleccion">DNI:</form:label>'+
'<div>'+'<form:input path="seleccion"/>'+'<form:errors path="seleccion"/>'+'</div>'+'</div>');
}if(seleccionado == 'nombre'){
$('#seleccion').html('<div class="campo">'+'<form:label path="seleccion">Nombre:</form:label>'+
'<div>'+'<form:input path="seleccion"/>'+'<form:errors path="seleccion"/>'+'</div>'+'</div>');
}
}
$(function () {
$('#buscarPor').change(cargarLabel);
});
</script>
</div>
<div class="campo">
<form:label path="seleccion">??</form:label>
<div>
<form:input path="seleccion"/>
<form:errors path="seleccion"/>
</div>
</div>
Solution
First things first, change the path
attribute of your <form:label path="buscarPor">Buscar Por:</form:label>
to something else. Spring tag library generates an id
attribute of the same value and that will directly conflict with the id
attribute of your select tag. That is the reason why in your current code, jquery is selecting your label
tag instead of the select
tag and binding the change
event to it.
That said, also take a look at this JSFiddle for the correct way to approach this problem. I think your approach is too verbose and you can do yourself a favor by avoiding all those if/else blocks.
Answered By - Ganeshji Marwaha
Answer Checked By - Robin (JavaFixing Admin)