Is there a way to filter a multi-line select box using jQuery?
I'm a new to jQuery and can't seem to figure out the best way to do this.
For example if I have:
<select size="10">
<option>abc</option>
<option>acb</option>
<option>a</option>
<option>bca</option>
<option>bac</option>
<option>cab</option>
<option>cba</option>
...
</select>
I want to filter this list based on a selection drop down with:
<select>
<option value="a">Filter by a</option>
<option value="b">Filter by b</option>
<option value="c">Filter by c</option>
</select>
Something like this might do the trick (assuming you give your 'Filter by...' select an id of filter and the filtered / other select an id of otherOptions):
$(document).ready(function() {
$('#filter').change(function() {
var selectedFilter = $(this).val();
$('#otherOptions option').show().each(function(i) {
var $currentOption = $(this);
if ($currentOption.val().indexOf(selectedFilter) !== 0) {
$currentOption.hide();
}
});
});
});
UPDATE: As #Brian Liang pointed out in the comments, you might have problems setting the <option> tags to display:none. Therefore the following should give you a better cross-browser solution:
$(document).ready(function() {
var allOptions = {};
$('#otherOptions option').each(function(i) {
var $currentOption = $(this);
allOptions[$currentOption.val()] = $currentOption.text();
});
$('#filter').change(function() {
// Reset the filtered select before applying the filter again
setOptions('#otherOptions', allOptions);
var selectedFilter = $(this).val();
var filteredOptions = {};
$('#otherOptions option').each(function(i) {
var $currentOption = $(this);
if ($currentOption.val().indexOf(selectedFilter) === 0) {
filteredOptions[$currentOption.val()] = $currentOption.text();
}
});
setOptions('#otherOptions', filteredOptions);
});
function setOptions(selectId, filteredOptions) {
var $select = $(selectId);
$select.html('');
var options = new Array();
for (var i in filteredOptions) {
options.push('<option value="');
options.push(i);
options.push('">');
options.push(filteredOptions[i]);
options.push('</option>');
}
$select.html(options.join(''));
}
});
Related
I have drop down menu with some random values. When I select the value onchange event triggers and I want to add new drop down under it, but the new one should have all values except selected one in first drop down.
Now when I change value of second one, I need third one that has only non selected values from previous two drop downs.
What is the easiest way to do this in javaScript?
What I have for now is mechanism for adding new dropdowns, but for now I am filling it with some dummy data.
I need to implement function which I can call instead of dateGenerate()
I have to solve this without using jQuery :(
This is HTML:
Test:<br>
<select id="ddlTest" onchange="addNewTestDrop('newTest');">
<option value=""></option>
<option value="Raven">Raven</option>
<option value="PPA">PPA</option>
<option value="PPA+">PPA+</option>
<option value="Basic Knowledge">Basic Knowledge</option>
<option value="PCT">PCT</option>
</select>
<div id="newTest">
</div>
And this is javaScript I have:
function dateGenerate() {
var date = new Date(), dateArray = new Array(), i;
curYear = date.getFullYear();
for(i = 0; i<5; i++) {
dateArray[i] = curYear+i;
}
return dateArray;
}
function addNewTestDrop(divname) {
var newDiv=document.createElement('div');
var html = '<select>', dates = dateGenerate(), i;
for(i = 0; i < dates.length; i++) {
html += "<option value='"+dates[i]+"'>"+dates[i]+"</option>";
}
html += '</select>';
newDiv.innerHTML= html;
document.getElementById(divname).appendChild(newDiv);
}
Get all options except the one that has the same value as the select (as it's selected), clone them, and append to the new select
document.getElementById('ddlTest').addEventListener('change', function() {
var newSelect = document.createElement('select');
var options = [].slice.call(this.querySelectorAll('option')).forEach(function(elem) {
if (this.value !== elem.value) newSelect.appendChild(elem.cloneNode(true))
}.bind(this));
document.getElementById('newTest').appendChild(newSelect);
}, false);
FIDDLE
You can modify this code as you need.
$(document).ready(function() {
var selectWrapper = $('#select-boxes');
$(document).on('change', '.dynamic-select', function() {
var element = $(this);
var optionsLength = (element.find('option').length) - 1; // because we have an empty option
if(optionsLength === 1) {
return true;
}
var newSelect = $(this).clone();
newSelect.find("option[value='" + element.val() + "']").remove();
newSelect.appendTo(selectWrapper)
});
});
.dynamic-select{
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="select-boxes">
<select class="dynamic-select">
<option value=""></option>
<option value="Raven">Raven</option>
<option value="PPA">PPA</option>
<option value="PPA+">PPA+</option>
<option value="Basic Knowledge">Basic Knowledge</option>
<option value="PCT">PCT</option>
</select>
</div>
I have pair of text boxes. I need to find duplicate pair values in my select dropdown.
JSFIDDLE example
txt12 txt12
txt2 txt1
txt3 txt3
txt4 txt5
txt12 txt12
In my example, txt12 select pair is duplicated. I could possibly find each duplicate values by considering each select dropdowns.
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value); break;
}
else
values.push(select.value);
}
How is it possible to find duplicate pair of select dropdown values
You can use something like
function chkVal() {
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value);
}
else
values.push(select.value);
}
}
You have to just remove the break in the if block as it is moving out of the for loop in the first loop when it find text12.
Refer to the fiddle : "http://jsfiddle.net/sL6ofchd/9/"
With jQuery, try something like this:
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length );
});
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length + ' duplicates' );
duplicates.each(function(i) {
console.log( i, this, $(this).prev()[0] );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<select>
<option value="txt2">txt2</option>
</select> <select>
<option value="txt1">txt1</option>
</select><br><br>
<select>
<option value="txt3">txt3</option>
</select> <select>
<option value="txt3">txt3</option>
</select><br><br>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<input type="button" value="save" class="check-value">
How can I set/retrieve the last selected value of a select drop-down with JavaScript? I'm trying to create an onchange function on a select drop-down that that sets the selected option, and then on each page-load, that valued is loaded.
Here is the HTML
<select class="testSelect">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test2">test3</option>
<option value="test2">test4</option>
</select>
I'm having a little trouble with the JavaSCript though.
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var getLast = localStorage.getItem(select, lastSelected);
selectOption = getLast;
select.onchange = function () {
var lastSelected = select.options[select.selectedIndex].value;
localStorage.setItem(select, lastSelected);
}
and here's a fiddle http://jsfiddle.net/5yJNL/1/
The values in your HTML were wrong
<select class="testSelect">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
</select>
Javascript
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected) {
select.value = lastSelected;
}
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select', lastSelected);
}
http://jsfiddle.net/2MPPz/1/
You have at least two problems in your code.
The first one is an scope problem: The lastSelected variable is
local defined in your function. You must define as global variable.
The second one is that the first parameter of setItem & getItem
methods should be a String
So your corrected code looks like:
var lastSelected;
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var getLast = localStorage.getItem('select', lastSelected);
selectOption = getLast;
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
localStorage.setItem('select', lastSelected);
};
I would like to know how can we arrange the three select box, with having some options, it will be configured according to the previous select box value.
Please look at the code which we applied for our program.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var rtype = $("#rtype").val();
var rarray = rtype.split(' ');
var max_adults = rarray[1];
var min_adults = rarray[0];
//var max_adults = 3;
//var min_adults = 2;
$('#rooms').change(function(){
var room_num = $(this).val();
var options = '';
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) { options += '<option value="'+i+'">'+i+'</option>' } $('#person').html(options); }); $('#rooms').change(); });
</script>
</head>
<body>Room Type <select name="rtype" id="rtype"><option Selected value="">Select</option><option value="2 3">Room 2-3</option> <option value="3 4">Room 3-4</option></select> Category: <select name="rooms" id="rooms"> <option Selected value="">Select</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option> </select>Persons<select name="person" id="person"> </select></body>
Above this code is working fine if we remove the code for "rtype" ID, and entered the hard coded value to the query like this.
var max_adults = 3;
var min_adults = 2;
but we likt to update this value when we change the "rtype" id, the value for the an option is ( 2 3), we just have to split these value in to two part, the higher one will put into " var max_adults", and lower one will go to "var min_adult".
Please give me the proper solution, how can we arrange the codes accordingly.
You need to put the rtype code inside the change event handler tof the #rooms element:
$(function () {
$('#rooms').change(function(){
//get the `#rtype` value
var rtype = $("#rtype").val();
//check to make sure the `#rtype` value isn't an empty string
if (rtype != '') {
var room_num = $(this).val(),
rarray = rtype.split(' '),
options = '',
max_adults = rarray[1],
min_adults = rarray[0];
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) {
options += '<option value="'+i+'">'+i+'</option>';
}
$('#person').html(options);
} else {
//since no `#rtype` value was found alert the user
alert('Please Select a Room Type');
}
//trigger the change event by chaining rather than re-selecting the same element
}).change();
});
Update
To make one element appear when the other changes, add this to the document.ready event handler:
$('#rtype').change(function () {
//if a value has not been selected then hide the `#rooms` element, otherwise show it
if (this.value == '') {
$('#rooms').hide();
} else {
$('#rooms').show();
}
});
You then need to add the following CSS for the #rooms element:
#rooms {
display : none;
}
I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?
Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.
Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});
I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight