I want to create element select with bootstrap class using button onclick. The element inserted into body, but not visible on page.
<html>
<head>
<link rel="stylesheet" href="../bootstrap-4.6.2-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bootstrap-select-1.13.14/dist/css/bootstrap-select.min.css" />
<script src="../jquery-3.7.1.min.js"></script>
<script src="../popper.min.js" ></script><!--https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js-->
<script src="../bootstrap-4.6.2-dist/js/bootstrap.min.js"></script>
<script src="../bootstrap-select-1.13.14/dist/js/bootstrap-select.min.js"></script>
<script>
function addElement(){
//normal
document.body.innerHTML += '<select>'+
'<option>Mustard</option>'+
'<option>Ketchup</option>'+
'</select>';
//using boostrap class
document.body.innerHTML+= '<select class="selectpicker" multiple data-live-search="true">'+
'<option>Mustard</option>'+
'<option>Ketchup</option>'+
'</select>';
}
</script>
</head>
<body>
<button type="button" id="addRowBottom" onclick='addElement()'>add row</button>
</body>
if put directly on html, it is visible with all styling.
<html>
<head>
<link rel="stylesheet" href="../bootstrap-4.6.2-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bootstrap-select-1.13.14/dist/css/bootstrap-select.min.css" />
<script src="../jquery-3.7.1.min.js"></script>
<script src="../popper.min.js" ></script><!--https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js-->
<script src="../bootstrap-4.6.2-dist/js/bootstrap.min.js"></script>
<script src="../bootstrap-select-1.13.14/dist/js/bootstrap-select.min.js"></script>
</head>
<body>
<select class="selectpicker" multiple data-live-search="true">
<option>Mustard</option>
<option>Ketchup</option>
</select>
</body>
2
Answers
As told by @CBroe, we have initialize via javascript to apply bootstrap class function on element when add element dynamically.
Here is a way to create options from an array using parameters passed to the function to determine if that is added to the new
<select>
element.I took the click off the button and put it in the code where it should be as a best practice.
Some notes and references at appropriate points in the code: