jQuery fire function when previous <select> is enabled
I have three <select>
elements.
- Select 1
- Select 2
- Select 3
Select 1 is enabled, while Select 2 & 3 are disabled by default, as they depend on their "previousSibling".
Select 1 is populated with options coming from a MySQL query. When one of this options is selected, the following code enables Select 2 and populates it with an AJAX call:
$("#select1").change(function(){
var id = $(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: './php/selectProperty.php?nocache=' +
(new Date()).getTime(),
data: dataString,
cache: false,
async: false,
success: function(html){
$("#select2").html(html);
$('#select2').prop("disabled", false);// Element(s) are now enabled.
}});
});
Although Select3 follows the same methodology ($("#select2").change(function()...
) it is not being enabled or populated, as I can imagine that the change method expects an explicit change from the user's side and not just a change in the DOM. Because sometimes Select 2 has only one option, change() will never fire.
Is there an alternative method for firing the population of Select 3 and enable it? For example, when Select 2 lose its disabled property?
Answer
1st: you need to use .on()
$("#select2").on('change',function(){});
or
$("body").on('change', '#select2' ,function(){});
but I think the .on() will work
2nd: to make just one code for all of them
$('select[id^="select"]').on('change',function(){
var ThisIt = $(this);
var id= ThisIt.val();
var getNextSelect = ThisIt.next('select[id^="select"]');
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: './php/selectProperty.php?nocache=' + (new Date()).getTime(),
data: dataString,
cache: false,
async: false,
success: function(html){
getNextSelect.html(html).promise().done(function(){
getNextSelect.prop("disabled", false); // Element(s) are now enabled.
});
}
});
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM