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();
Related
Here i have the javascript code for my task: https://jsfiddle.net/gckkvLcv/4/
<select id="s1">
<option selected="selected">USD</option>
<option>KZT</option>
<option>EUR</option>
</select>
<select id="s2">
<option>USD</option>
<option selected="selected">KZT</option>
<option>EUR</option>
</select>
I need to translate it to a jQuery version.
On a document load i can see the same values in a select lists. I need to disable that behavior.
Since you're using jQuery that could be done simply like :
$('.tracked_select').on('change', function() {
//Get selected options
var selected_options = $('.tracked_select').map(function(){
return this.value
}).get();
//Disable the already selected options and enable others
$('.tracked_select option').each(function(index) {
$(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
});
});
Hope this helps.
trigger_chane();
$('.tracked_select').on('change', function() {
trigger_chane();
});
function trigger_chane(){
var selected_options = $('.tracked_select').map(function(){
return this.value
}).get();
$('.tracked_select option').each(function(index) {
$(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="tracked_select">
<option selected="selected">USD</option>
<option>KZT</option>
<option>EUR</option>
</select>
<select class="tracked_select">
<option>USD</option>
<option selected="selected">KZT</option>
<option>EUR</option>
</select>
<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 want to set the selected value of a select box if it exists, and to add it to the select box if it does not exist.
How do I do that?
I have:
<select id="abc" name="abc">
</select>
I want:
$('#abc').val(123);
afterwards:
<select id="abc" name="abc">
<option value="123" selected>
</select>
You can append element
var html = '<option value="123">123</option>';
jQuery("#abc").append(html);
How about the below code.
if($('#abc option[value=' + testValue + ']').length === 0) {
$('#abc').append('<option value="' + testValue + '">' + testValue + '</option>');
}
First thing is that you can use jQuery append method to add any html element to your page. In this case, you may need to append an option element. So first thing you need is to check if that option exists. If it does not you need to append it into the select element. In both cases( whether it exists or not), you can set the value as selected using val() method:
$(document).ready(function(){
select123();
});//document ready
function select123()
{
if( ! $("#abc option[value=123]").length )
{
$("#abc").append('<option value="123">123</option>');
}
$("#abc").val("123");
}//select123
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="abc" name="abc">
</select>
var valueExists = $("#abc option[value=123]");
if(!valueExists){
("#abc").append('<option>123</option>')
}
$("#abc option[value=123]")
will return empty array which is evaluted to "" so it is false otherwise Array of object of html Collection returned
Check if the value exists using $("#abc option[value='123']").length > 0 and if not, append.
$(function(){
var val = '1234';
if($("#abc option[value='123']").length > 0){
alert('present')
}
else {
var s = '<option value=' + val + '>' + val + '</option>';
$('#abc').append(s);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="abc" name="abc">
<option value="123" selected>
</select>
Below code can help you started.
If the value is already present, then set it as the selected option.
Else append the value to dropdown.
Scenario 1: Value already exists in dropdown. So just select it.
$(function() {
var val = '1';
var exists = false;
$('#abc option').each(function() {
if (this.value == val) {
$('#abc').val(val);
exists = true;
return false;
}
});
if (exists == false) {
$('#abc').append('<option value="' + val + '" selected>' + val + '</option>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="abc" name="abc">
<option value="1">1</option>
<option value="2">2</option>
</select>
Scenario 2: Value not in dropdown. So append it.
$(function() {
var val = '123';
var exists = false;
$('#abc option').each(function() {
if (this.value == val) {
$('#abc').val(val);
exists = true;
return false;
}
});
if (exists == false) {
$('#abc').append('<option value="' + val + '" selected>' + val + '</option>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="abc" name="abc">
<option value="1">1</option>
<option value="2">2</option>
</select>
I am trying to change a select option on click but I don't want to use the option value. My code works if I give my button a value='3' but what I want is to select the one with data-price="0" which in my case is the one with value='3'.
JS :
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option').val(jQuery(this).attr('value'));
});
});
Html :
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
Any help will be appreciated
You can use attribute equals selector to get the option and then select option by setting selected property using prop() method.
jQuery(document).ready(function() {
jQuery('#sample-addtocart-button').click(function() {
jQuery('.product-custom-option option[data-price="' + jQuery(this).attr('value') + '"]').prop('selected', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
You can select elements by attribute, and then set the selected property on the element.
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option [data-price=' + this.value + ']').prop("selected", true);
});
});
This selects the element with a data-price attribute equal to the value of this.value, which is a descendant of .product-custom-option, and sets its selected property to true.
Without jQuery, it could look like this:
document.addEventListener("DOMContentLoaded", function () {
document.querySelector('#sample-addtocart-button').addEventListener("click", function(){
document.querySelector('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
And a handful of helper methods always helps with the verbosity:
function listen(el, typ, fn, cap) {
el && el.addEventListener(typ, fn, cap)
}
function query(el, sel) {
if (typeof el === "string") {
sel = el;
el = document;
}
return el.querySelector(sel)
}
listen(document, "DOMContentLoaded", function () {
listen(query('#sample-addtocart-button'), "click", function(){
query('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
Try this:
jQuery('#sample-addtocart-button').click(function(){
var val= jQuery(this).attr('value');
jQuery('.product-custom-option option[data-price='+val+']').prop('selected', true); // it will find the select option with certain data-price and make it selected
});
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');
});