Reputation: 1261
There is a webpage with certain number of required fields that needs to be filled in order to submit a form successfully. The biggest indicator of required field is that it has a * and its label has a class 'required' in it. The number of required fields change when we change dropdown value. I have written some javascript and jquery code that changes the dropdown value and then checks the number of required fields but for some reason(most probably DOM changes is taking time and code executes before that so actually the change in number of required fields is not reflected in page). However if I change the dropdown value manually and then run the checkRequired() function, it works fine but I want to automate the procedure. How can I achieve that?
var count = 0;
var allRequired = []; // total number of required fields in the page
var newRequired = []; // change in the no. of required fields
$('select').each(function(){
var id = $(this).attr('id');
$('#'+id+' option').each(function() {
$(this).attr('selected','selected');
if(count == 0){
getAllRequiredFields();
}
else{
setTimeout(() => {
checkRequired();
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',allRequired[index]);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}, 3000);
}
count++;
})
});
function getAllRequiredFields(){
$('span.required').each(function () {
var text = $(this).parent().text()
var id = $(this).closest("td").attr('id').split("_label")[0];
allRequired.push(id);
});
}
function checkRequired() {
newRequired = [];
$('span.required').each(function () {
var text = $(this).parent().text()
var id = $(this).closest("td").attr('id').split("_label")[0];
newRequired.push(id);
});
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',count);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}
Upvotes: 0
Views: 49
Reputation: 1261
Just added change event fixed my problem
$('#'+id+' option').each(function() {
$(this).attr('selected','selected');
$('#'+id).change();
if(count == 0){
getAllRequiredFields();
}
else{
setTimeout(() => {
checkRequired();
for (let index = 0; index < allRequired.length; index++) {
console.log('for else',allRequired[index]);
if(!newRequired.includes(allRequired[index])){
console.log('allRequired',allRequired[index]);
}
}
}, 3000);
}
count++;
})
Upvotes: 4