Jquery dropdown, want one value always top when page loads - javascript

When the page loads i want to sort the dropdown using the jquery, to show the BI option first in the dropdown. I am generating the dropdown from the database.
<select id="conversionPixels" name="conversionPixels" >
<option value="10">PA3G ABTestConversion1DayWindow</option>
<option value="11">activ Conversion</option>
<option value="12">Proactiv Plus 24 Hour View</option>
<option value="13">Proactiv Plus Conversion</option>
<option value="0">BI</option>
</select>
I have used below jquery, it is not working
$("#conversionPixel").each(function() {
// Keep track of the selected option.
var selectedValue = $(this).val();
// Sort all the options by text. I could easily sort these by val.
$(this).html($("option", $(this)).sort(function(a, b) {
if( a.text=='BI'){
return -1;
}
if( b.text=='BI'){
return 1;
}
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
// Select one option.
$(this).val(selectedValue);
});

So why not to do something like
When you get data from database make sure BI is first Use code like
select id,name
from friends
order by id=5 desc, id asc
And then just use foreach to create options for your select - BI will be first

Use this code snippet:
$("#conversionPixels > option").each(function() {
if(this.text == "BI"){
$(this).remove();
$("#conversionPixels").prepend($(this));
}
});

This works if the select option text value you want to change is always BI.
//copy values BI
var html = $('select option').filter(function () { return $(this).html() == "BI"; }).html(),
value = $('select option').filter(function () { return $(this).html() == "BI"; }).val();
//remove option BI
$('select option').filter(function () { return $(this).html() == "BI"; }).remove();
//add to start copied value BI
$('select').prepend("<option selected value ='"+value+"'>"+html+"</option>");

If I understood your question correctly, all you want is the <option value="0">BI</option> element to be first on the select. Try runing the code snippet below.
$("#conversionPixels").children().each(function(index, elem) {
var $elem = $(elem);
if ($elem.val() === "0") {
$elem.remove();
$("#conversionPixels").prepend($elem);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="conversionPixels" name="conversionPixels">
<option value="10">PA3G ABTestConversion1DayWindow</option>
<option value="11">activ Conversion</option>
<option value="12">Proactiv Plus 24 Hour View</option>
<option value="13">Proactiv Plus Conversion</option>
<option value="0">BI</option>
</select>

Related

how to get dropdown (HTML Select) text against it value from local storage?

I am working on an existing project where I have to get the dropdown (HTML select) Text against its selected value in jquery.
I am storing the dropdown value in localstorage to get the value again if the user refreshed the page so I can maintain the same text against its value.
For demonstration, I created a similar code. My desired output will be:
If the value is 0 then in the console it should print Select Value...
<select class="form-control " id="test" name="test" placeholder="Select Value...">
<option value="0">Select Value...</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
$(document).ready(function() {
debugger;
var value = $("#test").val(),
currentTestValue = localStorage.getItem("test_selected_value");
if (currentTestValue === undefined || currentTestValue === '' || currentTestValue === null) {
localStorage.setItem("test_selected_value", 0);
} else {
localStorage.setItem("test_selected_value", value);
}
var textValue = $("#test").options[value.selectedIndex].text;
console.log(textValue);
});
find() is used to retrieve child elements from the DOM. Using an integer (in a string) is not a valid selector.
To find an option within a select by its value you can use an attribute selector or filter():
var textValue = $("#test option").filter((i, opt) => opt.value == value).text();
Also note that the logic to set the localStorage item can be simplified. Here's an updated version of your code:
$(document).ready(function() {
var value = $("#test").val();
var currentTestValue = localStorage.getItem("test_selected_value");
localStorage.setItem("test_selected_value", currentTestValue || value);
var textValue = $("#test option").filter((i, opt) => opt.value == value).text();
console.log(textValue);
});
Example in jsFiddle - as the SO snippet editor restricts access to localStorage.
Since you already have set the value of the select - The selected text value will be:
$("#test option:selected").text();

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

Jquery : Select option of dropdown based on textbox text

I have tried to select option based on the textbox text.
Below is my html
<select id="select1">
<option value="">-- Please Select --</option>
<option value="277">12 +$2.99</option>
<option value="278">25 +$2.75</option>
<option value="279">50 +$2.50</option>
<option value="280">100 +$2.00</option>
<option value="281">250 +$1.90</option>
<option value="282">500 +$1.70</option>
<option value="283">1000 +$1.60</option>
<option value="284">2500 +$1.50</option>
<option value="285">5000 +$1.20</option>
<option value="286">10000 +$1.00</option>
<option value="287">25000 +$0.80</option>
</select>
<input type="text" id="pqr" />
And my js like bellow
$(function(){
$('#pqr').change(function(){
$txt = $( "#select1 option:contains('"+$(this).val()+"')" ).text();
$arr = $txt.split(" +");
$( "#select1").val($txt);
alert($arr[0])
$( "#select1" ).filter(function() {
alert($( this ).text > $arr[0]);
})
});
});
so if user enter text 12 or greater than 12 and bellow 25 than i want to select option second 12 +$2.99 and if user enter 1500 than option 1000 +$1.60 get selected. Basically i have try to compare option text before (+) sign and try to select based on that.
Please give me hint or any good help so solve this problem
At every change, iterate over all option elements and compare based on parseInt():
jQuery(function($) {
$('#pqr').on('change', function() {
var value = parseInt(this.value, 10),
dd = document.getElementById('select1'),
index = 0;
$.each(dd.options, function(i) {
if (parseInt(this.text, 10) <= value) {
index = i;
}
});
dd.selectedIndex = index; // set selected option
});
});
Demo
Loop through each option to compare the value. You can use something like this,
$(function () {
$('#pqr').change(function () {
var txtvalue = parseFloat($(this).val());
$("#select1 option").each(function () {
var splitText = $(this).next().text().split("+");
if (splitText.length > 1) {
if (txtvalue < parseFloat(splitText[0].trim())) {
$(this).prop("selected", true);
return false;
}
}
});
});
});
Fiddle
Try this :
$(function(){
$('#pqr').change(function(){
var inputVal = parseInt($(this).val());
$('#select1 option').each(function(){
var firstVal = $(this).text().split('+')[0];
var nextVal = inputVal;
if(!$(this).is(':last'))
$(this).next().text().split('+')[0];
if(parseInt(firstVal) <= inputVal && parseInt(nextVal) >=inputVal)
{
$(this).prop('selected',true);
}
});
});
});
Demo
The $arr[0] in the change callback function will be containing a text value which is not yet parsed to integer so the statement alert($( this ).text > $arr[0]); would not give desired output.
For checking the value lying between a range of select lists option you can use data attributes as followed:
<select id="select1">
<option value="" data-min="-" data-max="-"> Please Select </option>
<option value="277" data-min="12" data-max="25">12 +$2.99</option>
<option value="278" data-min="25" data-max="50">25 +$2.75</option>
This way you will not have to Parse the text of option into integer.
These data values can be retrieved for using jquery data function http://api.jquery.com/data/.
Also all the times you will not be getting the $('#pqr').val() as the text in the option's text so you will have to collect the value of text box and compare it with the range of each option(value >= data-max || value <= data-min).
$(function(){
$('#pqr').on("input", function(){
var text = this.value;
var options = $("#select1 > option");
var elementToSelect = options.eq(0);
if (text.match(/[0-9]+/)) {
elementToSelect = options.filter(function(){
return Number(this.innerText.split("+")[0]) <= text;
})
.eq(-1);
}
elementToSelect.attr("selected",true);
});
});

how to show 2 select options value in another element?

I am have been searched too much on net but nothing found.
I have 2 select options tag.
I want to show option value in the input tag by multiplying option tag value whatever it is.
and selecting 2nd option tag I want to assign 2nd option tag value to 1st option tag value.
and I also want to multiply that values as the 1st options value have before.
how to do this?
here is my code.
My 1st options tag.
<select name="" id="test">
<option selected="" value="0" disabled='disabled'>Select Duration</option>
<option value="1">1/month</option>
<option value="2">2/month</option>
<option value="3">3/month</option>
<option value="6">6/month</option>
<option value="12">12/month</option>
</select>
<input type="text" data-val="9" id="price_value" style="border:1px solid #0a0; padding:1px 10px; color: #f90;" value="0" size="5"/><br>
Here is 2nd option tag.
<select id="plan">
<option value='Basic'>Basic</option>
<option value='Standard'>Standard</option>
<option value='Professional'>Professional</option>
<option value='Enterprice'>Enterprise</option>
</select>
here is JS.
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).find('option:selected').val();
input.val( input.data('val') * parseInt(value) );
});
$('#plan').on('change',function(e) {
var plan = $(this).find('option:selected').val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.removeAttr('data-val');
price_value.attr('data-val','9');
}
else if (plan == "Standard"){
price_value.removeAttr('data-val');
price_value.attr('data-val','19');
}
else if (plan == "Professional"){
price_value.removeAttr('data-val');
price_value.attr('data-val','29');
}
else if (plan == "Enterprice") {
price_value.removeAttr('data-val');
price_value.attr('data-val','59');
}
});
Here is Demo
Changes
Use $(this).val() instead of $(this).find('option:selected').val() to fetch select value. or even better use this.value
use .data() to set value like price_value.data('val', 9); instead of price_value.attr('data-val','9');
No need to use price_value.removeAttr('data-val');
Code
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).val(); //Or this.value
input.val( input.data('val') * parseInt(value, 10) );
});
$('#plan').on('change',function(e) {
var plan = $(this).val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.data('val',9);
}
else if (plan == "Standard"){
price_value.data('val',19);
}
else if (plan == "Professional"){
price_value.data('val',29);2
}
else if (plan == "Enterprice") {
price_value.data('val',59);
}
$('#test').trigger('change'); //Trigger $('#test') change event
});
DEMO
This solution would work if you are okay with changing your HTML a bit:
<select id="plan">
<option value='9'>Basic</option>
<option value='19'>Standard</option>
<option value='29'>Professional</option>
<option value='59'>Enterprise</option>
</select>
Then simply use:
$('#test, #plan').on('change',function() {
var valueOne = $('#test').val();
var valueTwo = $('#plan').val();
$('#price_value').val(parseInt(valueOne) * parseInt(valueTwo));
});
That's all!

