Hi I am using jquery chosen plugin. I want to selected menu value by selected value from other select menu. But my code working with simple selected menu. I want it to work with jquery chosen plugin. Example code
$(".chzn-select").chosen()
$('[id*=second]').change(function(){
var val = $(this).find('option:selected').val()
if(val.toLowerCase()=='mr'){
$('[id*=gender]').find('option').eq(0).attr('selected', 'selected');
}
else{
$('[id*=gender]').find('option').eq(1).attr('selected', 'selected')
}
})
You should add value to the options and try to match those value onchange. See my implementation below and let me know if it works for you.
Edit: Added few lines to update the plugin selection.
DEMO: http://jsfiddle.net/vUkQg/3/
Note: Below method can relate any number of drop downs with just same class and value.(no change to the script) http://jsfiddle.net/vCE4Y/18/
HTML:
<select id="second" class="chzn-select" style="width:100px">
<option value="1"> mr</option>
<option value="2"> mrs</option>
</select>
<select id="gender" class="chzn-select" style="width:100px">
<option value="1"> male</option>
<option value="2"> female</option>
</select>
JS:
$(function() {
$(".chzn-select").chosen().change(function() {
var val = $(this).val();
$('.chzn-select').val(val);
$('.chzn-select').not(this).each(function () {
var $chzn = $('#' + this.id + '_chzn');
var $li = $chzn.find('li');
$li.removeClass('result-selected');
var selectedLi = $li.eq(val - 1);
selectedLi.addClass('result-selected');
$chzn.find('a.chzn-single span').html(selectedLi.html());
//update selected result in plugin
var $data = $(this).data('chosen');
$.each($data['results_data'], function (idx, el) {
if (idx == val-1) {
el.selected = true;
$data.result_single_selected = selectedLi;
} else {
el.selected = false;
}
});
});
});
});
Demo
I hope the below script does what you expect
$(".chzn-select").chosen();
$('[id*=second]').change(function(){
var val = $('div[id*=second]').find('li.result-selected').html().trim();
$('select[id*=gender]').find('option').removeAttr('selected');
$('div[id*=gender]').find('li.active-result').removeClass('result-selected');
var selectedValue = "";
if(val.toLowerCase()=='mr'){
selectedValue = $('div[id*=gender]').find('li.active-result').eq(0).addClass('result-selected').html();
$('select[id*=gender]').find('option').eq(0).attr('selected','selected');
} else {
selectedValue = $('div[id*=gender]').find('li.active-result').eq(1).addClass('result-selected').html();
$('select[id*=gender]').find('option').eq(1).attr('selected','selected');
}
$('div[id*=gender]').find('a.chzn-single span').html(selectedValue);
});
Use selectedIndex
eg:
document.getElementById('selectId').selectedIndex = 0;
//selectId - id of the select elem
<select id="selectId">
<option value="1" selected="selected">Male</option>
<option value="2">Female</option>
</select>
To get the Selected value
var e = document.getElementById("selectId");
var strUser = e.options[e.selectedIndex].value;
here strUser = 1;
if you want the TEXT
var strUser = e.options[e.selectedIndex].text;
here strUser = Male;
i think this helps you.
<select id="second" class="chzn-select" style="width: 100px">
<option value="1">mr</option>
<option value="2">mrs</option>
</select>
<select id="gender" class="chzn-select" style="width: 100px">
<option value="1">male</option>
<option value="2">female</option>
</select>
$(document).ready(function () {
$('.chzn-select').change(function () {
$('.chzn-select').val($(this).val());
//$('.chzn-select').val($(this).val()).trigger('change');
});
});
Demo
I used the value of the options, the minus 1 is to reach the indexnumber
DEMO
$('#second').change(function(){
var val = $(this).val();
$('#gender option').eq(val - 1).attr('selected', 'selected');
});
or
$('#second').change(function(){
var index = $(this)[0].selectedIndex;
$('#gender option').eq(index).attr('selected', 'selected');
});
Related
I am using a jquery code found on Stakeoverflow to remove duplication value in the dropdown. my problem is the jquery code worked for the first dropdown but will not work for the second dropdown any help will be welcome
1st dropdown
<select id="AssetStoredWhere" name="AssetStoredWhere" class="form-control js-example-disabled-results
select">
<option value="#ViewBag.AssetStoredWhere">#ViewBag.AssetStoredWhere</option>
<option value="UK">UK</option>
<option value="EU">EU</option>
<option value="Worldwide">Worldwide</option>
</select>
2bd Dropdown
<select asp-for="Dpiaavailable" id="Dpiaavailable" name="Dpiaavailable" class="form-control js-
example-disabled-results select">
<option value="#ViewBag.Dpiaavailable">#ViewBag.DpiaavailableValue</option>
<option value="False">No</option>
<option value="True">Yes</option>
</select>
Jquery code
var seen = {};
jQuery('.select').children().each(function () {
var txt = jQuery(this).attr('value');
if (seen[txt]) {
jQuery(this).remove();
} else {
seen[txt] = true;
}
});
You need another loop to iterate through the select elements themselves, not through the option elements of every select as one. Try this:
$('.select').each(function() {
var seen = {};
$(this).children().each(function() {
var $option = $(this);
if (seen[$option.val()]) {
$option.remove();
} else {
seen[$option.val()] = true;
}
});
});
I'm using multiple select for fill a simple select. I'm trying to if I select a value and it doesn´t exists append to simple select, if exists do not do anything, but if I unselect option, remove it from simple select. How could I do that?
$(function() {
$(document).on('change', '#foo', function() {
var values = $(this).val();
values.forEach(function(val) {
$('#bar option').each(function() {
var v = $(this).val();
if (values.indexOf(v) === -1) {
$('#bar').append('<option value="' + val + '">' + val + '</option>');
return false;
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled>Add some from multiple</option>
</select>
Remove all options except the disabled one from #bar after #foo changed and create new options and appendTo() #bar.
$(function() {
$(document).on('change', '#foo', function() {
var values = $(this).val() || []; // in case you don't select anything
$('#bar option:not(:disabled)').remove()
values.forEach(function(val) {
$('<option>', {
value: val,
text: val
}).appendTo('#bar')
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled>Add some from multiple</option>
</select>
You have to empty the children upon every change or else the new <option>s will get appended and the list becomes very long. Try this:
$(function() {
$(document).on('change', '#foo', function() {
var values = $(this).val();
$('#bar').empty().append('<option selected disabled>Add some from multiple</option>');
values.forEach(function(val) {
$('#bar option').each(function() {
var v = $(this).val();
if (values.indexOf(v) === -1) {
$('#bar').append('<option value="' + val + '">' + val + '</option>');
return false;
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled>Add some from multiple</option>
</select>
You should bind click event rather than change, because if you click same option twice, change event cannot be listened.
You can try the following code.
$(function() {
//get onclick value
$(document).on('click', '#foo', function() {
let value = $(this).val();
//get existing values in #bar
let exist = false;
$("#bar option").each(function(){
if($(this).val() == value){
exist = true;
//remove if exist
$(this).remove();
}
});
//append if not exist
if(!exist){
$('#bar').append(`<option value="${value}">${value}</option>`);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="foo">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="bar">
<option selected disabled value="default">Add some from multiple</option>
</select>
Well you're going to have more problems than this I think, but if you're just looking how to remove an option, you could do something like this
$("#bar option([value=" + val+ "]").remove();
<div id="div1">
<input id="input1">
<select multiple="multiple" id="select1">
<option value="sandeep">sandeep</option>
<option value="ram">ram</option>
<option value="raj">raj</option>
<option value="pak">pak</option>
<option value="abc">abc</option>
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="journey">journey</option>
<option value="mahesh">mahesh</option>
</select>
</div>
<script type="text/javascript">
var selectClone1;
selectClone1 = $('#select1 option').clone();
$('#input1').on('keyup', function(){
$('#select1 option').remove();
var value = $(this).val();
selectClone1.filter(function(index, element){
console.log('index : '+index);
console.log('element : '+element);
return value == '' || element.value.indexOf(value) >= 0;
}).appendTo('#select1');
});
$('#select1').on('click', function(){
var option = $('option:selected', this).clone();
$('option:selected', this).remove();
selectClone1 = $.grep(selectClone1, function(el){return el.value == option[0].value}, true);
</script>
I am working on the search functionality along with removal of options when user clicked on option. The above code is working properly for search but when i clicked an option to delete from select box after search for a value, parameters of filter function(index, element) getting exchanged. Due to it error is coming. Can you help me guys where i am missing the point.
Better to use Array's splice method for removing element from main array and no need to clone.
$('#select1').on('click', function(){
var option = $('option:selected', this);
$('option:selected', this).remove();
selectClone1.splice($.inArray( option[0], selectClone1 ), 1);
});
i have a bit of problem to deal with the option value in jquery. which i have 2 kind of select and one of theme contain an array. some how i dont know how to compared them.
example:
<select id="category">
<option value="[1,2]"> category fruit</option>
<option value="[3,4]"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
script:
$(function(){
var $article = $('#article > option').each(function(){
//var $v = $(this).val();
//console.log($v);
return $(this).val();
});
$('#categorie').on('change', function(){
var $e = $(this).val();
console.log($e);
if($e == $article){
// here should be the value from the article was choosed from category
}else{
console.log('there are no entries')
}
});
})
but i dont know how to compare theme properly. and it should be if #category [1,2] selected then the #article 1 and 2 only shown in option and the other should be hidden. any kind of idea or suggestion thank you very much. best regard.
You can use something like that. It works for me.
Here is html.
<select id="category">
<option value="[1,2]"> category fruit</option>
<option value="[3,4]"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
And here is jquery.
$(document).ready(function(){
function checkData(value){
var $e = value;
$('#article > option').each(function(index, item) {
if ($e.indexOf($(item).val()) === -1) {
$(item).hide();
} else {
$(item).show();
}
});
}
$('#category').change(function(){
checkData($(this).val());
});
checkData($('#category').val());
});
I think that may help you.
Thanks
First of all there is a typo categorie. It should be category
Try this
var opts = [];
$('#article > option').each(function(){
opts.push($(this).val());
});
console.log(opts)
$('#category').on('change', function(){
var $e = $(this).val();
var present = false;
$(opts).each(function(i,v){
if($e[1]==v){
present= true;
console.log($e[1])
}
});
if(!present){
console.log('there are no entries')
}
});
Demo
You need to get the select value [1,2], then use JSON.parse to make that and array. Then you can search it.
var $article = [];
$(function() {
$article = $('#article > option').map(function() {
return parseInt(this.value);
}).get();
console.log($article);
$('#category').on('change', function() {
var $e = JSON.parse(this.value);
console.log($e);
valid = false;
$.each($e, function(i, val){
valid = valid || $.inArray(val, $article) != -1;
});
if (valid)
alert('Exists' + $e.join())
else
console.log('there are no entries')
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="category">
<option value="[1,2]">category fruit</option>
<option value="[3,4]">category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
try this:
if($e.indexOf($article)!=-1){
}else{
console.log('there are no entries')
}
Try this option, working example jsfiddle
$('#categorie').on('change', function(){
var $e = $(this).val();
$('#article > option').each(function(index, item) {
if ($e.indexOf($(item).val()) === -1) {
$(item).hide();
} else {
$(item).show();
}
});
});
The value inside first select element is not an array, it just a string, remove bracket and leave only number with comma separated like following :
HTML
<select id="category">
<option value="1,2"> category fruit</option>
<option value="3,4"> category vegies</option>
</select>
<select id="article">
<option value="">chose</option>
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
Js
(first option)
// use this
$('#category').change(function(){
var cat = $( this ).val().split(',');
$('#article option').hide()
$.each(cat,function(i,e){
$('#article option[value="'+e+'"]').show()
})
});
(second option)
//or use this : filter out only matched element
var cacheElem = $('#article option').detach();
$('#category').change(function(){
$('#article option').remove();
var cat = $( this ).val().split(',');
var h = cacheElem.filter(function(){
return $.inArray(this.value, cat) !== -1 && this
});
$('#article').append(h)
});
DEMO
I'm not sure of your flexibility to change the category option value attribute but I took the liberty to take another approach to your issue.
I created an object with a list of possible items to display.
The select id="category" options value is the name of the list of items I want to display.
When the category changes I update the article select with only the list of items I want to show.
<select id="category">
<option value="fruits"> category fruit</option>
<option value="vegies"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
</select>
as for the JavaScript
$(function(){
var items = {
fruits: ["banana", "mango"],
vegies: ["letus", "spinash"]
};
var current = items[0];
var updateOptions = function(cat_in) {
current = cat_in;
output = "";
for(var i = 0; i<items[cat_in].length; i++) {
output += '<option value="'+i+'">'+items[cat_in][i]+'</option>';
}
return output;
};
$('#category').on('change', function(){
var $e = $(this).val();
if($e == current) return;
var options = updateOptions($e);
$("#article").empty().append(options);
});
});
Here is a live example: https://jsfiddle.net/marioandrade/mkt16n1g/1/
Seems pretty simple:
$('#category').on('change', function() {
var currentCategory = $(this).val();
// reset and show/hide group items
$('#article').val("").find('option').each(function(index) {
$(this).toggle(!(currentCategory.indexOf($(this).val()) === -1));
});
}).triggerHandler('change');
I have two dropdowns, both have the same items in them. If an option is selected in dropdown 1 then I would like to hide that option in dropdown 2. When it is unselected in dropdown 1 I would like it to appear again in dropdown 2 and whichever option is then selected to then be hidden in dropdown 2. I am trying to have this exclude the blank option in the first index.
Here is a codepen that I started, but I am not sure where to go from here:
http://codepen.io/cavanflynn/pen/EjreJK
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function () {
var selectedItem = $($dropdown1).find("option:selected").val;
});
Thanks for your help!
As said in comments, one of the options is to disable/enable options according to the selection in the first select, like below. This would work on all browsers as opposed to hide/show which doesn't.
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function() {
$dropdown2.find('option').prop("disabled", false);
var selectedItem = $(this).val();
if (selectedItem) {
$dropdown2.find('option[value="' + selectedItem + '"]').prop("disabled", true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="dropdown1">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<select name="dropdown2">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
Another option is to remove/add options in the 2nd dropdown based on the selection in the first via .clone(), as below.
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function() {
$dropdown2.empty().append($dropdown1.find('option').clone());
var selectedItem = $(this).val();
if (selectedItem) {
$dropdown2.find('option[value="' + selectedItem + '"]').remove();
}
});
A Demo
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function() {
var selectedItem = $(this).val();
var $options = $("select[name='dropdown1'] > option").clone();
$("select[name='dropdown2']").html($options);
$("select[name='dropdown2'] > option[value="+selectedItem+"]").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="dropdown1">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<select name="dropdown2">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
Demo
You should use this plugin http://gregfranko.com/jquery.selectBoxIt.js
It has some really nice callbacks and customisation options.
When one changes you can put it in the callback to update the other.
Here is one way of doing it. You do need to include jQuery, and then as long as the value isn't empty hide the option with the similar value.
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
$dropdown1.change(function() {
$dropdown2.children().show();
var selectedItem = $($dropdown1).val();
if (selectedItem != "")
$('select[name="dropdown2"] option[value="' + selectedItem + '"]').hide();
});
$dropdown2.change(function() {
$dropdown1.children().show();
var selectedItem = $($dropdown2).val();
if (selectedItem != "")
$('select[name="dropdown1"] option[value="' + selectedItem + '"]').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="dropdown1">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<select name="dropdown2">
<option></option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
Here's an approach that stores a set of the options on page load then filters the alternate select when a change is made. It works in both directions for changes made to either select
var $drops = $('.drop'),
// store a set of options
$options = $drops.eq(1).children().clone();
$drops.change(function(){
var $other = $drops.not(this),
otherVal = $other.val(),
newVal = $(this).val(),
$opts = $options.clone().filter(function(){
return this.value !== newVal;
})
$other.html($opts).val(otherVal);
});
Values will also be maintained and this is 2 directional so a change in either will filter the other
DEMO
Well, this code will find option by value in necessary selects and remove it.
http://codepen.io/anon/pen/LVqgbO
var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");
var populateDropdown = function(element) {
element.find("option").remove();
element.append("<option></option>");
// There should be real data
for (var i = 1; i <= 3; i++) {
element.append("<option value='" + i + "'>Test " + i + "</option>");
}
}
var getOptionProps = function(element) {
var selectedValue = element.val();
var selectedText = element.find("option[value=" + selectedValue + "]").text();
return { text: selectedText, value: selectedValue };
}
var removeOptionWithValue = function(element, value) {
element.find("option[value='" + value + "']").remove();
}
$dropdown1.on("change", function () {
var selectedProps = getOptionProps($(this));
populateDropdown($dropdown2);
removeOptionWithValue($dropdown2, selectedProps.value);
});
$dropdown2.on("change", function () {
var selectedProps = getOptionProps($(this));
populateDropdown($dropdown1);
removeOptionWithValue($dropdown1, selectedProps.value);
});