Div Update From Selecting HTML Option - javascript

Getting console error:
SyntaxError: Unexpected end of script.
Code here:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<script> // In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
$("#cars2").select2();
});
</script>
<script>
<!--Need help here I think.-->
function myFunction(){
var x = document.getElementById("myDIV");
var y = this.value;
switch (y) {
case '1':
x.innerHTML = "<p>Volvo dude</p>";
break;
case '2':
x.innerHTML = "<p>Roy!</p>";
}
}
</script>
<style>
select {
width: 150px;
}
</style>
</head>
<body>
<div id="myDIV">Hello</div>
<label for="cars">Choose a car:</label>
<select id="cars2" onchange="myFunction()">
<option value="0">Pick something</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
</body>
</html>
I can't use the snippet editor 'cause all I have is an iPad.
JSFiddle here: https://jsfiddle.net/CoolBuys1290/59qmbt0f/19/
Please help me update the div text based on selecting an option.
Updated braces.
Thanks.

You were missing the correct way to pick the current selected option that, for example in the snippet I included here, I've got using the css selector select#cars2 option:selected and through the jQuery object, because your code was based on it, instead of the vanilla document.querySelector
$(document).ready(function() {
$("#cars2").select2();
});
function myFunction(event){
var x = document.getElementById("myDIV");
//here you are picking the selected option item
var y = $('select#cars2 option:selected').val();
switch (y) {
case '1':
x.innerHTML = "<p>Volvo dude</p>";
break;
case '2':
x.innerHTML = "<p>Roy!</p>";
}
}
select {
width: 150px;
}
<script
src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<div id="myDIV">Hello</div>
<label for="cars">Choose a car:</label>
<select id="cars2" onchange="myFunction()">
<option value="0">Pick something</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>

The jQuery slogan is "write less, do more!" - and the following takes it up in a way. I have created an array captions that supplies the captions for the div and - if nothing was provided - switches it back to "Hello".
const x=document.getElementById("myDIV"), captions=[null,'Volvo dude!','Roy!'];
$(document).ready(function() {
$("#cars2").select2().change(ev=>x.textContent=captions[ev.target.value]||"Hello");
});
select {
width: 150px;
}
<script
src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<div id="myDIV">Hello</div>
<label for="cars">Choose a car:</label>
<select id="cars2">
<option value="0">Pick something</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>

Related

Autocomplete on HTML Select Field

I have this simple select html field, i am learning JS, I just want to have a autocomplete kind of thing in this field, so when user type it should have this kind of functionality, can It be done?
<html>
<body>
<select>
<option>USA</option>
<option>India</option>
<option>Canada</option>
<option>UK</option>
</select>
</body>
</html>
I have used this library and modified it for my needs. I had modified it to have search clear and custom styling of dropdown. Easy to do. You can also give it a try. https://davidstutz.github.io/bootstrap-multiselect/
Below is the example
<!-- Initialize the plugin: -->
$(document).ready(function() {
$('#example-getting-started').multiselect({
enableFiltering: true,
includeFilterClearBtn: false
});
});
.hide
{
display:none;}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" 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.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/1.1.1/js/bootstrap-multiselect.min.js" integrity="sha512-fp+kGodOXYBIPyIXInWgdH2vTMiOfbLC9YqwEHslkUxc8JLI7eBL2UQ8/HbB5YehvynU3gA3klc84rAQcTQvXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<body>
<select id="example-getting-started" class="hide">
<option value="usa">USA</option>
<option value="india">India</option>
<option value="canada">Canada</option>
<option value="uk">UK</option>
</select>
</body>
The previous answer is working fine, but one little more addition to the searchbox is sensiability to lower cas.
so this more accurate code for your issue.
<div class="container my-5">
<select class="mdb-select md-form" searchable="Search here..">
<option value="" disabled selected>Choose your country</option>
<option value="1">USA</option>
<option value="2">Germany</option>
<option value="3">France</option>
<option value="3">Poland</option>
<option value="3">Japan</option>
NB: i'm using bootstrap v4
here is also a link to the source code
https://mdbootstrap.com/snippets/jquery/mdbootstrap/921549#html-tab-view

Need alternative to change function that fires when the page loads

