I’ve got a form that allows adding and removing dropdown lists dynamically using JavaScript. I want to populate an input with name "nombre" according to dropdown selection. I can fetch the name for the select ID from an MySQL table, but I don’t how to populate input with the name.
This is the JavaScript code for adding the dropdown list dynamically (idmedico) and the input to populate (nombre):
var fila='<tr class="filas" id="fila'+cont+'">'+
'<td><button type="button" class="btn btn-danger" onclick="eliminarDetalle('+cont+')">X</button></td>'+
'<td><select name="idmedico[]" class="form-control idmedico" onchange="myFunction(this.value)" required><option value="" >Seleccione Cuenta</option><?php echo seleccionar_medico($connect); ?></select></td>'+
'<td><input type="text" id="nombre[]" name="nombre[]" value=""></td>'+
'</tr>';
cont++;
detalles++;
$('#detalles').append(fila);
I can fetch the name (nombre) according the ID selected on the dropdown list. For onchange
, I have the following JavaScript function:
function myFunction(idmedico) {
$.ajax({
url: "traer_nombre_medico.php",
type: "POST",
dataType: "json",
data: { idmedico: idmedico },
success: function (data) {
alert(data.nombre);
},
error: function (errorThrown) {
alert(errorThrown);
},
});
}
But I don’t know how to fill the input with name (id="nombre[]"
) fetched:
'<td><input type="text" id="nombre[]" name="nombre[]" value=""></td>'+
Please, any ideas?
2
Answers
Thanks for your answer bhishek Kumar.
I tried your code, but when I make a selection in the dropdown list (class .medico) I never go to JavaScript function (medico).
This is my code with the dropdown list and the input:
This my JavaScript function:
For trying I put just an alert on my JavaScript function but I reach that function:
For Trying If I use onchange in the dropdown list I can go to JavaScript function and there in the JavaScript function put the name fetched manually in input it works:
JavaScript Function myFunction:
I don't know how to pass to javascript function the counter variable
cont
and idmedico (at same time) for populatingid="nombre_'+cont+'"
try this code this will work . use Jquery change event on .medico class which will work as same your onchange event also each nombre input is given unique id based on your cont variable which can be used in data-id attribute for further usage. check below code.
javascript function