Reputation: 622
I am trying to make an ajax request which would change the content of my select.
Here is my request :
$(function() {
$("#client").change(function() {
type: 'GET',
url: "jsonContacts.php",
dataType: "json",
data: {
q: $("#client").val()
},
success: function(data) {
document.form.contactClient.options.length=0;
document.form.contactClient.options[0]=new Option("Test", "test", true, false);
for(var i=0; i<data.length; i++) {
}
}
});
});
My form is :
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form' onsubmit="return validateForm()" >
<p>
<label for="client">Client</label>
<input type='text' id='client' name='client' required>
</p>
<p>
<label for="contactClient">Contact client</label>
<SELECT name="contactClient" id="contactClient">
</SELECT>
</p>
</form>
I would like that when the text of 'client' change, the request change the data of my SELECT but, my test Option isn't displayed at all.
Thanks!
Upvotes: 0
Views: 54
Reputation: 1014
Listen to the keyup event beside the change event on textbox. You can do it like
$(function() {
$("#client").keyup(function() {
type: 'GET',
url: "jsonContacts.php",
dataType: "json",
data: {
q: $("#client").val()
},
success: function(data) {
var html = '';
$.each(data,function(i,k){
html += '<option value="'+k.val+'">'+k.text+'</option>';
});
$('#contactClient').html(html);
}
});
});
Hope it helps you.
Upvotes: 0
Reputation: 7878
As you are using jQuery already you can do it like this:
$('#contactClient').append($('<option>', {
value: 'Test',
text: 'test',
selected: true
}));
Upvotes: 1
Reputation: 4508
If you're going with jQuery might as well use it for populating the select too.
success: function(data) {
$("#contactClient").html("");
$("#contactClient").append("<option value='test' selected>Test</option>");
for(var i=0; i<data.length; i++) {
}
}
Upvotes: 0