Jquery not showing select element. No errors in console - javascript

I have a "state" select and a few "carrier" selects. for simplicity I'm using only two carrier selects here.
My jquery is suppose to show the carrier selects based on the the state selected.
The state select value is appended to the carrier select name so I can choose which carrier select to add a specific class to.
MY PROBLEM: My carrier selects wont show up. I had this working at one point, and I must've changed something along the way. Not sure whats happening here. Any help would be great. Thanks!
EDIT: I've added my original JS to show where I was, and how I want to change to Jquery.
HTML:
<div style="width:160px;">
<select name="state_select" id="state_select">
<option value="0" selected>Choose a state</option>
<option value="1">Connecticut</option>
<option value="2">New Hampshire</option>
<option value="3">New Jersey</option>
<option value="4">New York</option>
</select>
</div>
<div id="select-div1" class="select-div">
<select name="carrier_select" id="carrier_select1" class="carrier_select">
<option selected disabled>Select a carrier - Conn</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>
<div id="select-div" class="select-div">
<select name="carrier_select" id="carrier_select2" class="carrier_select">
<option selected disabled>Select a carrier - NH</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>
JQUERY:
$('#state_select').prop('selectedIndex', 0);
$('.carrier_select').prop('selectedIndex', 0);
function optionCheck() {
stateVal = $('div.select-div select').val();
selectDiv = $('#carrier_select')[0] + stateVal;
if ($(stateVal).attr('selected', 'selected')) {
$(selectDiv).attr('class', "conn_select", "nh_select", "nj_select", "ny_select");
$(selectDiv).addClass("dropdown-box");
} else {
$(selectDiv).attr('class', 'carrier_select');
}
}
$('#state_select').change(function(e) {
$('.carrier_select').prop('selectedIndex', 0);
optionCheck();
});
MY JAVASCRIPT (WORKS) BEFORE TRYING JQUERY:
function optionCheck() {
var i, len, optionVal, selectDiv,
selectOptions = document.getElementById("state_select");
// loop through the options in case there
// are multiple selected values
for (i = 0, len = selectOptions.options.length; i < len; i++) {
// get the selected option value
optionVal = selectOptions.options[i].value;
// find the corresponding help div
selectDiv = document.getElementById("carrier_select" + optionVal);
// move on if I didn't find one
if (!selectDiv) { continue; }
// set CSS classes to show/hide help div
if (selectOptions.options[i].selected) {
selectDiv.className = "conn_select nh_select nj_select ny_select";
$(selectDiv).addClass("dropdown-box");
} else {
//Hide carrier select on page load
selectDiv.className = "carrier_select";
}
}
}
// bind the onchange handler
document.getElementById("state_select").onchange = optionCheck;
CSS:
.select-div select {
border: none;
-webkit-appearance: none;
-moz-appearance: none;
text-indent: 1px;
text-overflow: '';
}
.carrier_select {
display: none;
}

First off, your code has some redundancies and some questionable decisions in it in my humble opinion that you could work around in order to simplify and/or make it more usable. However, there is a way to achieve what you want with most of it untouched, using Javascript/jQuery code. For the full thing, check this fiddle, the script is below as well along with its explanation:
$('#state_select').prop('selectedIndex', 0);
$('.carrier_select').prop('selectedIndex', 0);
function optionCheck() {
stateVal = $('#state_select').val();
selectDiv = $('#carrier_select'+ stateVal);
$('.dropdown-box:not(#state_select_box)').removeClass('dropdown-box').addClass('carrier_select');
$(selectDiv).removeClass('carrier_select').addClass('dropdown-box');
$($selectDiv).val('0');
}
$('#state_select').change(function(e) {
optionCheck();
});
What this does is it gets the val() of #state_select, appends it to the #carrier_select so that the selector targets the right id, then changes all active selectors, except the #state_selector_box (which I made to wrap around #state_select) to ones with the .carrier_select class, thus making them invisible and then it finally makes the one that corresponds to the selected state visible using the dropdown-box class. Also the val() of the selector that just appeared is set to 0.