I'm trying to display a piece of styled text below a dropdown using the change function, the problem is the option that triggers the change is the first option when the page loads, and because it's disabled (which it needs to be), there is no way to change to it
Instead, I'm wondering if there is an alternative to change that loads the function when the page loads
Just to be clear, the text should not be visible when any other value is selected from the dropdown
I'm also struggling with assigning a class name to the printed text, I have commented out what I thought should work
Days of numerous different code examples, and although I'm closer than a few days ago, I still can't figure out the proper way
<!DOCTYPE html>
<html>
<head>
<title>Reports</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
select {
outline: none;
}
</style>
</head>
<body>
<select id="reports" class="w3-select w3-border" style="font-size: 20px;" name="reports">
<option value="0" disabled selected>- Choose -</option>
<optgroup label="Reports">
<option value="1">Report 1</option>
<option value="2">Report 2</option>
<option value="3">Report 3</option>
<option value="4">Report 4</option>
</optgroup>
</select>
<script type="text/javascript">
$(document).ready(function() {
$('#reports').change(function() {
if ($(this).val() == "0") {
var x = document.createElement("div");
// class = "w3-center w3-text-light-green"
x.textContent = "Choose Report From Menu";
document.body.appendChild(x);
}
});
});
</script>
</body>
</html>
The desired result is have the "styled" text appear when the page loads, but disappear when any other option from the dropdown is selected
add onchange="hide()" to <select...> and add div with text in body and after change just hide it.
<!DOCTYPE html>
<html>
<head>
<title>Reports</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
select {
outline: none;
}
</style>
</head>
<body>
<select id="reports" class="w3-select w3-border" style="font-size: 20px;" name="reports" onchange="hide()">
<option value="0" disabled selected>- Choose -</option>
<optgroup label="Reports">
<option value="1">Report 1</option>
<option value="2">Report 2</option>
<option value="3">Report 3</option>
<option value="4">Report 4</option>
</optgroup>
</select>
<div id="msg">"Choose Report From Menu"</div>
<script type="text/javascript">
function hide() {
msg.style.display='none';
};
</script>
</body>
</html>
If you're trying to execute that function one time when the page loads, try something like this:
$(document).ready(function () {
function reportsChange() {
if ($(this).val() == "0") {
var x = document.createElement("div");
// class = "w3-center w3-text-light-green"
x.textContent = "Choose Report From Menu";
document.body.appendChild(x);
}
}
$('#reports').change(function () {
reportsChange();
});
reportsChange();
});
This will execute the "reportsChange" function once when loading the page, and it will also be available for you to use whenever the on change event triggers.

How to display all elements from a Javascript file

