Add data into a Select - javascript

I have this select; to select countries and add to a new select multiple with a limit of 5 countries, but I just want to add 1 country by select or more countries if i do a multiple select.
My mistake is in my function addC(), when I want to add more than 1 country in my select, it add the several countries in 1 option tag like this:
<option>South KoreaUSAJapan</option>
What I can modify to display the following way if i do a multiple select?:
<option>South Korea</option>
<option>USA</option>
<option>Japan</option>
My code:http://jsbin.com/osesem/4/edit
function addC() {
if ($("#agregarProvincia option").length < 5) {
var newC = ($("#countries option:selected").text());
$("#addCountry").append("<option>" + newC + "</option>");
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<label for="provincia2"><b>¿Country?</b></label><br>
<span>
<select multiple="multiple" size="5" id="countries">
<option value="1">South Korea</option>
<option value="2">USA</option>
<option value="2">Japan</option>
<option value="3">Italy</option>
<option value="4">Spain</option>
<option value="5">Mexico</option>
<option value="6">England</option>
<option value="7">Phillipins</option>
<option value="8">Portugal</option>
<option value="9">France</option>
<option value="10">Germany</option>
<option value="11">Hong Kong</option>
<option value="12">New Zeland</option>
<option value="13">Ireland</option>
<option value="14">Panama</option>
<option value="15">Norwey</option>
<option value="16">Sweeden</option>
<option value="17">India</option>
<option value="18">Morroco</option>
<option value="19">Russia</option>
<option value="20">China</option>
</select>
</span>
<div class="addremover">
<input class="add" type="button" onclick="addC()" value="Addd »" />
<br/>
</div>
<span>
<select id="addCountry" multiple="multiple" size="5">
</select>
</span>

use each function to loop through the text and append it..
try this
function addC() {
if ($("#agregarProvincia option").length < 5) {
var newC = ($("#countries option:selected"));
newC.each(function(){
$("#addCountry").append("<option>" + $(this).text() + "</option>");
})
}
}
JSbin here

Or just clone the selected <option>'s
function addC() {
if ($('#countries option:selected').size() < 5)
{
$('#addCountry').append($('#countries option:selected').clone());
}
else
{
alert('you can only select 5');
}
}

Related

Filter multiple data attributes in dropdown list

I have a dropdown list with multiple data attributes
<select class="op" id="b0">
<option
value="1"
data-type="vehicle"
data-vtype="car"
data-model="bmw"
data-engine="1"
data-owner="1"
data-year="2009"
>BMW2009 </option>
<option
value="2"
data-type="vehicle"
data-vtype="bus"
data-model="jeep"
data-engine="2"
data-owner="4"
data-year="2006"
>BMW2009 </option>
<option
value="3"
data-type="boat"
data-vtype="boat1"
data-model="boat2"
data-engine="0"
data-owner="3"
data-year="2010"
>BMW2009 </option>
There will be around 10k of the data, so I have dropdowns to filter the data
<select id="typeFilter">
<option value="vehicle">Vehicle </option>
<option value="Aeroplane">Aeroplane </option>
<option value="Boat">Boat </option>
</select>
<select id="modelFilter">
<option value="BMW">BMW </option>
<option value="Jeep">Jeep </option>
<option value="Boat2">Boat2 </option>
</select>
I want to filter by typeFilter and/or modelFilter. I used the following code
$('#modelFilter').on('change', function() {
let mtype = $(this).find("option:selected").data("model");
$("#b0").show();
$("#b0 option[data-model]:not([data-model*='" + mtype + "'])").hide();
});
$('#typeFilter').on('change', function() {
let ttype = $(this).find("option:selected").data("type");
$("#b0").show();
$("#b0 option[data-type]:not([data-type*='" + ttype + "'])").hide();
});
The method partially works, so when I select BMW, I can see only the option 3 list but for the multiple conditions with the same name it doesn't. Is there a simpler way to filter the multiple data attributes?
first you define a function,
function filter(){
//show all data
$("#b0 option").show();
//check filter by model
let mtype = $('#modelFilter').find("option:selected").data("model");
if(mtype){
$("#b0 option[data-model]:not([data-model*='" + mtype + "'])").hide();
}
//check filter by typeFilter
let ttype = $('#typeFilter').find("option:selected").data("type");
if(ttype){
$("#b0 option[data-type]:not([data-type*='" + ttype + "'])").hide();
}
}
then in each filter call this function,
$('#modelFilter,#typeFilter').on('change', function () {
filter()
})
First, the value of your filter select element is not matched with your dropdown because it is case-sensitive.
Second, you can use one single function to do your filtering.
Note: I add a option <option selected disabled>---select a option----</option> to force the user to trigger a change event.
$("#modelFilter").on("change", filter);
$("#typeFilter").on("change", filter);
function filter() {
$("#b0 option").show();
const typeFilterValue = $("#typeFilter").val();
const modelFilterValue = $("#modelFilter").val();
if(typeFilterValue!==null){
$(`#b0 option:not([data-type='${typeFilterValue}'])`).hide();
}
if(modelFilterValue!==null){
$(`#b0 option:not([data-model='${modelFilterValue}'])`).hide();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="op" id="b0">
<option selected disabled>---select a option----</option>
<option
value="1"
data-type="vehicle"
data-vtype="car"
data-model="bmw"
data-engine="1"
data-owner="1"
data-year="2009"
>
BMW2009
</option>
<option
value="2"
data-type="vehicle"
data-vtype="bus"
data-model="jeep"
data-engine="2"
data-owner="4"
data-year="2006"
>
Jeep
</option>
<option
value="3"
data-type="boat"
data-vtype="boat1"
data-model="boat2"
data-engine="0"
data-owner="3"
data-year="2010"
>
Boat
</option>
</select>
<select id="typeFilter">
<option selected disabled>---select a option----</option>
<option value="vehicle">Vehicle</option>
<option value="Aeroplane">Aeroplane</option>
<option value="Boat">Boat</option>
</select>
<select id="modelFilter">
<option selected disabled>---select a option----</option>
<option value="bmw">BMW</option>
<option value="jeep">Jeep</option>
<option value="boat2">Boat2</option>
</select>

Car Make/Model dynamic dropdown

I'm setting up a new form on my site, and I'm using some code I found here (Vehicle drop down selector). However, I'm using this code within a form, and once the form is submitted, the values for make/model aren't changed to their respective names, instead showing their form values. Being a complete JS noob, how would I go about changing the values submitted from values to make/model names?
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
$model.html($options.filter('[value="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
var $model = $('#model'),
$year = $('#year'),
$yearOptions = $year.find('option');
$model.on('change', function() {
$year.html($yearOptions.filter('[value="' + this.value + '"]'));
$year.trigger('change');
}).trigger('change');
var $year = $('#year'),
$identifier = $('#identifier'),
$identifierOptions = $identifier.find('option');
$year.on('change', function() {
var filteredIdetifiers = $identifierOptions.filter('[value="' + this.value + '"]');
debugger
if (!($("#make").val() == 3 && $("#model option:selected").text() == 'Falcon')) {
filteredIdetifiers = filteredIdetifiers.filter(function(i, e) {
return e.value !== '3'
});
}
$identifier.html(filteredIdetifiers);
$identifier.trigger('change');
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Vehicle Brand Selector List -->
<select name="make" id="make">
<option value="0">Make</option>
<option value="1">BMW</option>
<option value="2">Daewoo</option>
<option value="3">Ford</option>
<option value="4">Holden</option>
<option value="5">Honda</option>
<option value="6">Hyundai</option>
<option value="7">Isuzu</option>
<option value="8">Kia</option>
<option value="9">Lexus</option>
<option value="10">Mazda</option>
<option value="11">Mitsubishi</option>
<option value="12">Nissan</option>
<option value="13">Peugeot</option>
<option value="14">Subaru</option>
<option value="15">Suzuki</option>
<option value="16">Toyota</option>
<option value="17">Volkswagen</option>
</select>
<!-- Vehicle Model List -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="1">318i</option>
<option class="lanos" value="2">Lanos</option>
<option class="courier" value="3">Courier</option>
<option class="falcon" value="3">Falcon</option>
<option class="festiva" value="3">Festiva</option>
<option class="fiesta" value="3">Fiesta</option>
<option class="focus" value="3">Focus</option>
<option class="laser" value="3">Laser</option>
<option class="ranger" value="3">Ranger</option>
<option class="territory" value="3">Territory</option>
<option class="astra" value="4">Astra</option>
<option class="barina" value="4">Barina</option>
<option class="captiva" value="4">Captiva</option>
<option class="colorado" value="4">Colorado</option>
<option class="commodore" value="4">Commodore</option>
<option class="cruze" value="4">Cruze</option>
<option class="rodeo" value="4">Rodeo</option>
<option class="viva" value="4">Viva</option>
</select>
<!-- Vehicle Year List -->
<select name="year" id="year">
<option value="0">Year</option>
<option value="1">1998</option>
<option value="1">1999</option>
<option value="1">2000</option>
<option value="1">2001</option>
<option value="1">2002</option>
<option value="1">2003</option>
<option value="1">2004</option>
<option value="1">2005</option>
<option value="2">1997</option>
<option value="2">1998</option>
<option value="2">1999</option>
<option value="2">2000</option>
<option value="2">2001</option>
<option value="2">2002</option>
<option value="2">2003</option>
<option value="3">1991-1999</option>
<option value="4">1997-2007</option>
<option value="5">1997-2007</option>
<option value="3">2002</option>
<option value="3">2003</option>
<option value="3">2004</option>
<option value="3">2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
</select>
<!-- Vehicle Identity List -->
<select name="identifier" id="identifier">
<option value="0">Type</option>
<option class="E46" value="1">E46</option>
<option class="1997-2003" value="2">N/A</option>
<option class="1997-2007" value="4">N/A</option>
<option class="1997-2007" value="5">N/A</option>
<option class="5041618" value="3">BA</option>
<option class="1997-2005" value="3">AU</option>
<option class="1997-2005" value="3">AU2</option>
<option class="1997-2005" value="4">N/A</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
</select>
In every <option> tag there is an attribute called value. This value attribute is what is returned at as the value of the dropdown when that option is selected. Seems like in the code you found they are all simply set to numbers. You can set them to be whatever you want though:
<option value="Ford">Ford</option>
<option class="focus" value="Focus">Focus</option>
FIXING DYNAMIC OPTIONS
I see that modifying the values directly affect how the dynamic options are displayed. For example the value attribute of the car model dropdown is used to filter the car make dropdown by only displaying options with the same value. Instead of using the model dropdown's value attributes to compare with make, we can add a new data- attribute called data-make and filter the model dropdown based on that instead. This allows you to freely modify the value attribute in model. The example code below shows this. You would need to modify your JS so model affects year, and year affects identifier in the same way.
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
// We now filter model using the data-make attribute, not value
$model.html($options.filter('[data-make="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
$('#carForm').submit(function(e) {
e.preventDefault();
let formData = $(this).serializeArray();
let data = {};
for (let i = 0; i < formData.length; i++) {
data[formData[i].name] = formData[i].value;
}
alert('Make: ' + data.make + '\nModel: ' + data.model);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="carForm">
<select name="make" id="make">
<option value="0">Make</option>
<option value="BMW">BMW</option> <!-- These values are now make names -->
<option value="Daewoo">Daewoo</option>
<option value="Ford">Ford</option>
</select>
<!-- Vehicle Model List -->
<!-- Notice the new "data-make" attributes for each -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="318i" data-make="BMW">318i</option>
<option class="lanos" value="Lanos" data-make="Daewoo">Lanos</option>
<option class="courier" value="Courier" data-make="Ford">Courier</option>
<option class="falcon" value="Falcon" data-make="Ford">Falcon</option>
<option class="festiva" value="Festiva" data-make="Ford">Festiva</option>
<option class="fiesta" value="Fiesta" data-make="Ford">Fiesta</option>
<option class="focus" value="Focus" data-make="Ford">Focus</option>
</select>
<button type="submit">Submit</button>
</form>
You can get the selected option text like this.
$('#form').submit(function(e) {
e.preventDefault();
var make = $make.find(':selected').text();
}
But it would be good practice to set the value you expect to return as the option value and use a data attribute or class to handle the filtering logic.

Displaying multiple Select Values into an alert? [duplicate]

This question already has answers here:
How to get all selected values of a multiple select box?
(28 answers)
Closed 5 years ago.
I'm still a beginner hence this is difficult, but how do I display the options I selected into an alert box. So it would be "You selected (value), (value), (value)".
This is my select list
<form id='form1'>
<select id="options" multiple >
<option value="action">Action</option>
<option value="animation">Animation</option>
<option value="children">Children</option>
<option value="classics">Classics</option>
<option value="comedy">Comedy</option>
<option value="documentary">Documentary</option>
<option value="drama">Drama</option>
<option value="family">Family</option>
<option value="foreign">Foreign</option>
<option value="games">Games</option>
<option value="horror">Horror</option>
<option value="music">Music</option>
<option value="new">New</option>
<option value="scifi">Sci-Fi</option>
<option value="sports">Sports</option>
<option value="travel">Travel</option>
</select>
</form>
Should I add a button. But what I'm struggling with is the javascript.
The easiest way to access selected elements of a select tag is with the "selectedOptions" property.
I would do it this way:
var form = document.getElementById('form1');
form.addEventListener('submit', function () {
var select = form.querySelector('#options'),
options = select.selectedOptions,
values = [];
for (var i = options.length - 1; i >= 0; i--) {
values.push(options[i].value);
}
alert('You selected: ' + values.join(', '));
}, false);
Try something like this:
function selectedValues()
{
var x=document.getElementById("options");
var selectedValues= '';
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
selectedValues += x.options[i].value + ", ";
}
}
alert("You selected: "+ selectedValues.slice(0, -2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='form1'>
<select id="options" multiple onchange="selectedValues()">
<option value="action">Action</option>
<option value="animation">Animation</option>
<option value="children">Children</option>
<option value="classics">Classics</option>
<option value="comedy">Comedy</option>
<option value="documentary">Documentary</option>
<option value="drama">Drama</option>
<option value="family">Family</option>
<option value="foreign">Foreign</option>
<option value="games">Games</option>
<option value="horror">Horror</option>
<option value="music">Music</option>
<option value="new">New</option>
<option value="scifi">Sci-Fi</option>
<option value="sports">Sports</option>
<option value="travel">Travel</option>
</select>
</form>

Alert when selecting some particular value from drop down in JavaScript

Below are the dropdown data..
<select size="1" name="Test_Data">
<option selected value="Select One">Select One</option>
<option value="Data1">IN-Data1</option>
<option value="Data2">IN-Data2</option>
<option value="Data3">IN-Data3</option>
<option value="Data4">AUS-Data4</option>
<option value="Data5">AUS-Data5</option>
<option value="Data6">US-Data6</option>
<option value="Data7">US-Data7</option>
I want to get alert/pop up when I select the data which is start from IN in drop down list.
Try this:
https://jsfiddle.net/mminetto/bggwnkwj/
var select = $('select[name="Test_Data"]');
select.on('change', function(){
var options = select.children('option:selected');
if(options.length > 0 && options[0].innerText.startsWith("IN")){
alert(this.value);
alert(options[0].innerText);
}
});
<select size="1" name="Test_Data" id="dropdown">
<option selected value="Select One">Select One</option>
<option value="Data1">IN-Data1</option>
<option value="Data2">IN-Data2</option>
<option value="Data3">IN-Data3</option>
<option value="Data4">AUS-Data4</option>
<option value="Data5">AUS-Data5</option>
<option value="Data6">US-Data6</option>
<option value="Data7">US-Data7</option>
in javascript
<script>
$("#dropdown").change(function(){
if($(this).find("option:selected").text().startsWith("IN")){
alert("option with IN selected =>"+$(this).find("option:selected").text());
}
});
</script>
Try this code
HTML
<select size="1" onChange="showAlert()" id="dataCountry" name="Test_Data">
<option selected value="Select One">Select One</option>
<option value="Data1">IN-Data1</option>
<option value="Data2">IN-Data2</option>
<option value="Data3">IN-Data3</option>
<option value="Data4">AUS-Data4</option>
<option value="Data5">AUS-Data5</option>
<option value="Data6">US-Data6</option>
<option value="Data7">US-Data7</option>
</select>
JavaScript
<script>
function showAlert() {
var el = document.getElementById('dataCountry'); // get the index
var text = el.options[el.selectedIndex].innerHTML; // get the label
var n = text.search("IN"); //search number of IN
if(n>=0) {
alert(text);
}
}
</script>

Javascript auto select from dropdown

I'm searching and searching and can not find anything exactly what I need.
So I need javascript, that will select option from dropdown, but not by the option value number, but name.
I have:
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
So I need to select • Jawor by name, not by id - it's the most important. How do I make it work?
For you is it like;
var options = document.getElementsByClassName("aa")[0].options,
name ="Jawor";
for(i = 0; i < options.length; i++){
if(options[i].text.indexOf(name) > -1){
options[i].selected = true;
break;
}
}
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
U need to Use onChange Event Handler ... for example
<select onchange="showSelected()">
Then write your script ...
<script>
function showSelected(){
var s=document.getElementById('local'); //refers to that select with all options
var selectText=s.options[s.selectedIndex].text // takes the one which the user will select
alert(selectText) //Showing the text selected ...
}
</script>
Rest of your code is okay !
<select class="aa" id="local" name="local" onchange='showSelected'()>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
Using jquery here. You can use the following function:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
}
})
}
A demo:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
return false;
}
})
}
//use the function
setTimeout(function() {
selectFromDropdown('#local', '• Dzierżoniów')
}, 1000)
setTimeout(function() {
selectFromDropdown('#local', '• Jawor')
}, 4000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="aa" id="local" name="local">
<option value="">Select</option>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
for chrome console use this
document.getElementById("id").selectedIndex = '3'; or
document.getElementById('id').value = 'BA';

Categories