show selected option in dropdown javascript - javascript

I have implemented the nav bar and how to show the selected options first using javascript
function getoptions(){
var x =document.getElementById("languagelist");
var y = document.getElementById("language");
y.innerHTML= // set the selected language
}
<nav>
<div class="dropdown">
<button id="language" class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
English
</button>
<div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="getoptions()">
<a class="dropdown-item" href="/en">English</a>
<a class="dropdown-item" href="/fr">French</a>
</div>
</div>
</nav>

This pure javascript solution would work for you. run and test
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<nav>
<div class="dropdown">
<button id="language" class="btn btn-warning dropdown-toggle" type="button" id="dropdownMenu2"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="clickButton()">
English
</button>
<div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="clickItem(); return false">
<a class="dropdown-item" href="/en">English</a>
<a class="dropdown-item" href="/fr">French</a>
</div>
</div>
</nav>
</body>
<script>
function clickButton() {
document.getElementById("languagelist").click();
}
function clickItem() {
var element = document.getElementById("languagelist");
for (var i = 0; i < element.children.length; i++) {
(function(index) {
element.children[i].onclick = function() {
var thetext = element.getElementsByTagName('a')[index].innerHTML;
// var thehref = element.getElementsByTagName('a')[index].href; get the href here once you hosted, for testing I will use the name
var buttonelement = document.getElementById("language");
buttonelement.innerText = thetext;
window.open("/"+thetext);
}
})(i);
}
}
</script>
</html>
hope this will help to someone. cheers!

You can use this code
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li>Action</li>
<li>Another action</li>
<li>Something else here</li>
<li>Separated link</li>
</ul>
</div>
<script type="text/javascript">
$(".dropdown-menu li a").click(function(){
alert($(this).data('value'));
});

Add data attribute and identify the element,
<nav>
<div class="dropdown">
<button id="language" class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
English
</button>
<div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" >
<a class="dropdown-item" data-value="/en" href="/en">English</a>
<a class="dropdown-item" data-value="/fr" href="/fr">French</a>
</div>
</div>
</nav>
script like this,
remove element and add as first item
$(".dropdown-item").click(function () {
var value = $(this).data('value');
var innerHtmlValue = $(this).html();
$('.dropdown-item').filter('[data-value="' + value + '"]').remove();
$('#languagelist a:eq(0)').before("<a class='dropdown-item' data-value='" + value + "' href='/en'>" + innerHtmlValue + "</a>");
});

Related

How to console selected dropdown option using <ul> <li>

