Keep current bootstrap menu open when the input is on focus - javascript

I have many (dynamic) input with each having its own dropdown
I want to keep the dropdown popup in focus when the current input is active/being typed , now the issue is my dropdown menu closes when I type in textbox
I cannot use ID selector and hard code since the number of dropdowns are dynamic.
I have tried with
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="input-group input-group-sm ">
<input type="text" class="form-control" aria-label="Text input with segmented dropdown button">
<div class="input-group-append input-group-sm">
<button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu">
<input type="text" placeholder="Search.." id="myInput" class="search">
<a class="dropdown-item" data-value="{{Action}}" href="#">Action</a>
<a class="dropdown-item" data-value="{{Another action}}" href="#">Another action</a>
<a class="dropdown-item" data-value="{{Something else here}}" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" data-value="{{Separated lin}}" href="#">Separated link</a>
</div>
</div>
</div>
<div class="input-group input-group-sm ">
<input type="text" class="form-control" aria-label="Text input with segmented dropdown button">
<div class="input-group-append input-group-sm">
<button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu">
<input type="text" placeholder="Search.." class="search">
<a class="dropdown-item" data-value="{{Action}}" href="#">Action</a>
<a class="dropdown-item" data-value="{{Another action}}" href="#">Another action</a>
<a class="dropdown-item" data-value="{{Something else here}}" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" data-value="{{Separated lin}}" href="#">Separated link</a>
</div>
</div>
</div>
<div class="input-group input-group-sm ">
<input type="text" class="form-control" aria-label="Text input with segmented dropdown button">
<div class="input-group-append input-group-sm">
<button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu">
<input type="text" placeholder="Search.." class="search">
<a class="dropdown-item" data-value="{{Action}}" href="#">Action</a>
<a class="dropdown-item" data-value="{{Another action}}" href="#">Another action</a>
<a class="dropdown-item" data-value="{{Something else here}}" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" data-value="{{Separated lin}}" href="#">Separated link</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
$(function(){
$('.dropdown-item').click(function(e){
var value = $(this).data('value');
var textElement = $(this).parent().parent().prev()
textElement = textElement.val(textElement.val() + value);
event.preventDefault();
event.stopPropagation();
textElement.focus()
});
});
$(".search").keyup(function(){
var input, filter, ul, li, a, i;
input = $(this).get(0);
filter = input.value.toUpperCase();
div = $(this).parent().get(0);
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
});
(function() {
var disable = false;
$('.dropdown-toggle').on('mousedown touchstart', function() {
disable = true;
console.log("inside1")
})
.on('focus', function() {
if (!disable) {
$(this).dropdown('toggle'); console.log("inside2")
}
})
.on('mouseup touchend',function() {
disable = false;console.log("inside3")
})
})()
</script>
</body>
</html>