You are telling css to hide the element
.carrier_select {
display: none;
}
Both of your select elements have the class "carrier_select" and as a result of this css definition, they are not displayed. Remove or change this definition for them to be shown.

Edited in such a way that you can see the carrier selections. But other part of your question - appending to carrier name, showing carriers depending on the state needs more inputs.
$('#state_select').prop('selectedIndex', 0);
$('.carrier_select').prop('selectedIndex', 0);
function optionCheck() {
stateVal = $('div.select-div select').val();
selectDiv = $('#carrier_select')[0] + stateVal;
if ($(stateVal).attr('selected', 'selected')) {
$(selectDiv).attr('class', "conn_select", "nh_select", "nj_select", "ny_select");
$(selectDiv).addClass("dropdown-box");
} else {
$(selectDiv).attr('class', 'carrier_select');
}
}
$('#state_select').change(function(e) {
$('.carrier_select').prop('selectedIndex', 0);
optionCheck();
});
.select-div select {
border: none;
-webkit-appearance: none;
-moz-appearance: none;
text-indent: 1px;
text-overflow: '';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="dropdown-box" style="width:160px;">
<select name="state_select" id="state_select">
<option value="0" selected>Choose a state</option>
<option value="1">Connecticut</option>
<option value="2">New Hampshire</option>
<option value="3">New Jersey</option>
<option value="4">New York</option>
</select>
</div>
<div id="select-div1" class="select-div">
<select name="carrier_select" id="carrier_select1" class="carrier_select">
<option selected disabled>Select a carrier - Conn</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>
<div id="select-div" class="select-div">
<select name="carrier_select" id="carrier_select2" class="carrier_select">
<option selected disabled>Select a carrier - NH</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>

Without commenting on the rest of the code, try removing
.carrier_select {
display: none;
}

Related

How do I remove padding with JavaScript?

var urlmenu = document.getElementById('category');
urlmenu.onchange = function() {
document.location.href = this.value;
};
function search_designs() {
let input = document.getElementById('searchbar').value
input=input.toLowerCase();
let x = document.getElementsByClassName('summary-title-link');
let z = document.getElementsByClassName('summary-item');
for (i = 0; i < x.length; i++) {
if (!x[i].innerHTML.toLowerCase().includes(input)) {
x[i].style.display="none";
z[i].style.display="none";
}
else {
x[i].style.display="list-item";
z[i].style.display="block";
}
}
}
#searchbar{
text-align: left;
position: center;
}
.search_designs{
display: list-item;
}
<input id="searchbar" type="text" name="search" onkeyup="search_designs()" placeholder="Search..">
<select id="category" name="category">
<option value="https://www.keslyns.com/all-designs-details">All Designs</option>
<option value="https://www.keslyns.com/alphabet-quote-designs">Alphabet/Wording</option>
<option value="https://www.keslyns.com/box-designs">Boxes</option>
<option value="https://www.keslyns.com/floral-designs">Floral</option>
<option value="https://www.keslyns.com/heart-designs">Hearts</option>
<option value="https://www.keslyns.com/holidayseasonal-designs">Holiday/Seasonal</option>
<option value="https://www.keslyns.com/mulitple-motif-designs">Multiple Motif</option>
<option value="https://www.keslyns.com/new-designs">New Designs</option>
<option value="https://www.keslyns.com/ornament-designs">Ornaments</option>
<option value="https://www.keslyns.com/pillowpurse-designs">Pillow/Purses</option>
<option value="https://www.keslyns.com/specialty-items-designs">Specialties</option>
<option value="https://www.keslyns.com/symstitch-designs">Sym-Stitch</option>
</select>
For starters I have barely worked with javascripting with HTML. I am trying to create a search function that filters a list of items on a webpage. Context: The site was originally created on squarespace so some options are limited, this is why I'm using their built in code blocks to accomplish this. The downside of this is that class/ IDs are hard to find. The page in question is https://www.keslyns.com/all-designs-details.
You can remove padding style of an element with a code similar to this
document.getElementById("myDiv").style.padding = "0";
If there is no class or id associated with an element, then you can try to use document.querySelector() to target a specific element.
document.querySelectorAll() is used to match more than one element.
You can read more about it here
Please also note that, this code must run after the elements are loaded onto the DOM. So, it is better to add your javascript to footer section of your page.