In this code i am not able to console the selected dropdown in console.
HTML
<div class="dropdown"><button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
Dropdown
</button>
<ul class="dropdown-menu" (change)="selectChangeHandler($event)">
<li class="dropdown-item" *ngFor="let option of selectedDay">{{option}}</li>
</ul>
</div>```
TS.
selectedDay = ['GCP','Azure','AWS'];
selectChangeHandler(event: any) {
this.selectedDay = event.target.value;
console.log(this.selectedDay)
}
You can not add change event to ul tag, you need change ul/li tag to select/option tag. And you should distint between selectedDay and listSelectedDay variable.
HTML
<div class="dropdown">
<button
type="button"
class="btn btn-primary dropdown-toggle"
data-bs-toggle="dropdown"
>
Dropdown
</button>
<select class="dropdown-menu" (change)="selectChangeHandler($event)">
<option class="dropdown-item" *ngFor="let option of listSelectedDay">
{{ option }}
</option>
</select>
</div>
TS
export class AppComponent {
listSelectedDay = ['GCP', 'Azure', 'AWS'];
selectedDay = '';
selectChangeHandler(event: any) {
this.selectedDay = event.target.value;
console.log(this.selectedDay);
}
}
Demo code https://stackblitz.com/edit/angular-ivy-tapafd
May be You can use button for that code for e.g
----HTML----
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1" name="selected" >
<li><a class="dropdown-item" data-bs-toggle="modal" *ngFor="let option of Menu">
<button class="btn btn-secondary" type="button" (click)="selectedChanged(option)">{{option}}</button>
</a></li>
</ul>
</button>

How to change the value of parent when i trigger a child?

I want to do something like a dropdown so that my user can pick whether they want gmail, hotmail, or outlook. And then, I want the button to update to show their preference. I must use bootstrap only and thus cannot use < select> due to assignment reasons.
So far, I've tried giving them all the same id, but JS just used the first one, and i dont want to give them all different IDs (too troublesome). So what I've written is to use the child number (like an array) and putting the value into the button. However, I have no idea how to find out the position number of the current html tag. Please help me and thank you for the help in advance
Bootstrap CDN used (Bootstrap 4.6.0):
link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button' onclick='example()'>#gmail.com</a>
<a class="dropdown-item" role='button' onclick='example()'>#hotmail.com</a>
<a class="dropdown-item" role='button' onclick='example()'>#outlook.com</a>
<a class="dropdown-item" role='button' onclick='example()'>#yahoo.com</a>
</div>
</div>
<script>
function example() {
var c = document.getElementById('emailexample').children;
txt = c[i].textContent
document.getElementById("btnemailexample").innerHTML = txt;
}
</script>
This should do the trick!
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id='btnemailexample' data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
#example.com
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#gmail.com</a>
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#hotmail.com</a>
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#outlook.com</a>
<a class="dropdown-item" href="#" role='button' onclick='example(this)'>#yahoo.com</a>
</div>
</div>
<script>
function example(el) {
var txt = el.textContent;
document.getElementById("btnemailexample").innerHTML = txt;
}
</script>
In your case you don't need the search the id or the children, you can just use the event param.
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button' onclick='example(event)'>#gmail.com</a>
<a class="dropdown-item" role='button' onclick='example(event)'>#hotmail.com</a>
<a class="dropdown-item" role='button' onclick='example(event)'>#outlook.com</a>
<a class="dropdown-item" role='button' onclick='example(event)'>#yahoo.com</a>
</div>
</div>
<script>
function example(event) {
var txt = event.target.textContent;
document.getElementById("btnemailexample").innerHTML = txt;
}
</script>
A best solution in this case would be to use event delegation which will reduce your ID or Classes markup issue, adding function to every element, etc. It will help you get your required data as well.
Here is a good article on event delegation
You could do this a lot better if you have some JavaScript library like jQuery. I'll show you how to do it by both means.
Please note that I have not linked any styles. So make sure to link them for better viewability.
Using Core Javascript
// Add event listener to table
const el = document.getElementById("emailexample");
el.addEventListener("click", function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
document.getElementById("btnemailexample").textContent = text;
}, false);
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button'>#gmail.com</a>
<a class="dropdown-item" role='button'>#hotmail.com</a>
<a class="dropdown-item" role='button'>#outlook.com</a>
<a class="dropdown-item" role='button'>#yahoo.com</a>
</div>
</div>
Using jQuery
$("#emailexample .dropdown-item").on('click', function(e) {
e.preventDefault();
var text = $(this).text();
$("#btnemailexample").text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='btnemailexample'>#example.com</button>
<div class="dropdown-menu" id='emailexample'>
<a class="dropdown-item" role='button'>#gmail.com</a>
<a class="dropdown-item" role='button'>#hotmail.com</a>
<a class="dropdown-item" role='button'>#outlook.com</a>
<a class="dropdown-item" role='button'>#yahoo.com</a>
</div>
</div>

Trying to get the Bootstrap dropdown button text to change to the item selected

I'm using bootstrap to style a dropdown button and I'd like to have the button text change to whatever item is selected from the dropdown. I'm guessing JavaScript is the best way to make this happen, but I'm not that familiar with it yet. Any help would be greatly appreciated.
Here is my html for the first dropdown button. Thanks
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Genre
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu1">
<button class="dropdown-item" type="button">Adventure</button>
<button class="dropdown-item" type="button">Sci-Fi</button>
<button class="dropdown-item" type="button">Comedy</button>
</div>
#finiteloop thanks for your help. Based on the direction you pointed me in I added an onclick event for each dropdown element and added the following function which does what I need:
<div class="dropdown mx-3">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Genre
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu1">
<button class="dropdown-item" type="button" onclick="showGenre(this)">Adventure</button>
<button class="dropdown-item" type="button" onclick="showGenre(this)">Sci-Fi</button>
<button class="dropdown-item" type="button" onclick="showGenre(this)">Comedy</button>
</div>
</div>
function showGenre(item) {
document.getElementById("dropdownMenu1").innerHTML = item.innerHTML;
}
#MasterShake20 you could do something like this and integrate it into your code:
<!DOCTYPE html>
<html>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
<p>Click the button to change the selected fruit to banana.</p>
<button id="btnTxt" type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
let buttonVal = document.getElementById("mySelect").value;
document.getElementById('btnTxt').innerHTML = buttonVal;
}
</script>
</body>
</html>
See how this works here:
https://www.w3schools.com/code/tryit.asp?filename=GI7I2WCF1N82
This is not exactly what you are trying to do, but it could set you in the right direction and give you an idea of what needs to happen.
Also, if you are just starting out, W3 is a great resource, so check their JavaScript Tutorials out here:
https://www.w3schools.com/js/default.asp
:D
with jquery is easy:
<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Number
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">1</a></li>
<li><a class="dropdown-item" href="#">2</a></li>
<li><a class="dropdown-item" href="#">3</a></li>
</ul>
<script>
$(".dropdown-toggle").next(".dropdown-menu").children().on("click",function(){
$(this).closest(".dropdown-menu").prev(".dropdown-toggle").text($(this).text());
});
</script>
if you have more components in your page and want this behavior for specifics components,
add an property to correct select only its:
(in this example, add property changeable="true")
<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" changeable="true">
Number
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">1</a></li>
<li><a class="dropdown-item" href="#">2</a></li>
<li><a class="dropdown-item" href="#">3</a></li>
</ul>
<script>
$(".dropdown-toggle[changeable=true]").next(".dropdown-menu").children().on("click",function(){
$(this).closest(".dropdown-menu").prev(".dropdown-toggle").text($(this).text());
});
</script>
$(".dropdown-toggle").next(".dropdown-menu").children().on("click", function() {
$(this).closest(".dropdown-menu").prev(".dropdown-toggle").text($(this).text());
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Number
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">1</a></li>
<li><a class="dropdown-item" href="#">2</a></li>
<li><a class="dropdown-item" href="#">3</a></li>
</ul>

Selected value in drop down returning undefined in javascript

I'm trying to select a value from the drop down and pass the value in the JavaScript function. But in the JavaScript function i'm getting the value undefined. How can i resolve this?
Here goes the html
<div class="input-group-btn search-panel">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span id="search_concept">All</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" id="chooser" role="menu" onclick="dropDown_chooser()">
<li value="type">Type</li>
<li value="loc">Location</li>
<li value="name">Name</li>
<li value="sal">Salary</li>
</ul>
</div>
and the javaScript
function dropDown_chooser() {
var select = document.getElementById("chooser");
var select_val = select.value;
console.log("select val" + select_val);
}
var dropdown = document.querySelectorAll('#chooser > li');
dropdown.forEach(function(item){
item.addEventListener('click',function(){
console.log(this.getAttribute('value'));
})
})
<div class="input-group-btn search-panel">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span id="search_concept">All</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" id="chooser" role="menu">
<li value="type">Type</li>
<li value="loc">Location</li>
<li value="name">Name</li>
<li value="sal">Salary</li>
</ul>
</div>
I guess you are using bootstrap by looking at the classes you have used; you can go with the following code then
<div class="input-group-btn search-panel">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span id="search_concept">All</span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="chooser" role="menu">
<li value="type">Type</li>
<li value="loc">Location</li>
<li value="name">Name</li>
<li value="sal">Salary</li>
</ul>
</div>
And using jQuery
$(document).ready(function(e){
$('.search-panel .dropdown-menu').find('a').click(function(e) {
e.preventDefault();
var param = $(this).parent('li').attr("value");
var concept = $(this).text();
$('.search-panel span#search_concept').text(concept);
console.log("select val = " + param);
});
});
As stated in the comments, this is not a dropdown menu ,using "select" and
"option" is the proper way and you should use "onchange" instead of "onclick".
I posted it, like this it works, hope this helps!
function getvalue(){
var skillsSelect = document.getElementById("chooser");
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
console.log(selectedText);
alert(selectedText);
}
<div class="input-group-btn search-panel">
<select class="dropdown-menu" id="chooser" role="menu"
onchange="getvalue()">
<option value="type"><a href="#">Type</option>
<option value="loc"><a href="#">Location</option>
<option value="name"><a href="#">Name</option>
<option value="sal"><a href="#">Salary</option>
</select>
</div>
.

bootstrap drop down button aligns on the wrong side

When you click on the dropdown ul, the list items (<li>) are shown all the way to the left..
As you can see in my simplified jfiddle example:
http://jsfiddle.net/3bfvvkbh/
<div>
<div class="btn-group">
<button type="button" class="btn btn-info">random button</button>
<button type="button" class="btn btn-info">random button</button>
<button type="button" class="btn btn-info">random button</button>
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="d``ropdown" aria-expanded="false"> <span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul id="yearlist" class="dropdown-menu" role="menu">
<li> <a>2010</a>
</li>
</ul>
</div>
</div>
$(document).ready(function() {
$(function() {
var append = function( txt ) {
$("#yearlist").append( '<li>' + txt + '</li>' );
};
append("<a>2012</a>");
append("<a>2014</a>");
});
});
The dropdown has be in a seperate btn-group.
See my updated fiddle and also the Bootstrap Docs - #Nested Button groups
$(document).ready(function () {
$(function () {
var append = function (txt) {
$("#yearlist").append('<li>' + txt + '</li>');
};
append("<a>2012</a>");
append("<a>2014</a>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<div>
<div class="btn-group">
<button type="button" class="btn btn-info">random button</button>
<button type="button" class="btn btn-info">random button</button>
<button type="button" class="btn btn-info">random button</button>
<div class="btn-group">
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul id="yearlist" class="dropdown-menu" role="menu">
<li> <a>2010</a>
</li>
</ul>
</div>
</div>
</div>
Add this Class dropdown-menu-right in the UL tag, class="dropdown-menu dropdown-menu-right", Demo
<ul id="yearlist" class="dropdown-menu dropdown-menu-right" role="menu">
<li> <a>2010</a>
</li>
</ul>
Instead of using the button tag like you're using in the example rather use a div with a .btn-group class.
<div class="btn-group">
Dropdown
<span class="caret"></span>
<ul class="dropdown-menu">
<li>Action</li>
<li>Another action</li>
<li>Something else here</li>
<li class="divider"></li>
<li>Separated link</li>
</ul>
</div>
http://jsfiddle.net/3bfvvkbh/2/
Everything else is perfect but you just missed to take one extra btn-group to bind button and toggling menu
See: http://jsfiddle.net/3bfvvkbh/6/
$(document).ready(function () {
$(function () {
var append = function (txt) {
$("#yearlist").append('<li>' + txt + '</li>');
};
append("<a>2012</a>");
append("<a>2014</a>");
});
});

Categories

Resources