drop options in dropdown box

I am using 24 dropdowns. I want to select a driver for a position. But when i select a driver for the first position it should be removed from the other dropdowns so i can't use a driver two times. The dropdown is:
<select name="rijderQual1">
<option value="1">S. Vettel</option>
<option value="2">M. Webber</option>
<option value="3">J. Button</option>
<option value="4">L. Hamilton</option>
<option value="5">F. Alonso</option>
<option value="6">F. Massa</option>
<option value="7">M. Schumacher</option>
<option value="8">N. Rosberg</option>
<option value="9">K. Raikkonen</option>
<option value="10">R. Grosjean</option>
<option value="11">R. 11</option>
<option value="12">R. 12</option>
<option value="14">K. Kobayashi</option>
<option value="15">S. Perez</option>
<option value="16">R. 16</option>
<option value="17">R. 17</option>
<option value="18">P. Maldonado</option>
<option value="19">R. 19</option>
<option value="20">H. Kovalainen</option>
<option value="21">J. Trulli</option>
<option value="22">P. de</option>
<option value="23">R. 23</option>
<option value="24">T. Glock</option>
<option value="25">C. Pic</option>
</select>
The names are rijderQual1 to rijderQual24. So when i select S Vettel for example in rijderQual1 it should be removed from the 23 other dropdowns.
Is there a way to do this? I think it should be done with JS or jQuery?
You can iterate thru all options everytime some selected value is changed and hide the options that are selected somewhere else:
$('select').change(function() {
var selectedValues = $('select').map(function() { return this.value; }).get();
$('option').show();
$.each($('option'), function(i, item) {
if($(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 )
{
$(this).hide();
}
});
});​
DEMO
Try populating your dropdown box through an array, and on each item selected delete that item from that array. both JS and JQuery would work.
I still believe another approach would be wiser, for example colour-coding all dropdowns that have the same value selected. Or unselect the option from the first dropdown if you select it in another. That way you wouldn't deprive users from doing what they want, but warn them if they try to do something that's not allowed. Better for UX. Something a little more like this.
// Store text labels for options
$("option")
.each(function() {
$(this).data("label", $(this).text());
});
$('select').change(function() {
// Get selected values
var selectedValues = $('select').map(function() { return this.value; }).get();
// Reset conflicting dropdowns
currentVal = $(this).val();
$(this).siblings("select")
.each(function() {
if ($(this).val() == currentVal) $(this).val(0);
});
// Mark selected options as unavailable
$("option")
.each(function() {
if( $(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 && !$(this).is(":selected"))
$(this).text("(" + $(this).data("label") + ")");
else
$(this).text($(this).data("label"));
});
});​
DEMO: http://jsfiddle.net/NAWNP/
Still, according to your requirements this would iterate through the options, disabling those that are in use by other dropdowns. This way you can still see your options, even though you can't make them.
$('select').change(function() {
var selectedValues = []
$("option:selected").each(function() { selectedValues.push($(this).val()) });
$("option")
.removeAttr("disabled")
.each(function() {
if( $(this).val() != 0 && $.inArray($(this).val(), selectedValues) > -1 && !$(this).is(":selected"))
{
$(this).attr("disabled", "true");
}
});
});​
DEMO: http://jsfiddle.net/ntxmh/2/
Working demo http://jsfiddle.net/zyGH7/
another http://jsfiddle.net/fLTxj/
Much concise version. This is the source: jQuery remove options except current (Very well written)
Hope it fits the cause! B-)
Code
$('document').ready(function() {
$(".hulk").change(function() {
var val = this.options[this.selectedIndex].value;
$('select').not(this).children('option').filter(function() {
return this.value === val;
}).remove();
});
});​

Categories