I am trying to add a placeholder image in the paragraph tag. The users select an option and the photo is replaced by the one chosen. I have tried to add a photo as a valued on the first option but didn't work. Any ideas please?
select { outline: none; width: 100%; padding: 10px 0; text-align: center;}
<select onchange="document.getElementById('preview2').src = this.value">
<option selected="selected" disabled="disabled">Select a finish</option>
<option value="/images/image1.jpeg">Chrome</option>
<option value="/images/image2.jpeg">Satin Chrome</option>
<option value="/images/image3.jpeg">Black</option>
<option value="/images/image5.jpeg" ">Brushed Brass</option>
<option value="/images/image6.jpeg "">Brushed Nickel</option>
<option value="/images/image7.jpeg" ">Powdercoated Gun Metal</option>
<option value="/images/image8.jpeg "">Gun Metal</option>
<option value="/images/image9.jpeg" ">Antique Brass</option>
<option value="/images/image10.jpeg "">Black Chrome</option>
</select><br />
<p><img id="preview2" alt="" /></p>
Just trigger the change and have the default on the first option:
window.addEventListener("DOMContentLoaded", () => { // when the page haas loaded
const sel = document.getElementById("imgSel");
const img = document.getElementById('preview2');
const changeImg = () => { // called when image needs to be changed
img.src = sel.value;
img.title = sel.value;
console.log(img.src); // for debugging
};
sel.addEventListener("change", changeImg); // better than inline event handler
changeImg(); // initialise
})
#imgSel {
outline: none;
width: 100%;
padding: 10px 0;
text-align: center;
}
img {
height: 100px;
width: 100px;
border: 1px solid black;
}
<select id="imgSel">
<option selected="selected" disabled="disabled" value="/images/default.jpg">Select a finish</option>
<option value="/images/image1.jpeg">Chrome</option>
<option value="/images/image2.jpeg">Satin Chrome</option>
<option value="/images/image3.jpeg">Black</option>
<option value="/images/image5.jpeg">Brushed Brass</option>
<option value="/images/image6.jpeg">Brushed Nickel</option>
<option value="/images/image7.jpeg">Powdercoated Gun Metal</option>
<option value="/images/image8.jpeg">Gun Metal</option>
<option value="/images/image9.jpeg">Antique Brass</option>
<option value="/images/image10.jpeg">Black Chrome</option>
</select><br />
<p><img id="preview2" alt="" /></p>
Related
How can I prevent browser from scrolling when focusing? Here's my code:
select {
width: 200px;
height: 55em;
overflow: auto;
}
<br><br><br><br><br><br><br><br><br>
<select multiple>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
</select>
Try choosing an option or two.
UPDATED
As your requirement, I'd suggest you use position: fixed for the temporary body block (removed immediately with setTimeout)
With this solution, onfocus is good enough (no need to have onblur)
function blockScroller(event) {
const body = document.getElementsByTagName("body")[0]
body.classList.add("scroller-blocker")
setTimeout(() => {
body.classList.remove("scroller-blocker")
})
}
select {
width: 200px;
height: 55em;
overflow: auto;
}
.scroller-blocker {
position: fixed;
height: 100%;
}
<br><br><br><br><br><br><br><br><br>
<select multiple onfocus="blockScroller(event)">
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
</select>
OLD ANSWER
You can block the scroller with overflow: hidden on your element body
onfocus is triggered whenever an user focuses on a element
onblur is triggered whenever an user clicks outside of a focused element
Note that for mobile devices, you need to remove touchmove event for completely blocking screen moving
const touchMoveEvent = function(e) {
e.preventDefault()
}
function blockScroller() {
const body = document.getElementsByTagName("body")[0]
body.classList.add("scroller-blocker")
//avoid touch move event on mobile
body.addEventListener('touchmove', touchMoveEvent)
}
function unblockScroller() {
const body = document.getElementsByTagName("body")[0]
body.classList.remove("scroller-blocker")
//put the default behaviour of touch move event back
body.removeEventListener('touchmove', touchMoveEvent)
}
select {
width: 200px;
height: 55em;
overflow: auto;
}
.scroller-blocker {
height: 100%;
overflow: hidden;
}
<br><br><br><br><br><br><br><br><br>
<select multiple onfocus="blockScroller()" onblur="unblockScroller()">
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
<option selected="">Lorem</option>
<option selected="">ipsum</option>
<option selected="">dolor</option>
<option selected="">sit</option>
<option selected="">amet</option>
</select>
I created a div which contains my counter that displays the "(n) option(s) selected." I want to locally store my div into html so that when I refresh my page it remains active. I am new to local storage, but understand it works with key value pairs.
I have created two variables:
var get_count = document.getElementsByClassName("counter");
var save_count = localStorage.getItem("counter");
My first variable returns an HTMLCollection[] and my second variable is returned as undefined. I am confused how to handle my key value pairs in my HTMLCollection[]. How can I locally store my div container that displays the total number of options selected?
$(document).ready(() => {
$.fn.select2.amd.require([
'select2/utils',
'select2/dropdown',
'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {
/* gets item */
var previousSelectionCount = window.localStorage.getItem('selectCount');
console.log('*****', previousSelectionCount);
function SelectAll() { }
SelectAll.prototype.render = function (decorated) {
var $rendered = decorated.call(this);
var self = this;
//define the buttons inside the menu
var $selectAll = $('<input type="checkbox"> Select/Unselect All</input>' );
//append the buttons inside the menu
$rendered.find('.select2-dropdown').prepend($selectAll);
$selectAll.on("click", function (e) {
var $results = self.$element.find("option").map(function (idx, ele) {
return ele.value;
});
if($(this).prop("checked") == true){
self.$element.val($results).trigger("change");
}
else{
self.$element.val(null).trigger("change");
}
self.trigger("close")
});
return $rendered;
};
$(".js-source-states").select2({
allowClear: true,
tag: false,
closeOnSelect: false,
placeholder: "Search",
dropdownAdapter: Utils.Decorate(
Utils.Decorate(
Dropdown,
AttachBody,
),
SelectAll
),
});
var placeHolderValue = `${previousSelectionCount}` ? previousSelectionCount : ' # options selected'
var $selectNumber = $(`<div class="counter"> ${placeHolderValue} options selected</div>`);
$(".js-source-states").after($selectNumber);
$(".js-source-states").on("change", function (e){
var selectedOptions = $(this).select2('data').length;
console.log('helllooooo', selectedOptions);
window.localStorage.setItem('selectCount', selectedOptions)
$(this).next(".counter").html(selectedOptions + ' options selected');
});
});
});
#import url("//cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css");
select{
width: 100%;
display: block;
margin: 0;
}
ul.select2-selection__rendered li.select2-selection__choice{
display: none !important;
}
.counter{
position: relative;
/* z-index: 100; */
display: block;
height: 34px;
border: 1px solid #ccc;
box-sizing: border-box;
padding: 8px 40px 8px 8px;
border-radius: 2px;
}
.select2-results__option.select2-results__option--selected{
background: blue;
}
.select2-results__option.select2-results__option--highlighted.select2-results__option--selectable
{
background: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.full.min.js"></script>
<body>
<select class="js-source-states" multiple="multiple">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
</select>
<div>
<pre>
</pre>
</div>
<select class="js-source-states" multiple="multiple">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
<option value="AZ">Arizona</option>
<option value="CO">Colorado</option>
<option value="ID">Idaho</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NM">New Mexico</option>
<option value="ND">North Dakota</option>
<option value="UT">Utah</option>
<option value="WY">Wyoming</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
</select>
</body>
You can store it like this:
localStorage.setItem("counter", document.getElementsByClassName("counter")[0]);
And you can load like this:
var save_count = localStorage.getItem("counter");
Yes, you are loading it correctly, but since you never saved it, you have nothing to load.
I want to show all the contents of select element (for below snippet) on focus when navigating to it using tab key.
select {
width: 200px;
border: 1px solid #aaa;
border-radius: 4px;
height: 28px;
overflow: hidden;
}
<select id="" class="select2" >
<option value="" disabled selected>Select Fruit</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
</select>
A solution I've found in jQuery but I want the same function in plain JavaScript which I'm not able to do.
jQuery code :-
$('.select2').select2({
minimumResultsForSearch: 20
});
$(document).on('focus', '.select2.select2-container', function (e) {
var isOriginalEvent = e.originalEvent
var isSingleSelect = $(this).find(".select2-selection--single").length > 0
if (isOriginalEvent && isSingleSelect) {
$(this).siblings('select:enabled').select2('open');
}
});
Try something like
<select id="select2" class="select2" >
<option value="" disabled selected>Select Fruit</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
</select>
document.getElementById("select2").addEventListener("focus", myFunction);
function myFunction() {
var e = document.getElementById("select2");
console.log(e.options[e.selectedIndex].value);
}
I have a div "businessmodel" with some html element inside that is hidden by default and I want it to display when the option selected in the select option "accounttype" is provider.
Please see the code here:
JavaScript
<script type="text/javascript">
$('#accounttype').bind('change', function(event) {
var i= $('#accounttype').val();
if(i=="0")
{
$('#businessmodel').hide();
}
elseif(i=="1")
{
$('#businessmodel').show();
}
});
</script>
HTML
Account Type
<select name="type" required="" class='selector' id="accounttype" onchange="change(this)">
<option value='0'>User</option>
<option value='1'>Provider</option>
</select>
<div id="businessmodel" style="display:none;">
<p id="modellevel" >Business model</p>
<select name="model" required="" class='selector' id="model">
<option value='choose' >Choose Business Model</option>
<option value='ALPHA' >ALPHA</option>
<option value='Thecla'>Thecla</option>
<option value='Sixtus'>Sixtus</option>
<option value='Marthar'>Marthar</option>
<option value='Alma' >Alma</option>
<option value='Manuel'>Manuel</option>
<option value='Dum'>Dum</option>
<option value='Gech'>Gech</option>
<option value='Alba'>Hika</option>
<option value='Win'>Win</option>
<option value='Rex'>Rex</option>
<option value='Hika'>Hika</option>
</select>
</div>
Try this
<script type="text/javascript">
$(document).ready(function() {
$('select').change(function () {
$('.business').toggleClass('hide');
});
});
</script>
<style type="text/css">
.accounttype {
border: 1px solid;
margin: 5px;
padding: 10px;
}
.business {
border: 1px solid;
margin: 5px;
padding: 10px;
}
.hide {
display: none;
}
</style>
<div class="accounttype">
Show business model :
<select>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="business hide">
Some content goes here
</div>
Try this code.
$('#accounttype').on('change', function() {
var i = this.value;
if(i=="0")
{
$('#businessmodel').hide();
}
else
{
$('#businessmodel').show();
}
}
<select name="type" required="" class='selector' id="accounttype">
<option value='0'>User</option>
<option value='1'>Provider</option>
</select>
<div id="businessmodel" >
<p id="modellevel" >Business model</p>
<select name="model" required="" class='selector' id="model">
<option value='choose' >Choose Business Model</option>
<option value='ALPHA' >ALPHA</option>
<option value='Thecla'>Thecla</option>
<option value='Sixtus'>Sixtus</option>
<option value='Marthar'>Marthar</option>
<option value='Alma' >Alma</option>
<option value='Manuel'>Manuel</option>
<option value='Dum'>Dum</option>
<option value='Gech'>Gech</option>
<option value='Alba'>Hika</option>
<option value='Win'>Win</option>
<option value='Rex'>Rex</option>
<option value='Hika'>Hika</option>
</select>
</div>
$('#accounttype').on('change', function(event) {
var i= $('#accounttype').val();
if(i=="0")
{
$('#businessmodel').hide();
}
else
{
$('#businessmodel').show();
}
});
i want to display the selected value, rather than the text.
like
instead
i have tried with below code, but doesn't works for me, any help would be appreciated
<select class="form-control" name="identity" id="identity">
<option value="CC">Cédula de Ciudadanía</option>
<option value="CE">Cédula Extranjera</option>
<option value="NIT">Nit</option>
<option value="TI">Tarjeta de Identidad</option>
<option value="PPN">Pasaporte</option>
<option value="SSN">Número de Seguridad Social</option>
<option value="LIC">Licencia de Conducción</option>
<option value="DNI">DNI</option>
</select>
but it sholud not reflect the select box values
Have a fake div element over select element
Set pointer-events: none; for fake element
Listen change event of select-element
Set the text of the fake element on change of the select-element
var $identity = $('#identity');
var $fake = $('#fake');
$fake.css($identity[0].getBoundingClientRect());
$identity.on('change', function() {
$fake.text($(this).find('option:selected').text());
}).change();
#fake {
pointer-events: none;
border: 1px solid black;
padding: 3px;
}
#identity {
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select class="form-control" name="identity" id="identity">
<option value="CC">Cédula de Ciudadanía</option>
<option value="CE">Cédula Extranjera</option>
<option value="NIT">Nit</option>
<option value="TI">Tarjeta de Identidad</option>
<option value="PPN">Pasaporte</option>
<option value="SSN">Número de Seguridad Social</option>
<option value="LIC">Licencia de Conducción</option>
<option value="DNI">DNI</option>
</select>
<div id="fake" style="position:absolute;"></div>
Sadly, this is not possible with the native HTML <select>. But, you can look for other <select> libraries which can do this or write your own <select> component which does this.
var $identity = $('#identity');
var $fake = $('#fake');
$fake.css($identity[0].getBoundingClientRect());
$identity.on('change', function() {
$fake.text($(this).find('option:selected').val());
}).change();
#fake {
pointer-events: none;
border: 1px solid black;
padding: 0px;
height: 32px !important;
line-height: 32px;
}
#identity {
opacity: 0;
height: 32px !important;
line-height: 32px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select class="form-control" name="identity" id="identity">
<option value="CC">Cédula de Ciudadanía</option>
<option value="CE">Cédula Extranjera</option>
<option value="NIT">Nit</option>
<option value="TI">Tarjeta de Identidad</option>
<option value="PPN">Pasaporte</option>
<option value="SSN">Número de Seguridad Social</option>
<option value="LIC">Licencia de Conducción</option>
<option value="DNI">DNI</option>
</select>
<div id="fake" style="position:absolute;"></div>