Reputation: 5
I need help creating an html button from javascript using the bootstrap class and customization.
I have created a bootstrap button
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="btn btn-success" href="#" id="testbtn" onclick="javascript('ActionTxT1' , 'dropdownMenuButton', 'btn btn-success')">Action</a>
<a class="btn btn-warning" href="#" id="testbtn" onclick="javascript('ActionTxT2' , 'dropdownMenuButton', 'btn btn-warning')">Another action</a>
<a class="btn btn-danger" href="#" id="testbtn" onclick="javascript('ActionTxT3' , 'dropdownMenuButton', 'btn btn-danger')">Something else here</a>
</div>
</div>
I need to create loads of these from an mysql query . So using a for () loop I want to create buttons like these in a table's cell's , but first I need to figure out how to create the button.
So far I have
var btn = document.createElement("div");
btn.className = "btn btn-secondary dropdown-toggle";
btn.nodeType = "button";
btn.id = "testDropDownButton";
// btn.data-toggle = "dropdown";
but here I start getting errors and I am not sure if I am even heading in the right direction.
Upvotes: 0
Views: 732
Reputation: 355
You can look at the below jsfiddle- https://jsfiddle.net/ashhaq12345/xpvt214o/1025242/
function createButton() {
var div = document.createElement("div");
var button = document.createElement("button");
button.className = "btn btn-secondary dropdown-toggle";
button.id = "dropdownMenuButton";
button.setAttribute("data-toggle", "dropdown");
button.setAttribute("aria-haspopup", "true");
button.setAttribute("aria-expanded", "false");
button.innerText="Dropdown button";
div.append(button);
div.className="dropdown";
var linkDiv = document.createElement("div");
linkDiv.className="dropdown-menu";
linkDiv.setAttribute("aria-labelledby","dropdownMenuButton");
var a = document.createElement("a")
a.href="#"
a.className="btn btn-success"
a.id="testbtn"
a.setAttribute("onclick", "javascript('ActionTxT1' , 'dropdownMenuButton', 'btn btn-success')")
a.innerText="Action"
linkDiv.append(a);
div.append(linkDiv);
$(".main-div").append(div);
}
Upvotes: 1
Reputation: 4764
You're likely getting errors when setting an attribute with a dash in it:
btn.data-toggle = "dropdown";
To set attributes, you have three options:
1) Use the setAttribute()
method:
btn.setAttribute('data-toggle', "dropdown");
2) Set the attribute in the dataset
property:.
btn.dataset['data-toggle'] = "dropdown";
3) Use camelCase notation:
btn.dataset.dataToggle = "dropdown";
When your element is built, add it an existing element using the appendChild
method:
let div = document.getElementById('mydiv');
div.appendChild(btn);
To create the entire Bootstrap dropdown in JS, you'll be repeating this process for each child element.
Upvotes: 0