$(document).ready(() => {
$(".input-group > input")
.on("focus", (e) => {
let inputEl = e.currentTarget;
let dropdownEl = inputEl.parentElement.querySelector(".dropdown-menu");
$(dropdownEl).show();
})
.on("blur", (e) => {
// If click outside the input, check for condition to hide the dropdown
let inputEl = e.currentTarget;
let dropdownEl = inputEl.parentElement.querySelector(".dropdown-menu");
let dropdownSearchEl = dropdownEl.querySelector('.search');
if (e.relatedTarget == dropdownSearchEl) {
// Check if the target is the input insdie dropdown, then return to prevent the dropdown hiding
return;
}
$(dropdownEl).hide();
})
.on('keyup', (e) => {
let inputEl = e.currentTarget;
let dropdownEl = inputEl.parentElement.querySelector(".dropdown-menu");
let dropdownSearchEl = dropdownEl.querySelector('.search');
// Un-comment here if you want to set the value of the dropdown input as the value of the actual input
// dropdownSearchEl.value = inputEl.value;
});
$(".search")
.on("blur", (e) => {
// When click outside the dropdown search input, hide the dropdown
let dropdownInputEl = e.currentTarget;
let dropdownEl = dropdownInputEl.parentElement;
$(dropdownEl).hide();
})
.on("keyup", function() {
var input, filter, ul, li, a, i;
input = $(this).get(0);
filter = input.value.toUpperCase();
div = $(this).parent().get(0);
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
});
});
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="input-group input-group-sm ">
<input type="text" class="form-control" aria-label="Text input with segmented dropdown button">
<div class="input-group-append input-group-sm">
<button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu">
<input type="text" placeholder="Search.." id="myInput" class="search">
<a class="dropdown-item" data-value="{{Action}}" href="#">Action</a>
<a class="dropdown-item" data-value="{{Another action}}" href="#">Another action</a>
<a class="dropdown-item" data-value="{{Something else here}}" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" data-value="{{Separated lin}}" href="#">Separated link</a>
</div>
</div>
</div>
<div class="input-group input-group-sm ">
<input type="text" class="form-control" aria-label="Text input with segmented dropdown button">
<div class="input-group-append input-group-sm">
<button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu">
<input type="text" placeholder="Search.." class="search">
<a class="dropdown-item" data-value="{{Action}}" href="#">Action</a>
<a class="dropdown-item" data-value="{{Another action}}" href="#">Another action</a>
<a class="dropdown-item" data-value="{{Something else here}}" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" data-value="{{Separated lin}}" href="#">Separated link</a>
</div>
</div>
</div>
<div class="input-group input-group-sm ">
<input type="text" class="form-control" aria-label="Text input with segmented dropdown button">
<div class="input-group-append input-group-sm">
<button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu">
<input type="text" placeholder="Search.." class="search">
<a class="dropdown-item" data-value="{{Action}}" href="#">Action</a>
<a class="dropdown-item" data-value="{{Another action}}" href="#">Another action</a>
<a class="dropdown-item" data-value="{{Something else here}}" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" data-value="{{Separated lin}}" href="#">Separated link</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</script>
</body>
</html>
Since you are using Bootstrap dropdown, you can use its Popover methods to toggle show/hide the dropdown Bootstrap Popover.
The steps I do to achieve what you want:
Assign event focus and blur on the input to show/hide the dropdown. Inside the blur event, I check for the condition if the user click on the dropdown's input, then still keep the dropdown opening
Assign the event blur on the dropdown input to hide the dropdown
Ps: Using the jQuery event you can get the related DOM element, to experiment a little bit further, you can log the event then use the Devtool to look for the element you want to get. As you can see, in the script, I use event.currentTarget to get the element that the user click on. That's solve the problem.

Related

jQuery Hide result data if no dropdown selected