I want to display all elements when the position is selected from a dropdown box when I select a position the correct elements display but when I select all to display all the elements nothing is displayed.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="players.js"></script>
<script type="text/javascript" src="playerFilter.js"></script>
</head>
<body>
<h1>Players by Position</h1>
<select id="position">
<option value=''>Select...</option>
<option value='All'>All</option>
<option value='Goalkeeper'>Goalkeeper</option>
<option value='Defender'>Defender</option>
<option value='Midfielder'>Midfielder</option>
<option value='Forward'>Forward</option>
</select>
<hr>
<div id="data"></div>
</body>
.JS File:
window.onload=function()
{
document.getElementById('position').onchange=function()
{
function getPlayerPosition(element)
{
if(element.Position == $("#position").val())
return true;
}
var playerPosition = _.filter(players, getPlayerPosition);
console.log(playerPosition);
$("#data").html("");
_.each(playerPosition, function(element){
$("#data").append(element.Name + "<br>");
});
}
}
Using only jquery you can do like this using [attribute-not-equal-selector] selector1
$("#position").on('change', function() {
var str = '';
if ($(this).val() === "All") {
var getAllElem = $("#position option").not("[value='All']").not("[value='']").each(function(i, v) {
str += $(v).text() + ' ';
})
$("#data").html(str);
} else {
$("#data").html($(this).val());
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Players by Position</h1>
<select id="position">
<option value=''>Select...</option>
<option value='All'>All</option>
<option value='Goalkeeper'>Goalkeeper</option>
<option value='Defender'>Defender</option>
<option value='Midfielder'>Midfielder</option>
<option value='Forward'>Forward</option>
</select>
<hr>
<div id="data"></div>

onclick not working with selectpicker multiselect dropdown

I have a selectpicker multiselect dropdown. I'm not able to invoke 'onclick' when I select any option. But this works with the normal html multiple dropdown. How to make it work with selectpicker?
Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
select/1.6.3/css/bootstrap-select.min.css" />
<link rel="stylesheet" href="https:
//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script
src=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
>
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
select/1.6.3/js/bootstrap-select.min.js"></script>
</head>
<body>
<form action="/action_page.php">
<select class="selectpicker" name="cars" multiple>
<option value="volvo" onclick="myFunction(this)">Volvo</option>
<option value="bmw" onclick="myFunction(this)">Bmw</option>
<option value="opel" onclick="myFunction(this)">Opel</option>
<option value="audi" onclick="myFunction(this)">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select
multiple options.</p>
<script type="text/javascript">
function myFunction(option) {
if (option.selected) {
alert(option.text);
}
}
</script>
</body>
</html>
I have changed the dropdownlist a bit below:
<select class="selectpicker" onchange="myFunction()" id="cars" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
Then modified your myFunction below:
var oldarr = [];
var newarr = [];
function myFunction() {
if ($("#cars option:selected").length == 1) {
oldarr = [];
oldarr.push($("#cars option:selected").val());
alert($("#cars option:selected").val());
}
else {
newarr = [];
$("#cars option:selected").each(function(i){
newarr.push($(this).val());
});
newitem = $(newarr).not(oldarr).get();
if (newitem.length > 0) {
alert(newitem[0]);
oldarr.push(newitem[0]);
}
else {
oldarr = newarr;
}
}
}
Basically, the oldarr will store the previous list of selected items. Then we insert the latest list of selected items into newarr. Then we compare what is in the newarr but not in the oldarr. This way we can filter out only the latest clicked item. If the user deselects an item instead, we just assign the newarr to oldarr.
try this, use forEach to find selected option
var selectEl = document.querySelector('.selectpicker');
var options = document.querySelectorAll('.selectpicker option');
selectEl.addEventListener('change', function() {
options.forEach(function(option) {
if(option.selected) { alert(option.value); }
})
})
<select class="selectpicker" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
or use jQuery find :select
$('.selectpicker').change(function() {
var thisValue = $(this).find(':selected').attr('value') ;
alert(thisValue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="selectpicker" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
Hope help :)
I have used jQuery to do this. since you use select from bootstrap, it will ordered as list not as options, thats why it didnt worked for you
$(function() {
$('.selectpicker').on('change', function(){
var selected = $(this).find("option:selected").text();
alert(selected);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
<form action="/action_page.php">
<select class="selectpicker" name="cars" multiple>
<option value="volvo" >Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select
multiple options.</p>
Hope this helps..!

Changing Background Image with cookie

I am looking for help in putting a cookie into this script so the browser remembers the background image selected when the browser is closed or changed page. Any help would be much appreciated!
function changeTheme()
{
var e = document.getElementById("themes");
var theme = e.options[e.selectedIndex].value;
console.log(theme);
document.getElementById("shelf").style.backgroundImage = "url("+theme+")";
}
<body id="shelf">
<select id="themes" onChange="changeTheme()" name="ChangeBG">
<option value="images/background1.jpg" selected="selected">Default</option>
<option value="images/background2.jpg">Heart</option>
<option value="images/background3.jpg">Earthly</option>
<option value="images/background4.jpg">Sunflowers</option>
<option value="images/background5.jpg">Mountin</option>
</select>
It looks like the only piece you are missing is the setting and getting of the cookie. Here is a post about setting and getting cookies using both jquery and javascript.
This is jquery but it gets the job done.
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<!--download jquery.cookie from here http://plugins.jquery.com/cookie -->
<script type="text/javascript" src="images/jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var theme = $.cookie("backgroundImage");
if (theme){document.getElementById("shelf").style.backgroundImage = "url("+theme+")";}
$("#themes").change(function() {
theme = $(this).val();
$.cookie("backgroundImage", theme);
document.getElementById("shelf").style.backgroundImage = "url("+theme+")";
});
});
</script>
</head>
<body id="shelf">
<!--<select id="themes" onChange="changeTheme()" name="ChangeBG">-->
<select id="themes" name="ChangeBG">
<option value="images/background1.jpg" selected="selected">Default</option>
<option value="images/background2.jpg">Heart</option>
<option value="images/background3.jpg">Earthly</option>
<option value="images/background4.jpg">Sunflowers</option>
<option value="images/background5.jpg">Mountin</option>
</select>
</body>
</html>

Categories

Resources