I have this jquery.ajax form which populates data from the database and auto fills the form fields upon button click.
It works great when the form field is of type text
But it does not auto fill when the form field is a select box.
here is my code so far..
<script type="text/javascript">
$(document).ready(function() {
function myrequest(e) {
var lead_id = $('#lead_id').val();
$.ajax({
method: "GET",
url: "/pdp/fetch-client-data/",
dataType: 'json',
cache: false,
data: {
lead_id: lead_id
},
success: function( responseObject ) {
alert('success');
$('#client_name').val( responseObject.client_name );
$('#state').val(responseObject.state);
},
failure: function()
{
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
$("#lead_id").bind("change", function(e)
{
myrequest();
});
});
</script>
<table width="600" align ='center'>
<form action ='<?php echo $SERVER['PHP_SELF']; ?>' method='post'>
<tr>
<td>
<label for="lead_id">Lead id: </label>
<input type="text" name="lead_id" id="lead_id">
<button id="fetchFields">Fetch</button>
</td>
</tr>
<tr>
<td>
Agent: <select name="agent">
<option value="">[Select]</option>
<?php foreach($this->agent_query as $agent){ ?>
<option value="<?php echo $agent['id']; ?>"><?php echo $agent['name'];?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>
<label for="client_name">Client Name: </label>
<input type="text" name="client_name" id="client_name">
</td>
</tr>
<tr>
<td>
<label for="state">State: </label>
<select name="state" id='state'>
<option id='state' value='1'></option>
</select>
</td>
</tr>
<tr>
<td>
# of Policies:
<select name="policies">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="NEXT" name="submit">
</td>
</tr>
</form>
</table>
When you say
Do you mean to fill the
<select>with a list of data from server-side or to select an<option>that is already on the<select>?If your case is that you want to fill the
<select>then you have to create each node that represents each<option>filled with its corresponding array item that you brought from server-side. Ex.If what you want is to select an
<option>that is already on your<select>then you need to iterate over your current options and either apply it the ‘selected’ attribute or set the<select>‘s selectedIndex as the index of the option you want to select. For example: