Jquery to set only one selected option - javascript

I'm using an html select from which i need to get only one selected value, while debugging using firebug i'd seen 2 options are selected.
How can make this mutually exclusive using a jquery? Please help
<select id="test" title="select table" class="selectChangeClass">
<option value="None">None</option>
<option value="Equal">Equal</option>
<option value="NotEqual">NotEqual</option>
<option value="LessThan">LessThan</option>
<option value="GreaterThan">GreaterThan</option>
<option value="LessthanOrEqual">LessthanOrEqual</option>
<option value="GreaterthanOrEqual">GreaterthanOrEqual</option>
</select>
Script
$('.selectChangeClass').live('change', function(event) {
var changedText = $(this).val();
var controlId = this.getAttribute('id');
var indexSelected = this.selectedIndex;
//
this.selectedIndex = indexSelected;
$('#test' option[value="' + changedText + '"]').attr('selected', 'selected');
var opt = $('#' + controlId + ' option[value="' + changedText + '"]');
var html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);
});

try
$("#selecID").change(function(e){
var selectedVal = $(this).val();
console.log(selectedVal);
});
EDIT
var selVal = $("#test :selected").val();
alert(selVal);
DEMO
also see this to how to change the selected option http://jsfiddle.net/9ftwG/1/
and this http://jsfiddle.net/9ftwG/4/ to see how to clone and change the selected option

I am not entirely sure i understand the issue. At what point are you getting two options selected? Is Multiple set on the select?
Here is a JSFiddle updating a div on change of a select: http://jsfiddle.net/aMs8G/.

Related

Unable to select the value automatically in drop down for second time

I've the html as scripted below
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<select id="drop_down_id">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
</body>
</html>
For this html, i'm selecting the option dynamically by using below code
var theText = "Saab";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();//If we not using change() also it'll work
at first time it's working fine but when i'm using it for second time with the same option it's not selecting the option
Explanation
Let assume, for first time I've selected the value Saab then I've selected Volvo and Audi. If tried again to select Saab or Volvo or Audi it's not selecting the option. Any one know how to achieve it in jQuery or JavaScript
Once you select one option, it will add selected attribute to that option. You are not removing the existing selected options So before you try selecting again you should remove the selected attribute from existing options
https://jsfiddle.net/9v8way30/6/
$(document).ready(function(){
var theText = "Audi";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();
theText = "Saab";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();
$('#drop_down_id option').removeAttr('selected');
theText = "Audi";
$("#drop_down_id option:contains(" + theText + ")").attr('selected', 'selected').change();
})
The above code adds the 'selected' attribute for each option which you are changing dynamically. Initially you need to remove the existing selected attribute from options
$("#drop_down_id").on('change', function() {
var value = $(this).val();
$(this).find('option').removeAttr("selected");
$(this).find('option[value="' + value + '"]').attr("selected", "selected");
});

Why jQuery Select box change event is not working?

I am working on product filters where user select from the select box according to his/her preference but I am not getting selected value by user in jQuery.
html code:
<select name="product_filter" id="product_filter">
<option value="price_low_first">Price : Low to High</option>
<option value="price_high_first">Price : High to Low</option>
<option value="latest">Latest</option>
<option value="popular">Most Popular</option>
</select>
jQuery code:
$(function () {
$("#product_filter").change(function () {
alert("hi")
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
});
});
Hi I believe that your code is perfect. Once please check jquery.min.js is included in your file. Please check if there are any console errors.Thank you.

get unselected option from multiple select list

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value

Dynamic Dropdown Lists (JSFiddle Included)

I have two dropdown lists as shown in the below JSFiddle:
https://jsfiddle.net/jkw8fxzf/4/
HTML:
<select id="first-choice">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
<select id="second-choice">
<option value="Spanish">Spanish</option>
<option value="English">English</option>
</select>
JS:
$("#first-choice").change(function() {
var userSelected = $(this).val()
alert(userSelected);
});
What I'm trying to do is as follows: If the users first-choice is English, then only display Spanish as an option in the second-choice dropdown. If the users first-choice is Spanish, then only display English in the second-choice dropdown.
Any thoughts on how to do this. Normally I would use an AJAX request and then catch the user selected paramater in the controller but since this is a devise registrations controller I've had issues overriding it.
If I understand your question, just use this. it's easy:
https://jsfiddle.net/sherali/jkw8fxzf/12/
var $secondOption= $('#second-choice>option').clone();
$("#first-choice").change(function() {
var userSelected = $(this).val();
$('#second-choice').html($secondOption);
// $("#second-choice").val(userSelected)
$('#second-choice option[value="'+userSelected+'"').remove()
});
You could dynamically append data into second-choice like this...
<select id="first-choice">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
<select id="second-choice">
</select>
JS:
$("#first-choice").change(function() {
var userSelected = $(this).val()
if($(this).val() == "English"){
var element = "option";
var val = "Spanish";
var html = "<"+element+" value='"+val+"'>"+val+"</"+element+">";
$("#second-choice").empty();
$("#second-choice").append(html);
}
else if($(this).val() == "Spanish"){
var element = "option";
var val = "English";
var html = "<"+element+" value='"+val+"'>"+val+"</"+element+">";
$("#second-choice").empty();
$("#second-choice").append(html);
}
});
JsFiddle
I'm also including an extra part in case you would like this to work the other way round.
$("#first-choice").change(function() {
var selected = $(this).val()
if(selected== "English"){
$("#second-choice option[value='Spanish']").attr("selected","selected");
}
else if(selected == "Spanish"){
$("#second-choice option[value='English']").attr("selected","selected");
}
});
$("#second-choice").change(function() {
var selected = $(this).val()
if(selected== "English"){
$("#first-choice option[value='Spanish']").attr("selected","selected");
}
else if(selected == "Spanish"){
$("#first-choice option[value='English']").attr("selected","selected");
}
});
Fiddle: https://jsfiddle.net/uyf7uprd/1/
I have changed your jsFiddle. Here is the code:
$("#first-choice").change(function() {
var userSelected = $(this).val();
var otherOption = $('#second-choice option[value!="' + userSelected + '"]').get(0);
$('#second-choice').get(0).selectedIndex = otherOption.index;
});
And here is link to new fiddle:
https://jsfiddle.net/jkw8fxzf/11/
But if you want other select to contains only 'other' option
you must keep data for other option somewere. Here is other jsfiddle.
https://jsfiddle.net/jkw8fxzf/18/
and other solution:
$("#first-choice").change(function _optionHandler() {
var userSelected = $(this).val();
var second = $('#second-choice');
if(typeof _optionHandler.oldOption != 'undefined') {
$("<option/>", {
text: _optionHandler.oldOption.text,
value: _optionHandler.oldOption.value
}).appendTo(second);
delete _optionHandler.oldOption;
}
var otherOption = $('#second-choice > option[value!="' + userSelected + '"]').get(0);
second.get(0).selectedIndex = otherOption.index;
var optionToRemove = $('#second-choice > option[value="' + userSelected + '"]');
_optionHandler.oldOption = {
text: optionToRemove.text(),
value: optionToRemove.val()
}
optionToRemove.remove();
});
I hope this helps.

Print contents of a list box as comma-separated values using JQuery

I have a select box defined as shown below. I want to print out the name and email address of each item in the select box as comma seperated values, like
Tom Wayne,tom#xyz.com
Joe Parker,joe#xyz.com
Peter Simons,peter#xyz.com
Any way to accomplish that using JQuery?
<select multiple="multiple" name="search_results">
<option value="tom#xyz.com">Tom Wane</option>
<option value="joe#xyz.com">Joe Parker</option>
<option value="peter#xyz.com">Peter Simons</option>
</select>
Thank You
I think is a good example to use Traversing/map:
$('select option').map(function () {
return $(this).text() + ',' + $(this).val();
}).get().join('\n');
Try this:
$("select").each(function() {
var options = [];
$(this).children("option").each(function() {
var $this = $(this);
options.push($this.text()+ "," + $this.val());
});
alert(options.join("\n"));
});
This will alert you the options for each select individually.
Something like this:
var s = "";
$("select option").each(function()
{
var $option = $(this);
s += $option.text() + ", " + $option.val() + "\n";
});
alert(s);

Categories