Reputation: 25
so I've read about callback and asynchronous behaviour of ajax but I can't figure out how to create an event from appended values from ajax.
I've got this html :
var searchRequest = null;
$(function() {
$(':input[type="submit"]').prop('disabled', true);
var minlength = 5;
$("#cp").keyup(function() {
var that = this,
value = $(this).val().trim();;
value = value.replace(/\s/g, '');
if (value.length == minlength) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "POST",
url: "post_job_ville.php",
data: {
'searchterm': value
},
dataType: "text",
success: function(msg) {
$("#ville").append(msg);
}
});
}
});
});
// Code to remove the disabled state of submit button
if ($('#ville').val()) {
$(':input[type="submit"]').prop('disabled', false);
$(':input[type="submit"]').toggleClass('btn-custom btn-primary');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input name="cp" id="cp" class="form-control">
</div>
<div class="form-group">
<select class="form-control" id="ville">
<option selected="selected" value="">Select a value</option>
</select>
</div>
<input type="submit" id="btn-login" class="btn btn-custom btn-lg btn-block" value="Submit">
My ajax call is working fine. When someone type 5 caracters in the input field (#cp) it triggers the ajax call and append
<option value="x">...</option>
to the select menu (#ville).
Problem is, I'd like to Jquery to remove the disable state of the submit button if an ajax called option with a value is selected. So i wrote the code at the end of the JS but since ajax is async it can't work like that. I tried to put the code in the success part of the ajax call but it didn't work.
If someone has an idea on how to proceed I'd really appreciate.
Thank you !
Upvotes: 1
Views: 123
Reputation: 316
You can try to place an event on your select like this:
$('#ville').on('change', function(e) {
if (e.target.value) {
$(':input[type="submit"]').prop('disabled', false);
/* other stuffs... */
} else {
$(':input[type="submit"]').prop('disabled', true);
/* other stuffs... */
}
})
The "on()" method from Jquery Selector allow you to place an event of your choice on the selected element. Here we place the 'change' event to call back a function when the input value 'change'. You just need to check if your selected value is not empty (like the first entry of your select) and it's done.
or something like that:
$('#ville').on('change', function(e) {
const value = e.target.value
$(':input[type="submit"]').prop('disabled', !value);
/* other stuffs... */
})
Upvotes: 3