jquery "clear" value in select box - javascript

So I have some markup that looks like this, And some jQuery javascript:
let color_select = $('select#SelectByColor');
color_select.val([]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="SelectByColor" class='filter-select' name='color'>
<option value="">By color</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green" selected="selected">Green</option>
<option value="Yellow">Yellow</option>
</select>
<button id="FilterReset">Reset</button>
That gets invoked when the "Reset" button is clicked. It pretty much works - when you
click the reset button. the Select box value gets set to "". BUT.. the visual display
of the select box is also set to blank, not "By color". Why is this the case?
In addition, according to the Chrome DevTools, the selected option is still Green.

Set the value to an empty string, not an array.
$("#FilterReset").click(function() {
let color_select = $('select#SelectByColor');
color_select.val("");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="SelectByColor" class='filter-select' name='color'>
<option value="">By color</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green" selected="selected">Green</option>
<option value="Yellow">Yellow</option>
</select>
<button id="FilterReset">Reset</button>

The value you set for the selector in the .val(...) function to needs to match the value="..." in HTML. So that should be color_select.val( "" )
Here's a code that works and a codepen:
jQuery($ => {
$('#FilterReset').on('click', () => {
$("#SelectByColor").val("");
});
});

Related

How to set default selection based on another selection

I have multiple dropdown selections on a single page with exact same options but different IDs. I need dropdown A and B to have the same option selected at all times but only if they both share those options.
I'm a javascript noob so I've tried many variations of code but nothing works, I think it's best if someone could write this simple code from scratch.
Imagine these two selections with cloned options:
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
If you select red in ID california it needs to switch to red in ID texas, and vice versa.
You can add a common class and select on the change event something like following
Jquery
$(document).ready(function(){
$(".select").change(function() {
$(".select").not(this).find("option[value="+ $(this).val() + "]").attr('selected', true)
});
});
Pure JavaScript Solution as already written by #Emeeus
const selectElement = [...document.getElementsByClassName("ClassName")];
selectElement.forEach(a => {
a.addEventListener("change", (e) => {
selectElement.forEach(aa => {
if (aa.querySelectorAll(`option[value=${e.target.value}]`).length)
aa.value = e.target.value;
})
})
})
A simple way to get this done is :
reference the select elements in JavaScript and store the two of them in an array.
when looping through the selects we can store the index of the current select, that has to be used to get the other select (a simple mathematical calculation).
loop through that array (that means looping through the selects) and attach a change event listener to each one of the select elements.
fetch the option that has to be selected, if found, after filtering the options of the other select based on the value of the selected option.
if there's an option that has the same value as the selected option, select that option in the other select.
This may still a bit ambiguous, a demo is worth a hundred docs :
the next demo takes into consideration that an/some option(s) may not appear in both of the select elements, simply nothing will happen and the same functionality stays as is.
/** an array that stores the selects **/
const selects = [document.getElementById('california'), document.getElementById('texas')];
/** ## cycle through these selects
* el: current select in the loop.
* idx: its index in the "selects" array.
**/
selects.forEach((el, idx) => {
/** attach change listener **/
el.addEventListener('change', () => {
/** get the option that should be selected in the other select if found there **/
/** "selects[Math.abs(idx - 1)]" gets the other select (the one that isn't changed) **/
const toBeSelected = [...selects[Math.abs(idx - 1)].options].filter(o => o.value === el.options[el.selectedIndex].value);
/** if we have an option from the other select's options that has the same value as the selected one then return in order to be selected **/
/** if ther's an option that matches the above condition simply select it **/
toBeSelected[0] && (selects[Math.abs(idx - 1)].selectedIndex = toBeSelected[0].index);
});
});
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<!-- new option that doesn't exist in the other select element -->
<option value="green">green</option>
</select>
The ideal solution would be using classes, but with that HTML here a solution:
const selects = [...document.getElementsByTagName("select")];
selects.forEach(s => {
s.addEventListener("change", (e) => {
selects.forEach(sl => {
if (sl.querySelectorAll(`option[value=${e.target.value}]`).length)
sl.value = e.target.value;
})
})
})
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="brown">brown</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="las_vegas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
this is very simple code :
<select id="california" onclick="applyEvent()">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="brown">brown</option>
</select>
<select id="texas" onclick="apply_Event()">
<option value="red"">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="brown">brown</option>
</select>
<script type="text/javascript">
function applyEvent() {
document.getElementById("texas").value = document.getElementById('california').value;
}
function apply_Event() {
document.getElementById("california").value = document.getElementById('texas').value;
}
</script>
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<script>
var californiaSelect = document.getElementById('california');
var texasSelect = document.getElementById('texas');
californiaSelect.addEventListener('change', () => {
texasSelect.value = californiaSelect.value;
})
texasSelect.addEventListener('change', () => {
californiaSelect.value = texasSelect.value;
})
</script>
You can find a working example is this fiddle
getElementById
addEventListener

How to empty a value from the first option of a select box option using javascript or jquery?

Here's my code. Is it possible to empty the value of the first option using jquery/javascript ?
<select id="select_1" name="select_1" class="category-select required">
<option value="0">Select category</option>
<option value="1">Phones</option>
<option value="2">Computers</option>
<option value="3">Tablets</option>
</select>
so it will become like that:
<option value="">Select category</option>
I already know that i can remove the whole first option by targeting its value
$("#select_1 option[value='0']").remove();
You can use plain javascript to get the first option of a select element using .options like so, which returns an indexed collection, so you can just use zero based index to grab the first option and set it's value property:
document.getElementById("select_1").options[0].value = '';
To target the first element of a collection use :first. Then you can use val('') to remove the value from it:
$('#select_1 option:first').val('');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select_1" name="select_1" class="category-select required">
<option value="0">Select category</option>
<option value="1">Phones</option>
<option value="2">Computers</option>
<option value="3">Tablets</option>
</select>
<script>
$(document).ready(function (){
$('#btnremoveoption').click(function (){
$('#select_1 option:first').remove();
});
});
</script>
<body>
<select id="select_1" name="select_1" class="category-select required">
<option value="0">Select category</option>
<option value="1">Phones</option>
<option value="2">Computers</option>
<option value="3">Tablets</option>
</select>
<input type="button" id="btnremoveoption" value="Click to Remove all Options" onclick="Remove_options()"/>
</body>
This Program will keep Removing first option when ever button will be click.
$(document).ready(function (){
$('#select_1 option:first').remove();
});
this will remove it onload of the page. without leaving the option blank it will be filled with the next option.

JQuery Set selected option

I have two selection boxes, the default value is - and i want to pick something else for both, my first problem is both fields have dynamic id like prod-685209-Size so i'm having trouble accessing with id.
I have the following HTML:
<select class="sku-attr" name="Size">
<option value="_def">-</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<select class="sku-attr" name="Color">
<option value="_def">-</option>
<option value="Black">Black</option>
<option value="Blue">Blue</option>
</select>
So i executed the following:
document.getElementsByTagName('select')[0].selectedIndex = 2
document.getElementsByTagName('select')[1].selectedIndex = 2
It worked on the front side, showing my new options but it didn't prompt the backend as it is not actually selecting the options. Backend works fine when i click to these options by hand, basically i need another solution to choose these options.
If I don't misunderstood your requirement then you need something like this. Just add two different ids to your select element and attach a change event listener. For example size and color
var s = document.getElementById("size");
var c = document.getElementById("color");
function getSize() {
sizeSelected = s.value;
console.log('size=' + sizeSelected);
}
function getColor() {
colorSelected = c.value;
console.log('color=' + colorSelected);
}
s.addEventListener('change', getSize);
c.addEventListener('change', getColor);
<select id="size" class="sku-attr" name="Size">
<option value="_def">-</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<select id="color" class="sku-attr" name="Color">
<option value="_def">-</option>
<option value="Black">Black</option>
<option value="Blue">Blue</option>
</select>
You need to add .validate() after your dom commands to actually prompt the page.

Mutually exclusive select boxes

I have 2 select boxes. On change of one select box, I want the other select box to be defaulted to Select a value, ie val()==0, and vice versa. Only one select box should have a value selected at a time. How do I do this? I tried the code below but it does not work.
$("#select_one").change(function() {
if ('#select_two'.val() != 0) {
$('#select_two').val(0);
}
});
The simplest way to do this would be to place a common class on both the select. You can then select that class in jQuery and use not() to exclude the current element before resetting the value, something like this:
$('.select').change(function() {
$('.select').not(this).val(0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-one" class="select">
<option value="0">Please select</option>
<option>Foo</option>
<option>Bar</option>
<option>Fizz</option>
<option>Buzz</option>
</select>
<select id="select-two" class="select">
<option value="0">Please select</option>
<option>Foo</option>
<option>Bar</option>
<option>Fizz</option>
<option>Buzz</option>
</select>
You may set the selectedIndex to 0:
$('select[id^="select_"]').on('change', function(e) {
$('select[id^="select_"]').not(this).prop('selectedIndex', 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_one">
<option value="volvo">1</option>
<option value="saab">2</option>
<option value="mercedes">3</option>
<option value="audi">4</option>
</select>
<select id="select_two">
<option value="volvo">11</option>
<option value="saab">22</option>
<option value="mercedes">33</option>
<option value="audi">44</option>
</select>
That could be done using two simple change events, like the following example.
Else if you want to use one event you could use a common class as #Rory McCrossan answer shows..
Hope this helps.
$("#select_one").change(function() {
$('#select_two').val(0)
});
$("#select_two").change(function() {
$('#select_one').val(0)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_one">
<option value="0">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<br>
<select id="select_two">
<option value="0">Default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>

Adding/Removing/Updating options from select inputs

Here is what I've started to do: http://jsfiddle.net/nd9ny/
For now it doesn't work as I want it to.
I want to update options each time when a new select input is added or an input is removed.
For example, we have our first select input with these options:
<select>
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
<option value="4"></option>
</select>
When I add new input to my page, I want my function to update all the inputs and to remove the newly selected option from them.
<select>
<option value="1" selected></option>
<option value="3"></option> // The second one is removed
<option value="4"></option>
</select>
<select>
<option value="2" selected></option> // The first one is removed
<option value="3"></option>
<option value="4"></option>
</select>
And then, If I remove the first input, the second one becomes:
<select>
<option value="1"></option>
<option value="2" selected></option>
<option value="3"></option>
<option value="4"></option>
</select>
Pure Javascript code needed.
You may try the following solution:
- CSS:
.hidden {
display: none;
}
- JS function:
function hide_selected(el) {
var index = el.selectedIndex;
// Show every options
for(var i=0; i<el.length; i++)
el[i].className="";
// Hide the selected one
el[index].className="hidden";
}
- HTML example:
<body>
<select onchange="javascript:hide_selected(this);">
<option value="1" class="hidden" selected="selected">1</option>
<option value="2" class="">2</option>
<option value="3" class="">3</option>
<option value="4" class="">4</option>
</select>
</body>
Note: This function was tested with Firefox, you may have to check if this works with other browsers.
Hope this helps

Categories

Resources