Dynamically append multiple options selected into one select jquery - javascript

I'm trying to add the options selected from one select element into another. I'm guessing it'll be something like this.
var selected = $("#selectWithOptions").append("<option'>" +
options[selectedIndex].value + "</option>");
This does not work.

The logic is pretty straight-forward and you can follow the inline comments in the JS function:
// Fire this function when a dropdown item is selected
$('#dd1').change(function() {
// Grab the text of the selected item
var selectedOption = $('#dd1 :selected').text();
// If it is not already in the second dropdown list, then append it
if( $('#dd2 option').filter(function () { return $(this).text() == selectedOption; }).length <= 0 ) {
$('#dd2').append('<option>'+selectedOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Dropdown 1:
<select id="dd1">
<option selected disabled>Select option</option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>xiyar</option>
</select>
</div>
<div>Dropdown 2:
<select id="dd2">
</select>
</div>

In Javascript(and jQuery), everything is an object. Get the selected option elements using the jquery :selected selector and then append them to the second select element.
I'm using clone() but if you don't want to copy, rather you want to move the elements from one select to the other, then get rid of clone() and that same object will be moved to the other select element.
$('button').on('click',function(e){
var opt = $('#first option:selected').clone();
$('#second').append(opt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="hello">Hello</option>
<option value="world">World</option>
</select>
<select id="second">
</select>
<button>
Copy
</button>

Related

Why select option change event can't have this and event.target to get selected value?

In select option change event,why can't we get this or event.target to get selected value instead of writing clumsy code like $( "select option:selected" ) to get selected value ?
Pure JavaScript
If you want a pure JavaScript approach, then use the event.target. To quote the official MDN documentation...
The target property of the Event interface is a reference to the object onto which the event was dispatched. (Source: MDN Web Docs: Event.target.)
Since that gives us the element selected, all we then need is the value attribute, and getting the text display would be nothing more than event.target[event.target.selectedIndex].text...
function getSelectedValue(event) {
console.log("Value: " + event.target.value + "; Display: " + event.target[event.target.selectedIndex].text + ".");
}
<select onchange="getSelectedValue(event)">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
Using the above approach, it would be trivial to update it to add in other attributes of the selection option value, all in pure JavaScript.
jQuery
If you want a jQuery approach, then try using the :selected query term...
$("#selector").on('change', function(){
console.log("Value: " + $(this).val() + "; Display: " + $(this).find('option:selected').text() + ".");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selector">
<option selected disabled>--Pick an Option--</option>
<option value="blue1">Blueberry</option>
<option value="rasp2">Raspberry</option>
<option value="straw3">Strawberry</option>
</select>
$("select").on('change', function(){
console.log($(this).val());
console.log($(this).find('option:selected').attr('data-attribute'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option data-attribute="a">1</option>
<option data-attribute="b">2</option>
<option data-attribute="c">3</option>
<option data-attribute="d">4</option>
</select>
You can't get the selected value, but of course you can get the element and the event.target.
<select onchange="mySelectOnchange(this, event)"></select>
function mySelectOnchange(elm, e) {
// **
}
It exists... take a look at this code for example
var selectElem = document.getElementById('select');
selectElem.addEventListener('change', onSelect_change);
function onSelect_change(domEvent){
// get the selected value :
var selectedValue = domEvent.target[domEvent.target.selectedIndex].value;
// you can also do it using domEvent.target.value but the other solution allows you to get every option's property you want
console.log("Selected: " + selectedValue);
}
<select id="select" name="select">
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Hope it helps ;)
PS: have a look on http://www.w3schools.com/jsref/prop_select_selectedindex.asp if you want more examples
The only property that's automatically transferred from the selected option to the <select> element itself is the value, because that's the main purpose of selecting an option from a drop-down menu. Other attributes like data-* are not automatically copied, because it's possible for the <select> to have its own attributes, e.g.
<select id="x" data-name="select">
<option value="1" data-name="option1">1</option>
<option value="2" data-name="option2">2</option>
</select>
It wouldn't make sense for $("#x").data("name") to return the name of the selected option instead of the name of the <select>.
<select onchange="getSelectedValue(this)"></select>
...
function getSelectedValue(select) {
console.log(select.value)
}

Database value cannot get it to the Dropdownlist jQuery

In my database there's a column, name is Sequence & it consist of numbers(int). In my application's edit function I need to show that selected number in my jQuery dropdown list.
In my AJAX call I sent ProductId and get the specific row.
Html Control
<select class="form-control" id="drpsequence"></select>
My jQuery dropdown
$("#drpsequence option:selected").append($("<option></option>").val(msg._prodlng[0].Sequence).text(msg._prodlng[0].Sequence));
In the above code msg._prodlng[0].Sequence comes as selected number
I'm not sure what you are trying to do but it looks like you are adding an <option> tag into another <option> tag which is most likely not what you want.
If the returned value already exists as a selected option:
$("#drpsequence").val(msg._prodlng[0].Sequence).prop('selected', true);
Or, if you need to add an option:
var opt = $("<option>")
.val(msg._prodlng[0].Sequence)
.text(msg._prodlng[0].Sequence);
$("#drpsequence").append(opt);
Snippet example:
// foo --> select
$('#foo').val('baz').prop('selected', true);
$('#bim').click(function(){
$('#foo').append('<option id="boop" value="boop">boop</option>'); //<-- or loaded value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foo">
<option>-- select --</option>
<option id="bar" value="bar">bar</option>
<option id="baz" value="baz">baz</option>
</select>
<button id="bim">Add an option</button>
You need to do one of following.
Either find that option and make that selected = true like this.
$("#sel option").each(function(i) {
if ($(this).val() == "Orange") $(this).attr("selected", "true");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</select>
Or if that option is not found then add and make that selected = true.
Like the one, which you had in your question.

Remove the first select option

I'd like to remove the first option of an select tag when I click on the select tag. Is this possible?
I don't want to see the first option after that click.
Thanks for any help.
You can remove the first option on click with jQuery.
$(document).on('click', 'select', function() {
$(this).find('option').get(0).remove();
});
This simply removes the first option of a select tag on click. You need to add an if statement to check if it was already removed.
There's also a simple no-javascript solution:
<select>
<option style="display: none">--Choose--</option>
<option>Cheese Cake</option>
<option>Hot Pockets</option>
<option>Sausage</option>
<option>Cookies</option>
<option>Bacon</option>
</select>
(Copied from the comments from #chipChocolate.py)
If you use bootstrap add placeholder attribute in your select.
If your not
<select required>
<option value="" disabled selected>Select your option</option>
<option value="1">1</option>
</select>
// to remove first...
document.getElementById("element_id_str").options[0].remove();
//to remove the lot...
document.getElementById("element_id_str").options.length = 0;
<select required>
<option value="" disabled selected hidden>Select your option</option>
<option value="1">1</option>
</select>
Probably you just want this:
<select required>
<option value="" hidden>Select your option</option>
<option value="1">1</option>
</select>
A very naive way of doing this:
$("#selector").change(function(evt) { //listen to changes of selection
var theElement = $(this);
if (!theElement.data("selected")) { //check if flag is not set
theElement.children("option")[0].remove(); //remove 1st child
theElement.data("selected", true); //set flag, so it doesn't continue removing items for every change
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option>--Choose--</option>
<option>Apple</option>
<option>Banana</option>
<option>Papaya</option>
</select>
If you want to remove the first option use this
$(document).ready(function()
{
$("select").children().first().remove();
});
If you want to remove the first option after clicking on the select box use this
$(document).ready(function()
{
var removed=false;
$(document).on("click","select",function()
{
if(!removed)
{
$(this).children().first().remove();
removed=true;
}
});
});
Javascript:
document.getElementById("SelectId")[0].remove();
Get the first option in the select and remove it.
I had the same problem, but the solutions above just work with one form, not with many. I added some extra code in order to validate it for many in your form:
$(document).ready(function()
{
$(document).on("change","select",function()
{
var x = $(this).children().first().attr("name");
var n = x.localeCompare("todelete");
if (n == 0)
$(this).children().first().remove();
});
});
Where "todelete" is the name for all first elements [0] defined inside the
Please select value //all first elem must have the same name
"> //the others another name (can be the same BUT not "todelete")
You need the id or class to remove the item. While testing and debugging I found 'option:first' fails to remove the item. But 'option:first-of-type' always does the work. You can get more info about 'first-of-type' here :first-of-type
$("#ID_or_.CLASS option:first-of-type").remove();

Jquery autoselect select options of the same class

I have three select options drop down menus with class 'film', but the values are linked so that I have to select all to get result. In my case the HTML code looks like this:
<select name="sc30" id="sc30" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>White</option>
<option>Black</option>
</select>
<select name="ij10" id="ij10" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Red</option>
<option>Green</option>
<option>Gold</option>
</select>
<select name="sc100" id="sc100" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Gold glossy</option>
<option>Silver glossy</option>
</select>
If I select White option from id="sc30" the other two select options must take a value "---". Or if I select option Gold glossy from id="sc100" the other options from this class 'film' must take this value ---
I think that I have to use jQuery each() method. But how to check if any select option is selected and make other select options from this class with "---" value without already selected option. The code below don't work properly.
function autoSelect() {
$('.dummy').each(function(index, value){
if($(this).val() != '---') {
$(".dummy").val($(".dummy option:eq(1)").val());
}
});
}
$(function() {
$('select.film').on('change', function() {
var cb = $(this);
if (2 === cb.prop('selectedIndex')) {
$('select.film').not(cb).prop('selectedIndex', 1);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="sc30" id="sc30" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>White</option>
<option>Black</option>
</select>
<select name="ij10" id="ij10" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Red</option>
<option>Green</option>
<option>Gold</option>
</select>
<select name="sc100" id="sc100" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Gold glossy</option>
<option>Silver glossy</option>
</select>
Try this : remove onchange="autoSelect()" from all select boxes and bind change event as shown below and select second option for each select box except the current one for which change event fired -
$(function(){
$('.film').change(function(){
//iterate all other select box except current using `not(this)`
$('.film').not(this).each(function(){
// get selected option for the current select box
var $selected = $(this).find('option:selected');
// if index of selected option is greater than 1,
// it means option is selected.
if($selected.index()>1)
$(this).val($(this).find('option:eq(1)').val());
});
});
});
DEMO
I just remove these two rows code:
var $selected = $(this).find('option:selected');
if($selected.index()>1)
and already is ok!
$(function(){
$('.film').change(function(){
//iterate all other select box except current using `not(this)`
$('.film').not(this).each(function(){
$(this).val($(this).find('option:eq(1)').val());
});
});
});

Simple way to reset the dropdown list in jquery

i want to clear only 3 elements in dropdown list. how to do by iteration i.e indexbased would be fine.
Here is how my dropdown looks.
<div id = "Dropdown">
<select id="dropdownlist" class="trace dropdown" name="dropdownlistitems">
<option value="ID1" selected="selected">--Please Select--</option>
<option value="ID2">ID2text</option>
<option value="ID3">ID3text</option>
</select>
</div>
Do you mean something like this?
$('#dropdownlist option').each(function (index, option) {
if(index!=0)
{
$(this).remove();
}
});
This will remove each option tag that the loop iterates through (except, of course, the first one)
How about this?
$('#dropdownlist option:lt(3)').remove();
This selects the first 3 options and removes them.

Categories

Resources