Having issues selecting next element in selectbox

When selecting another country, the list becomes visible. It works, however there's one issue. When selecting another county the very first item of its attached region must be displayed, instead of remained value.
I.e. when selecting Germany, New York must become invisible, and Dresden must become visible. I've been trying to do this for several hours with no luck. Any advice?
$(function() {
$("[name='country']").change(function() {
// Target option
var hiddenClass = 'hidden';
var selected = $(this).find(':selected').data('country-id');
// Hide all options
$("[name='region']").find('option') // Find all options
.addClass(hiddenClass) // Hide them all
.each(function() {
// Find current active
if ($(this).data('country-id') == selected) {
// Show currently matched against selection
$(this).removeClass(hiddenClass);
}
});
}).trigger('change');
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
</script>
<select name="country">
<option data-country-id="1">USA</option>
<option data-country-id="2">Germany</option>
</select>
<select name="region">
<option data-country-id="1">New York</option>
<option data-country-id="1">California</option>
<option data-country-id="1">Carolina</option>
<option data-country-id="2">Dresden</option>
<option data-country-id="2">Berlin</option>
</select>
The issue is because, although some of the option elements are hidden, they're still technically available in the DOM to be selected. To fix this you can force the selection to update to the first available option based on the given country-id value.
Also note that you can make your logic more succinct by using filter() instead of an each() loop. Try this:
$(function() {
$("[name='country']").change(function() {
var hiddenClass = 'hidden';
var selected = $(this).find(':selected').data('country-id');
$('[name="region"] option').addClass(hiddenClass)
.filter(`[data-country-id="${selected}"]`).removeClass(hiddenClass)
.first().prop('selected', true);
}).trigger('change');
});
.hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<select name="country">
<option data-country-id="1">USA</option>
<option data-country-id="2" selected="true">Germany</option>
</select>
<select name="region">
<option data-country-id="1">New York</option>
<option data-country-id="1">California</option>
<option data-country-id="1">Carolina</option>
<option data-country-id="2">Dresden</option>
<option data-country-id="2">Berlin</option>
</select>

Two select fields dependent on each other

what I'm trying to do is to create two select fields and after selecting some option in the first one, some of options in the second should be hidden.
I'm almost there, except the fact, that my script can't find certain option out of the first select field, but when I put such option in the first it works, but only with the first one, so it's useless. I need it to hide options in the second select field according to option chosen in the first one.
What makes it all more difficult is the fact that I can't add any classes or ids or anything actually here.
I think I've made some mistake that consists of the way I tell the script which element should it edit, but I have no idea how to write it another way.
HTML
<select name="NameOne">
<option value="First">Lorem Ipsum1</option>
<option value="Second">Lorem Ipsum2</option>
<option value="Third">Lorem Ipsum3</option>
<option value="CD">Dolor2</option>
</select>
<select name="NameTwo">
<option value="AB">Dolor1</option>
<option value="CD">Dolor2</option>
<option value="EF">Dolor3</option>
</select>
JS
$("select").change(function(){
if($(this).val() == "Second") {
$('option[value="CD"]', this).addClass('hidden');
} else {
$('option[value="CD"]', this).removeClass('hidden');
}
});
CSS
.hidden {
display: none
}
Please, help.
It is not working because of this code here:
$('option[value="CD"]', this)...
In simple words, this checks for the option on select which is currently clicked. Since you clicked the first select, this becomes the first select and it tries to find option with values CD on it which is not present. So what you do?? Simple, get the second select, find option with values CD in it and change the class :)
Try this
// you can change this to select first select only since selecting all the select doesnot make sense.
$("select").change(function(){
//$("select[name='NameOne']").change(function(){ <--- better
var secondSelect = $("select[name='NameTwo']"); //get second select
if($(this).val() == "Second") {
secondSelect.find('option[value="CD"]').addClass('hidden'); //find option with CD and add Class
} else {
secondSelect.find('option[value="CD"]').removeClass('hidden');
}
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="NameOne">
<option value="First">Lorem Ipsum1</option>
<option value="Second">Lorem Ipsum2</option>
<option value="Third">Lorem Ipsum3</option>
<option value="CD">Dolor2</option>
</select>
<select name="NameTwo">
<option value="AB">Dolor1</option>
<option value="CD">Dolor2</option>
<option value="EF">Dolor3</option>
</select>
$("select").change(function(){
var secondSelect = $(select["name='NameTwo']");
if($(this).val() == "Second") {
secondSelect.find('option[value="CD"]').addClass('hidden');
} else {
secondSelect.find('option[value="CD"]').removeClass('hidden');
}
});
You should query on a specific select and then hide the option in the other select, without this which would only do those options in the select that changed.
$("select[name='NameOne']").change(function() {
if ($(this).val() == "Second") {
$("select[name='NameTwo'] option[value='CD']").addClass('hidden');
} else {
$("select[name='NameTwo'] option[value='CD']").removeClass('hidden');
}
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="NameOne">
<option value="First">Lorem Ipsum1</option>
<option value="Second">Lorem Ipsum2</option>
<option value="Third">Lorem Ipsum3</option>
<option value="CD">Dolor2</option>
</select>
<select name="NameTwo">
<option value="AB">Dolor1</option>
<option value="CD">Dolor2</option>
<option value="EF">Dolor3</option>
</select>

Select2 jquery plugin show number of selected items in the result instead of tags

I am using Select2 jQuery Plugin.
https://select2.github.io/ for reference
When I am using the multiple dropdown option. The result of selected items is shown as tags in a box but, I just want to show the number of items selected.
Is it possible with Select2 jQuery plugin
HTML
<select multiple style="width:100%">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
<option value="5">Name5</option>
<option value="6">Name6</option>
<option value="7">Name7</option>
</select>
JS
$('select').select2();
I want output as below
instead of tag like output.
Example working Fiddle
You can add this code after initializing select2
$('select').on('select2:close', function (evt) {
var uldiv = $(this).siblings('span.select2').find('ul')
var count = $(this).select2('data').length
if(count==0){
uldiv.html("")
}
else{
uldiv.html("<li>"+count+" items selected</li>")
}
Ref: jsfiddle
Reference to select2 events: Here
Edit: If you want to display a blank when user deselects everything,
Use this fiddle: here
Edit: Updated to remove flaw in deselection of data and changed it to main answer.
Fiddle: here
Selectors can certainly be improved, but as a blueprint, adding a counter element on change and hiding the tags like this seems to work as asked.
$('select').select2({closeOnSelect: false}).on("change", function(e) {
$('.select2-selection__rendered li:not(.select2-search--inline)').hide();
$('.counter').remove();
var counter = $(".select2-selection__choice").length;
$('.select2-selection__rendered').after('<div style="line-height: 28px; padding: 5px;" class="counter">'+counter+' selected</div>');
});
.counter{
position:absolute;
top:0px;
right:5px;
}
.select2-search--inline{
background-color:Gainsboro;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select multiple style="width:100%" id="mySelect">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
<option value="5">Name5</option>
<option value="6">Name6</option>
<option value="7">Name7</option>
</select>
although the answer is given.
you can try this code. first initialize than on close call it.
jQuery('.multi-select-pbwp').select2();
$('.multi-select-pbwp').on('select2:close', function() {
const $select = $(this);
const numSelected = $select.select2('data').length;
$select.next('span.select2').find('ul').html(function() {
return `<li class="class="select2-selection__choice">${numSelected} selected</li>`;
})
});

HTML Select: How can you change the label when the <select> is closed?

Consider this:
<select name="month_selection">
<optgroup label="2012">
<option value="1">January</option>
</optgroup>
<optgroup label="2011">
<option value="1">January</option>
<option value="2">February</option>
The HTML above looks like #1 when open, and #2 when closed.
How can I get the closed version to look like #3?
The purpose is to also show the selected year without repeating it in the open options (so it looks cleaner).
My original (marked correct) answer is too old to be of use, so here is a more up-to-date answer that may be a helpful starting point. It has some weirdness around the select box width that would need resolving according to your UI structure. Hope it is helpful.
document.querySelector('select').addEventListener("change", function(e) {
var value = e.target.value
var option = e.target.querySelector("option[value='" + value + "']")
var group = option.parentElement
var display = document.querySelector("#value")
var text = option.text + " " + group.label
display.innerText = text
})
#wrapper {
position: relative;
}
#value {
position: absolute;
pointer-events: none;
width: 100%;
height: 100%;
display: flex;
align-items: center;
font-size: 0.8rem;
padding-left: 0.5em;
}
select {
color: #FFFFFF;
width: 100%;
}
select option {
color: black;
}
<html>
<div id="wrapper">
<div id="value">Select Dateā€¦</div>
<select>
<optgroup label="2012">
<option value="1">January</option>
<option value="2">February</option>
</optgroup>
<optgroup label="2013">
<option value="3">January</option>
<option value="4">February</option>
</optgroup>
</select>
</div>
</html>
Old Answer (2012)
Its good to see someone making efforts to keep a good clean UI. Kudos, more people should do this. However I'd advise against approaching to problem this way. You run a risk of trying to force an element to do something it wasn't designed to do. Even if you find a workaround, it might end up putting you into cross browser testing hell, or simply stop working on a new browser version.
I'd suggest replacing this with a JQuery or similar scriptable SELECT widget replacement such as http://filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/. This will give you all the flexibility you need to tweak the display through JavaScript.
This is a fairly simple way of doing it... Use change/input and when it is focused, reset the text to whatever is before the year.
Appears to work well in all browsers that I have tested.. The problem is that no matter what you do, you're always going to have to change the text value of the selected element, there is no way around that. Test yourself without deploying here - http://jsfiddle.net/CTwJy/
<select name="month_selection" id="month_selection">
<optgroup label="2012">
<option value="1">January</option>
</optgroup>
<optgroup label="2011">
<option value="1">January</option>
<option value="2">February</option>
</optgroup>
</select>
<script type="text/javascript">
function attach(ele, evt, cb) { ele.addEventListener ? ele.addEventListener(evt, cb) : ele.attachEvent('on' + evt, cb); }
function evSupported(ele, evt) { return ((('on'+evt) in ele) ? true : (function(ele, evt) { ele.setAttribute('on'+evt, 'return;'); return (typeof ele['on'+evt] == 'function'); })()); };
var selectBox = document.getElementById('month_selection');
attach(selectBox, (evSupported(selectBox, 'input') ? 'input' : 'change'), function() {
this.options[this.selectedIndex].innerText += ' ' + this.options[this.selectedIndex].parentNode.label;
this.blur();
});
attach(selectBox, 'focus', function() {
for (var i = 0; i < this.options.length; i++) {
this.options[i].innerText = this.options[i].innerText.split(' ')[0];
}
});
</script>
This isn't tested, so it may not work or may have bugs (for instance, it might permanently change the option's label), but perhaps it will give you some insight.
<script type="text/JavaScript">
function changeLabel()
{
var dropDown = document.getElementById("selMonth");
dropDown.options[dropDown.selectedIndex].label += " "+ dropDown.options[dropDown.selectedIndex].parentNode.label;
}
</script>
<select name="month_selection" id="selMonth" onchange="changeLabel()">
<optgroup label="2012">
<option value="1">January</option>
</optgroup>
<optgroup label="2011">
<option value="1">January</option>
<option value="2">February</option>

Categories