I have a select tag with multiple options and when the page is loaded I would like to put the selected options in first positions in the list. I'm using angular so my code for the select is :
<select class="form-control" id="field_shopName" multiple name="shopName [(ngModel)]=" product.shopNames ">
<option [ngValue]="getSelected(product.shopNames, shopPdvOption) " *ngFor="let shopPdvOption of shoppdvs; trackBy: trackShopPdvById ">{{shopPdvOption.shopPdV}}</option>
</select>
Is it possible to acheive this with only html5 or javascript ?
It is possible. The example below will add an extra list of fruits first.
window.onload = function () {
var select = document.getElementById("fruits");
var firstFruits = ['Kiwi', 'Peach', 'Orange'].reverse();
firstFruits.forEach(function (fruit) {
var option = document.createElement('option');
option.text = option.value = fruit;
select.add(option, 0);
})
};
<select id="fruits">
<option>Apple</option>
</select>
Related
For my code i need 2 selects, the first select is static (4 options that dont change) and the second select is dependant on what is selected in the first select.
Then depending on what is chosen in de the second list a function is executed.
i found some example code one W3schools that allow me to make the whole list thing:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_options3
So this works really well but now i dont know how to attach a function to the selected options in the second select since there is no where in the html to do something like an onchange.
Each option from the second select should have a function (in my code the selected option will display an image corresponding with the chosen option)
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>
I am adding dropdowns dynamically by code it is rendered in browser like
<select id="contact-type1"></select>
<select id="contact-type2"></select>
...
Now I am trying the below code for dynamically selecting nth number of dropdown in order to fill option values in them.
function fillContactTypes()
{
var types = ["Phone","Whatapp","Facebook","Web","Fax"];
var select = document.getElementById('contact-type[*n]');
for(var i = 0; i < types.length; i++)
{
var option = document.createElement('option');
option.innerHTML = types[i];
option.value = types[i];
select.appendChild(option);
}
}
Please help me in the line "var select = document.getElementById('contact-type[*n]');
".
I have just added common class to all dropdowns and using jquery you can dynamically bind all dropdown as shown below.
var types = ["Phone","Whatapp","Facebook","Web","Fax"];
$(document).ready(function(){
fillContactTypes()
});
function fillContactTypes(){
var myselect = $('<select>');
$.each(types, function(index, key) {
myselect.append( $('<option></option>').val(key).html(key) );
});
$('.contact-type').append(myselect.html());
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<select id="contact-type1" class="contact-type">
</select>
<select id="contact-type2" class="contact-type">
</select>
<select id="contact-type3" class="contact-type">
</select>
<select id="contact-type4" class="contact-type">
</select>
I have two html select element that the second one is disabled at first and only become enable if user choose one option from first select. consider we have 2 options in first select -> a , b if user choose a : in the second select options should be : a1,a2 if user choose b : in the second select options should be : b1,b2 ... I dont know what am i doing wrong that these two select options have conflict with each other !!!
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
All you need to do is clear out the previous entries in the second drop down every time a selection is made in the first one.
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
// Clear out the second list before adding new items to it
document.getElementById('sub-category').innerHTML = "";
// *******************************************************
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
But, beyond that, your code needs to be cleaned up quite a bit because you shouldn't be scanning the document for the element you want to work with over and over again when you've already found it before. That's extremely wasteful.
Also, .innerHTML is for passing strings that contain HTML so that the HTML parser can parse the string and update the DOM accordingly. You are just setting plain strings with no HTML in them, so you should be using .textContent instead, which doesn't invoke the HTML parser and is more efficient.
Next (just FYI), if you want the value of an option to be the same as the text that is displayed to the user, you don't need to set a value for that option. The value is the contents of the option element by default.
Really, the entire operation can be made so much simpler by simply making new options in list2 based on the first letter of the option chosen in list1.
// Get references to the elements you'll be working with just once:
var list1 = document.getElementById("main-category");
var list2 = document.getElementById('sub-category');
list1.onchange = function() {
list2.disabled = false;
var newHTML = ""; // A string that will contain the new HTML for the second list
// Loop the amount of times we find <option> elements in list one, but start
// at the second one to account for the first one, which isn't really a true choice
for(var i = 1; i < list1.querySelectorAll("option").length; i++){
// Build up a string that the new option should be made from using the
// first character from the option found in list 1
newHTML += '<option>' + list1.value.substr(0,1) + i + '</option>';
}
// By setting a new value for .innerHTML, the old values get thrown out.
list2.innerHTML = newHTML;
};
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option>a</option>
<option>b</option>
</select>
<select id="sub-category" required disabled> </select>
I need to check textbox value against dropdown list, and if that value does not exist, add to the list.
I have this script:
<select id="drop" onchange="ChooseContact(this)">
<option value="Volvo Red">Volvo Red</option>
<option value="Mers Blue">Mers Blue</option>
<option value="Ferr red">Ferr red</option>
</select>
function execute(data) {
var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
if ( document.createElement('option').value != txtbox ) {
var categories = document.getElementById("drop");
var newOption = document.createElement('option');
newOption.innerText = txtbox ;
newOption.setAttribute('value', txtbox );
categories.appendChild(newOption);
}
document.getElementById("drop").value = txtbox ;
}
But the new item is still created in the dropdown list, eventhough such item already there. Thanks.
You are not searching for the text among the options. Here is how you could do that:
add.addEventListener('click', execute);
function execute(data) {
var txtbox = txtServiceReportInspectedBy.value,
optionTexts = Array.from(document.querySelectorAll('#drop>option'),
option => option.value);
if ( !optionTexts.includes(txtbox) ) {
var newOption = document.createElement('option');
newOption.value = newOption.textContent = txtbox ;
drop.appendChild(newOption);
}
drop.value = txtbox;
}
<input id="txtServiceReportInspectedBy"><button id="add">Add</button><br>
<select id="drop">
<option value="Volvo Red">Volvo Red</option>
<option value="Mers Blue">Mers Blue</option>
<option value="Ferr red">Ferr red</option>
</select>
On your "if" sentence you are creating a new element "option" so always is going to be different your "value", so always is going to create a new element inside your "select" tag
You need to iterate for the elements of your "select" tag to find if its value exist or not
im trying to get multiple options on a multiple select and add them in a normal select but when i click on a button to add, for exemple, i select on two options and add them they change to one option on the normal select
JSFIDDLE EXAMPLE
JavaScript CODE
function addProf() {
// get reference to select element
var sel = document.getElementById('ProfAdd');
var opt = document.createElement('option'); // create new option element
// create text node to add to option element (opt)
if ($(this).find('option[value="' + sel + '"]').length == 0) {
opt.appendChild(document.createTextNode(document.getElementById('selProf').value));
opt.value = 'option val'; // set value property of opt
sel.appendChild(opt); // add opt to end of select box (sel)
$("#selProf").find('option:selected').remove();
}
}
function remProf() {
// get reference to select element
var sel = document.getElementById('selProf');
var opt = document.createElement('option'); // create new option element
// create text node to add to option element (opt)
if ($(this).find('option[value="' + sel + '"]').length == 0) {
opt.appendChild(document.createTextNode(document.getElementById('ProfAdd').value));
opt.value = $("#ProfAdd :selected").text(); // set value property of opt
opt.text = $("#ProfAdd :selected").text();
sel.appendChild(opt); // add opt to end of select box (sel)
$("#ProfAdd").find('option:selected').remove();
}
}
HTML CODE
<div class="form-group">
<label for="InputProf">Adicionar professores à turma</label>
<select id="selProf" class="form-control" required>
<option disabled selected>Professor</option>
<option value="2">2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<input type="button" id="button6" class="myButton2" onclick="addProf()" value="Adicionar Professor">
</br>
<div class="form-group">
<label for="InputTurma">Professores adicionados</label>
<select multiple class="form-control" id="ProfAdd">
</select>
</div>
<input type="button" id="button7" class="myButton2" onclick="remProf()" value="Retirar Professor">
If you have two options selected, $('select :selected').text() will return a single string concatenated selected text's. See fiddle.
Because :selected is returning multiple elements, you'll want to loop through them, and do something with each. One way of doing this is using jQuery.each.
You'll need to create a new option for each selected one - I've moved a little
$("#ProfAdd :selected").each(function (idx, selOpt) {
var opt = document.createElement('option'); // create new option element
opt.appendChild(document.createTextNode(document.getElementById('ProfAdd').value));
opt.value = $(selOpt).text(); // set value property of opt
opt.text = $(selOpt).text();
sel.appendChild(opt); // add opt to end of select box (sel)
$(selOpt).remove();
});
http://jsfiddle.net/daveSalomon/0b0obyra/5/
The code still isn't ideal - you're mixing document.getElementById (vanilla JS) with $('#id') (jQuery). Pick one and stick to it.
Here's a much cleaner solution...
var $multiSel = $('#ProfAdd');
var $singleSel = $('#selProf');
$('#button6').click(function(){
var $opts = $singleSel.find('option:selected');
$multiSel.append($opts).val('');
});
$('#button7').click(function(){
var $opts = $multiSel.find('option:selected');
$singleSel.append($opts).val('');
});
http://jsfiddle.net/daveSalomon/0b0obyra/8/