On page load, I populate a Select2 Select->Option
list and I bind the change
event using the technique here Jquery: bind load + change simultaneously so that I can control the change event to load other information. Now, this all works well except that, and this is the problem.
After populating the Select->Option
list with the function fillProjectSelect();
the first option in the list appears as the default text which means that a change event on the item that is shown will not trigger because it is not a change. Naturally, this causes a great deal of confusion.
So the question is how can I force the Select2 option text to display the list title, which happens to be Select a Project
and not the first element in the list?
Here is a code fragment:
fillProjectSelect();
$( "#projectSelector" ).bind ('change', function () {
var val = $("#projectSelector").val();
$( "#project_description" ).text( projectData[val].description );
$( "#contract_sum" ).text( projectData[val].contract_sum );
$( "#percentage_fee" ).text( projectData[val].percentage_fee );
$( "#fee" ).text( projectData[val].fee );
var project_ID = projectData[val].project_ID;
etc...
})
Just in case it is helpful, I have also added the fillProjectSelect()
code.
function fillProjectSelect() {
var projectIndex = 0;
getProjectData(function(data) {
console.log(data)
var combo = $(".myselect")[projectIndex];
for (var i = 0; i < data.projectData.length; i++) {
projectData[i] = data.projectData[i];
var option = document.createElement("option");
option.setAttribute("value",i);
// option.setAttribute("selected",true);
option.innerHTML=projectData[i].name;
combo.appendChild(option);
}
});
}
Just in case anyone is interested, there is a bit of a hack that appears to work. What you do is set the first element's value to -1 and the option text to "Pick a Project" and then then remove it during the click event with
$(".myselect option[value='-1']").each(function() {
$(this).remove();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.