mardi 23 décembre 2014

How to get selected item in Bootstrap 3 dynamic dropdown modal dialog from javascript.


I am using Bootstrap 3 to show a modal dialog with at dropdown selection. The dropdown allows the user to select a page in a pdf. It is dynamically populated just prior to showing the dialog. The dialog works well and the dropdown is correctly populated with page items.


enter image description here


See the working code here.





function choosePage(numPages) {
var pdfPageSelector = document.getElementById("pdfPageSelector");
for (var i = 1; i <= numPages; i++){
var opt = document.createElement("option");
var anchor = document.createElement("a");
anchor.href = "#";
anchor.id = "page_id";
var text = document.createTextNode("page " + i);
text.href = "#";
anchor.appendChild(text);
opt.appendChild(anchor);

anchor.onclick = function() {
alert('clicked');
};
pdfPageSelector.appendChild(opt);
}

$('#page_id').on('click', function(e){
alert('clicked');
e.preventDefault(); // Prevent the default anchor functionality
});

$('#page_id').click(function(e) {
alert('clicked');
e.preventDefault(); // Prevent the default anchor functionality
});

}

choosePage(3);



<script src="http://ift.tt/1oMJErh"></script>
<script src="http://ift.tt/1tSH0Pd"></script>
<!-- Modal -->
<div class="modal fade" id="pdfChooseModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Choose page to redact</h4>
</div>
<div class="modal-body">
<div>
Please choose page to redact.
</div>

<select class="form-control" id="pdfPageSelector">
</select>

</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="pageChosen()">Choose</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->



Bootstrap 3 changes the way that dropdown selections are implemented. I cannot figure out how read the index or value of the selected item. A fallback is to implement an event that is fired when the element is selected (the old Bootstrap 2 method doesn't work seem anymore).


I have tried adding onclick event handler in pure javascript:



var anchor = document.createElement("a");
anchor.id = "page_id";
anchor.onclick = function() {
alert('clicked');
};


I have tried adding .click and .on in jQuery:



$('#page_id').on('click', function(e){
e.preventDefault(); // Prevent the default anchor functionality.
alert('clicked');
});


or .click



$('#page_id').click(function(e) {
e.preventDefault(); // Prevent the default anchor functionality.
alert('clicked');
});


What am I missing?





Aucun commentaire:

Enregistrer un commentaire