i have a dropdown day and month that work well if selected, my problem is my jquery.. when i clicked a button, if i not select the dropdown it show the function text instead of none text. how i can change the function display to a text 'none'
example below:
<button type="button" class="btn btn-secondary dropdown-toggle" id="example-day2-button" name="psptexMont" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-flip="false" style="background-color: #007e90;border-color: #fff;width:140px" placeholder="month"></button>
<div class="dropdown-menu" aria-labelledby="example-day2-button">
<div class="hs-searchbox">
<input type="text" class="form-control" autocomplete="on">
</div>
<div class="hs-menu-inner">
<a onclick="btnDay1.call(this);" class="dropdown-item" data-value="" data-default-selected="" href="#">1</a>
<a onclick="btnDay1.call(this);" class="dropdown-item" data-value="1" href="#">2</a>
<a onclick="btnDay1.call(this);" class="dropdown-item" data-value="3" href="#">3</a>
<a onclick="btnDay1.call(this);" class="dropdown-item" data-value="4" href="#">4</a>
</div>
<button type="button" class="btn btn-secondary dropdown-toggle" id="example-month1-button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-flip="false" style="background-color: #007e90;border-color: #fff;width:140px" placeholder="month"></button>
<div class="dropdown-menu" aria-labelledby="example-month1-button">
<div class="hs-searchbox">
<input type="text" class="form-control" autocomplete="on">
</div>
<div class="hs-menu-inner">
<a onclick="btnMonth.call(this);" class="dropdown-item" data-value="" data-default-selected="" href="#" value="January">January</a>
<a onclick="btnMonth.call(this);" class="dropdown-item" data-value="1" href="#">February</a>
<a onclick="btnMonth.call(this);" class="dropdown-item" data-value="2" href="#">March</a>
<a onclick="btnMonth.call(this);" class="dropdown-item" data-value="3" href="#">April</a>
</div>
<script>
function btnDay() {
window.btnDay = this.textContent || this.innerText;
}
$(document).on('click', '#infoNext', function(){
var year = document.getElementById('year1').value;
var day = btnDay;
var month = btnMonth;
var dateExpired = day+" "+month+" "+year;
document.getElementById('dob').innerHTML = dateExpired
}
</script>
the error is below if i not select anything from the dropdown:
function btnDay() { window.btnDay = this.textContent || this.innerText; } function btnMonth() { window.btnMonth = this.textContent || this.innerText; }

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>

how to get dropdown-menu item value and apend to text input?

I want to change the value of a text box with the item I select from a dropdown menu. But it's not working.
<input class="dropdown-toggle" type="text" name="area-zone" id="area-zone"
data-toggle="dropdown">
<div class="dropdown-menu" role="menu" aria-labelledby="area-zone">
<a class="dropdown-item" href="#">Jway</a>
<a class="dropdown-item" href="#">Atrod</a>
</div>
This is my jquery code:
$('.dropdown-item').click(function (){
$('#area-inout').val() = $('.dropdown-item').text();
})
Can anyone help me?
try :
$('.dropdown-menu .dropdown-item').on('click', function(){
$("#area-zone").val($(this).text())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="dropdown">
<input class="dropdown-toggle" type="text" name="area-zone" id="area-zone"
data-toggle="dropdown">
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Jway</a></li>
<li><a class="dropdown-item" href="#">Atrod</a></li>
</ul>
</div>
Try this
$('.dropdown-menu .dropdown-item').on('click', function(){
$("#area-zone").val($(this).text())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="dropdown-toggle" type="text" name="area-zone" id="area-zone"
data-toggle="dropdown">
<div class="dropdown-menu" role="menu" aria-labelledby="area-zone">
<a class="dropdown-item d-area-input" href="#">Jway</a>
<a class="dropdown-item" href="#">Atrod</a>
</div>
Try this!
$("div#dropDownSelect").click(function(e){
document.getElementById('inputBox').value = e.target.innerHTML;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputBox" value="" class="dropdown-toggle" type="text" name="area-zone" id="area-zone"
data-toggle="dropdown">
<div id="dropDownSelect" class="dropdown-menu" role="menu" aria-labelledby="area-zone">
<a class="dropdown-item d-area-input" href="#">Jway</a>
<a class="dropdown-item" href="#">Atrod</a>
</div>
Please change the dorpdown_name with your selectbox name
<script>
$('select[name="dorpdown_name"]').change(function() {
$('#area-zone').val($(this).val());
})
</script>

Handle Bootstrap dropdown event in jQuery

I have markup for twitter bootstrap dropdown like below
<div class="dropdown" style="width: 300px !important;">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Source
</button>
<div class="dropdown-menu" id="SelectMe">
<a class="dropdown-item" href="#">CLE</a>
<a class="dropdown-item" href="#">SQL</a>
<a class="dropdown-item" href="#">FFILE</a>
<a class="dropdown-item" href="#">SampleAPI</a>
</div>
</div>
Now, added click event in dropdown using jquery as below
$('.dropdown-menu a').click(function () {
alert("Hi")
});
My click event is working but, I am not able to update the selected value in dropdown. How to do it?
$('.dropdown-menu a').click(function () {
$('button').text($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="dropdown" style="width: 300px !important;">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Source
</button>
<div class="dropdown-menu" id="SelectMe">
<a class="dropdown-item" href="#">CLE</a>
<a class="dropdown-item" href="#">SQL</a>
<a class="dropdown-item" href="#">FFILE</a>
<a class="dropdown-item" href="#">SampleAPI</a>
</div>
</div>
use $('button').text($(this).text()); to set value to button.
try this
$('.dropdown-menu a').click(function () {
$('button[data-toggle="dropdown"]').text($(this).text());
});
DEMO HERE

How to use Javascript if statement when linked with bootstrap dropdown menu

I've hit a wall with trying to get my JavaScript if statement to work when using bootstraps drop down menu.
Goal: There are 2 drop down menu's. The user will select one value from each, based on what the user selects something will happen. I've seen many examples using the method however bootstrap seems to be a bit different. Also, I've seen a lot of people recommend jQuery because it's easier but I prefer to use Javascript (I'm learning). If someone can point me in the right direction I would appreciate it, or if my approach is totally off base please kindly let me know the right approach. Also, I currently don't have the "id" in my html because I'm not sure where to put it. Cheers.
HTML:
<!--Drop down Item 1 -->
<h3 class="display-4" style="font-size: 1.5rem;">What is your eye color</h3>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Eye Color
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#"><img src="img/brown_eye.jpg" class="rounded-circle" value="brown"> Brown</a>
<a class="dropdown-item" href="#"><img src="img/blue_eye.jpg" class="rounded-circle" value="blue"> Blue</a>
<a class="dropdown-item" href="#"><img src="img/green_eye.jpg" class="rounded-circle" value="green"> Green</a>
<a class="dropdown-item" href="#"><img src="img/hazel_eye.jpg" class="rounded-circle" value="hazel"> Hazel</a>
</div>
</div>
<!--Drop down Item 2-->
<h4 class="display-4" style="font-size: 1.5rem;"> What is your skin tone</h4>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Skin Tone
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton" onchange="dropdownChange();">
<a class="dropdown-item" href="#"><img src="img/fair.jpg" class="rounded-circle" value="fair"> Fair (porcelain)</a>
<a class="dropdown-item" href="#"><img src="img/light.jpg" class="rounded-circle" value="light"> Light (fair to light)</a>
<a class="dropdown-item" href="#"><img src="img/medium.jpg" class="rounded-circle" value="medium"> Medium (light to medium)</a>
<a class="dropdown-item" href="#"><img src="img/bronze_dark.jpg" class="rounded-circle" value="bronze"> Bronze dark (deep tan)</a>
<a class="dropdown-item" href="#"><img src="img/tan.jpg" class="rounded-circle" value="tan"> Tan (warm to medium)</a>
<a class="dropdown-item" href="#"><img src="img/dark.jpg" class="rounded-circle" value="rich"> Rich (deep)</a>
</div>
</div>
<br>
<!--Result-->
<button type="button" class="btn btn-info btn-lg active" style="background-color: #3e4444;"> Submit</button>
JS:
function validate() {
var a =document.getElementById("eye_color").value;
var b =document.getElementById("skin_tone").value;
if (a == "green" && b == "fair"){
alert("Brown is your best hair color!!");
}
}
Here is a pure Javascript (no jQuery) example of what I think you have asked for.
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
initApplication();
}
}
var eyeColor = null;
function selectMenu1(value){
eyeColor = value;
}
var skinTone = null;
function selectMenu2(value){
skinTone = value;
}
function validate() {
if (eyeColor && skinTone){
alert(`You selected ${eyeColor} eye colour and ${skinTone} skin tone.`);
//////////////////////////
//////////////////////////
//put your extra conditions below
//////////////////////////
//////////////////////////
if (eyeColor=="brown" && skinTone=="fair"){
alert("You should have w/e colour hair...");
} else if (eyeColor=="brown" && skinTone=="tan"){
alert("You should have w/e colour hair...");
}
}
else if (!eyeColor){
alert("Please pick an eye colour");
}
else if (!skinTone){
alert("Please pick a skin tone");
}
}
function initApplication(){
//setup dropdown menu selection events
Array.from(document.querySelectorAll(".dropdown-menu")).forEach((menu,idx)=>{
if (!menu.attributes.onchange) return;
const menuCallbackName = menu.attributes.onchange.value;
const fetchedCallback = window[menuCallbackName] || null;
if (fetchedCallback){
Array.from(menu.children).forEach((child)=>{
const callbackValue = child.attributes.data ? child.attributes.data.value : null;
if (callbackValue) child.onclick = () => fetchedCallback(callbackValue);
});
} else console.error(`No callback function named ${menuCallbackName} for menu ${idx}`);
});
}
</script>
</head>
<body>
<!--Drop down Item 1 -->
<h3 class="display-4" style="font-size: 1.5rem;">What is your eye color</h3>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Eye Color
</button>
<div class="dropdown-menu" onchange="selectMenu1" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" data="brown"><img src="img/brown_eye.jpg" class="rounded-circle"> Brown</a>
<a class="dropdown-item" href="#" data="blue"><img src="img/blue_eye.jpg" class="rounded-circle" > Blue</a>
<a class="dropdown-item" href="#" data="green"><img src="img/green_eye.jpg" class="rounded-circle" > Green</a>
<a class="dropdown-item" href="#" data="hazel"><img src="img/hazel_eye.jpg" class="rounded-circle" > Hazel</a>
</div>
</div>
<!--Drop down Item 2-->
<h4 class="display-4" style="font-size: 1.5rem;"> What is your skin tone</h4>
<div class="dropdown">
<button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: #588c7e;">
Skin Tone
</button>
<div class="dropdown-menu" onchange="selectMenu2" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" data="fair"><img src="img/fair.jpg" class="rounded-circle" > Fair (porcelain)</a>
<a class="dropdown-item" href="#" data="light"><img src="img/light.jpg" class="rounded-circle" > Light (fair to light)</a>
<a class="dropdown-item" href="#" data="medium"><img src="img/medium.jpg" class="rounded-circle" > Medium (light to medium)</a>
<a class="dropdown-item" href="#" data="bronze"><img src="img/bronze_dark.jpg" class="rounded-circle" > Bronze dark (deep tan)</a>
<a class="dropdown-item" href="#" data="tan"><img src="img/tan.jpg" class="rounded-circle" > Tan (warm to medium)</a>
<a class="dropdown-item" href="#" data="rich"><img src="img/dark.jpg" class="rounded-circle" > Rich (deep)</a>
</div>
</div>
<br>
<!--Result-->
<button type="button" class="btn btn-info btn-lg active" style="background-color: #3e4444;" onclick="validate()"> Submit</button>
</body>
</html>

Categories

Resources