This is an issue that has bothered me to no end. I need to somehow generate options for a select tag from a Json object using Angular. The code looks something like this:
<select id="cargo" ng-model="cargo.values.cargoList">
<option ng-repeat="(class, name, weight) in cargo.values.cargolist
ng-click="orderList()">
</select>
The class cargo.js looks a little like:
function setCargo(){
this.cargo = {
values: {
forkliftNeeded: false,
cargoList: {
class: "class",
name: "name",
weight: "weight"
}
}
};
this.setData = function(input); {
this.cargo.value.cargoList = input.cargo.cargoList;
this.cargo.value.forkliftNeeded = input.cargo.forkliftNeeded;
}:
And the actual Json object:
[{"cargo":{"forkliftNeeded":true,"cargoList":[{"class":"A","name":"Book","weight":"1"}]}}]
The idea it to generate the appropriate number of option tags based on the number of items in the cargo list. Each option needs to display in order and also needs to display the class, name, and weight for each item (for the record, I'm delegating the forkliftNeeded item to a check box).
To make things even more complicated, I also want to make it so that clicking on a given option moves said option to the top of the list. Not just the options, either- it has to actually change the order of the Json object.
As you can imagine, I'm not nearly skilled enough in angular to make this work by myself. Any help you can give me will be greatly appreciated.
EDIT:
I managed to make some headway. Turns out you can do just fine using:
<select id="cargo">
<option ng-repeat="item in cargo.values.cargolist"
ng-click="orderList()">
{{ item.class + " " + item.name + " " + item.weight }}
</option>
</select>
Now all I need to know is how to do the orderList() function. Is there a way I can get the index for the order tags on click?
What you're looking for is ngOptions. Adding that parameter into your <select> tag will automatically fill out the <options> based on your array.
<select id="cargo"
ng-model="cargo.values.cargoList"
ng-options="option.class + ' ' + option.name + ' ' + option.weight as option.name for option in cargo.values.cargoList">
</select>
More on ngOptions here:
https://docs.angularjs.org/api/ng/directive/ngOptions
I have 2 dropdowns and one of them(the second one) is dynamic in the sense that its values change according to the option chosen in the first dropdown.
JSFiddle result: http://jsfiddle.net/pgbw56vb/10/embedded/result/
Can someone pls show me how i can make the second dropdown a multi-select? I'm really green in Jquery and html.
JSFiddle: http://jsfiddle.net/pgbw56vb/10/
<select id="kategorie_oder_seite"></select>
<select id="auswahl"></select>
var data = {
"Kategorie": ["Kraft", "Startseite", "Insurance", "Risk",],
"Seite": ["http://jsfiddle.net/tony089/pgbw56vb/2/", "https://stackoverflow.com/users/login?returnurl=%2fquestions%2fask"],
};
var $kategorien = $("#kategorie_oder_seite").on("change", function() {
var seiten = $.map(data[this.value], function(seite) {
return $("<option />").text(seite);
});
$("#auswahl").empty().append(seiten);
});
for (var kategorie in data) {
$("<option />").text(kategorie).appendTo($kategorien);
}
$kategorien.change();
Thanks in advance.
you can use the multiple attribute of select tag and set its value to multiple. also remember to set the name property in array form so that you could send multiple values via this select control.
eg.
<select multiple="multiple" id="kategorie_oder_seite" name="check[]"></select>
JsFiddle: http://jsfiddle.net/pgbw56vb/10/
just add "multiple" attribute on the "select" tag
Add multiple to your select tags.
<select id="kategorie_oder_seite" multiple></select>
<select id="auswahl" multiple></select>
Here is the code:
$('#date').append(
'<select id="date">'+
'<option value="0">- - SELECT - -</option>');
for(var i in data){
$('#date').append(
'<option value="">'+data[i]['date_time']+'</option>');
});
$('#date').append('</select>');
</select> is always added above for loop. If i replace it with just work select for example, it is appended at the end, where it should be. Why is this happening and how can i fix it?
I believe that jQuery will generate the DOM like this:
<div id="date">
<select id="date">
<option value="0">- - SELECT - -</option>
</select>
<option value="">foo</option>
<option value="">bar</option>
etc...
</div>
Since it is automatically closing the <select> after the first .append(). What you are doing afterwards is appending the options to the <div id="#date"/> rather than the <select> that was appended. I don't think the final closing </select> will actually do anything either.
If you really want to use append the following JavaScript will add the options to the correct node:
// dummy data object for example
var data = new Array(new Array(), new Array());
data[0].date_time = 2011;
data[1].date_time = 2012;
var options = new Array();
$.each(data, function(index, option) {
options.push('<option value="' + index + '">'+ option.date_time +'</option>');
});
$('<select id="date"/>').append(options.join('')).appendTo('#date');
Assuming the existing HTML:
<div id="date"></div>
However this does incur an overhead since appending is occurring twice. The faster approach is to build up the options markup as already answered by ShankarSangoli
It is not the right way to create html dynamically. You should create the complete markup all at once by putting it into an array and then provide it to jQuery. Try this
var html = [];
html.push('<select id="date">');
html.push('<option value="0">- - SELECT - -</option>');
for(var i in data){
html.push('<option value="">'+data[i]['date_time']+'</option>');
}
html.push('</select>');
//This selector should be some container like dateContainer
//because you have already give date as id to the above select element
$('#dateContainer').html(html.join(''));
$('#date').append($("<select/>", { name: "name"+i})
.find('select')
.append($("<option/>", { value: "abc"+i}).text('cell'))
.append($("<option/>", { value: "abc"+i}).text('home'))
.append($("<option/>", { value: "abc"+i}).text('work'));
all options should wrap inside select
I imagine the base HTML you have looks something like this:
<div id="date"></div>
then after the first $('#date').append('<select id="date">... in your code, you will have this:
<div id="date"><select id="date">...</div>
which is 2 elements with the same ID attribute.
The ID attribute is like the highlanders, there must only be one of them (in each page).
The seccond $('#date').append... works unexpectedly, and the 3rd one, also unexpectedly, doesn't work. Because you can't predict to which #date they are referring.
Also, as the other answers say, it will be better if you build it to do only 1 append, because calling the selectors so many times (especially inside the loop) it's a performance hit.
If you want to do it in your way - create, for example, string variable with html code in it and than append it.
data = [1, 2, 3];
var html = '<select id="date">'+
'<option value="0">- - SELECT - -</option>';
for(var i in data){
html += '<option value="">'+data[i]+'</option>';
}
$('#date').append(html)
or look here
What is the best way to add options to a select from an array with jQuery?
ps: the first append tries to create a valid DOM structure inside of document, closing select tag automatically. that is why the second one will not insert options into the created select.
another possible way, based on the link above, is
var sel = $('<select id="date">');
$.each(data, function(key, value) {
sel.append($('<option>').text(key['date_time']));
});
$('#date').append(sel);
a friend asked me to help him with a form, a client of his wants to make a form a bit more dynamic...my javascript is minimal at best since i just started learning.
He asked me something along the lines of " how can i make a form show another pull down ONLY WHEN a certain option is selected "
in the example he gave me, by default when page loads,he has a pull down menu which has 2 options, MANHATTAN and option two is BROOKLYN.
If Manhattan is chose, that reveals another pull down with zips for manhattan, if Brooklyn is chosen the same for BK.
in sample html, something along the lines like this:
<div>
<form>
<select name="boro" id="boro">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
i want to target/capture the option chosen by the user above on the pull down menu, to then activate this function(below).
according to his request what i guess id do is,(as a newbie), then as far as the .js goes (pseudo code):
<script type="text/javascript">
function valBoro (){
if( brook is chosen){ document.getElementById('empty2fill').innerHTML=" new dropdown code here")
}
}
</script>
aside from not knowing, my main problem is i dont know how to target the option chosen in the menu to thereafter, apply the function (which will be written later)
any ideas, tips etc are greately appreciated.
thanks in advance
Another option is to create the two dropdown lists and set the style display to "none". Then you can catch the onChange event and set display to "" based on the value of the select element.
function showZip() {
var boro = document.getElementById("boro");
if (boro.value == "manhattan") {
var zipManhattan = document.getElementById("zipManhattan");
zipManhattan.style.display = "";
}
}
And in the html
<div>
<select name="boro" id="boro" onchange="javascript:showZip();">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<br/>
<select name="zipManhattan" id="zipManhattan" style="display:none;">
<option value="zip1" id="zip1">1111</option>
<option value="zip2" id="zip2">2222</option>
</select>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Here is a link to a jsfiddle showing example code.
http://jsfiddle.net/WKqth/
Example markup:
<div>
<form>
<select name="boro" id="boro">
<option value="" id="none">Select a boro.</option>
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
</form>
<br/>
<div id="empty2fill"></div><!-- for showing chosen results -->
</div>
Example js
// include this js below the form in the body, or wrap it in a function and assign that to window.onload, or use a library that provides onDomReady (in jQuery, $(document).ready(function () ... });
var selectElement = document.getElementById('boro');
var showBoroSelect = function () {
// find the selected element
var selectedOption = selectElement.options[selectElement.selectedIndex].id,
// find the element that will contain the new drop down
containerElement = document.getElementById('empty2fill'),
// define the html for the manhattan drop down
manhSelectInnerHTML = '<select name="secondary"><option value="derp">manh derp?</option><option value="herp!">manh herp!</option></select>',
// define the html for the brooklyn drown down
brookSelectInnerHTML = '<select name="secondary"><option value="derp">brook derp?</option><option value="herp!">brook herp!</option></select>',
newInnerHTML;
// determine which html to use based on the selection
if (selectedOption === 'manh') {
newInnerHTML = manhSelectInnerHTML;
} else if (selectedOption === 'brook') {
newInnerHTML = brookSelectInnerHTML;
} else {
// no boro was selected, hide the menu
newInnerHTML = '';
}
// set the container to the new innerHTML
containerElement.innerHTML = newInnerHTML;
};
// when the boro select changes, show the new menu
selectElement.onchange = function () {
showBoroSelect();
};
// if you select a boro and reload the page, the boro may already be selected (for example, firefox might do this)
// this will set the boro menu initially before the user changes it
showBoroSelect();
You want to handle the change event of your "boro" select element.
I've put a plain-JS example solution on jsfiddle at http://jsfiddle.net/FHArd/1/
This creates three select lists - one is your "boro" and the other two are the zip code lists, but they are hidden via CSS until a selection is made.
The change event handler simply adds and/or removes classes from the zip code select elements; the CSS hides or shows the lists based on the class "active" that is attached to the zip code select list.
Note - being there in jsfiddle the way you start things up is a little different than normal. You'd really run your setup function at the onload or ondomready event.
This should do it.
<select name="boro" id="boro" onchange="valBoro(this)">
<option value="manhattan" id="manh">Manhattan</option>
<option value="brooklyn" id="brook">Brooklyn</option>
</select>
<script type="text/javascript">
function valBoro(dropDown) {
if (dropDown.options.[dropDown.selectedIndex].value.equals("manhattan")) document.getElementById('empty2fill').innerHTML = "newHTMLCode";
//change "manhattan" to whatever option you want to use
}
</script>
Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
<Select id="mySelect" size="9"> </Select>
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)
$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
EDIT: selected answer was close to what I needed. This worked for me:
$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
But both answers led me to my final solution..
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
why not just use plain javascript?
document.getElementById("selectID").options.length = 0;
If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:
$('#mySelect').find('option:not(:first)').remove();
I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.
The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.
$('#mySelect')[0].options.length = 0;
Not sure exactly what you mean by "add one and select it", since it will be selected by default anyway. But, if you were to add more than one, it would make more sense. How about something like:
$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();
Response to "EDIT": Can you clarify what you mean by "This select box is populated by a set of radio buttons"? A <select> element cannot (legally) contain <input type="radio"> elements.
$('#mySelect')
.empty()
.append('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected")
;
$("#control").html("<option selected=\"selected\">The Option...</option>");
Just one line to remove all options from the select tag and after you can add any options then make second line to add options.
$('.ddlsl').empty();
$('.ddlsl').append(new Option('Select all', 'all'));
One more short way but didn't tried
$('.ddlsl').empty().append(new Option('Select all', 'all'));
Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including "selected" in the option that I wanted selected.
$(function() {
$('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
$("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
// Bind click event to each radio button.
$("input[name='myRadio']").bind("click",
function() {
switch(this.value) {
case "1":
$('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
break ;
case "2":
$('#mySelect').find('option').remove() ;
var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
var options = '' ;
for (var i = 0; i < items.length; i++) {
if (i==0) {
options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
}
else {
options += '<option value="' + items[i] + '">' + items[i] + '</option>';
}
}
$('#mySelect').html(options); // Populate select box with array
break ;
} // Switch end
} // Bind function end
); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input name="myRadio" type="radio" value="1" /></label>
<label>Two<input name="myRadio" type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>
I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.
var ClearOptionsFast = function(id) {
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
More info here.
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');
The first line of code will remove all the options of a select box as no option find criteria has been mentioned.
The second line of code will add the Option with the specified value("testValue") and Text("TestText").
Building on mauretto's answer, this is a little easier to read and understand:
$('#mySelect').find('option').not(':first').remove();
To remove all the options except one with a specific value, you can use this:
$('#mySelect').find('option').not('[value=123]').remove();
This would be better if the option to be added was already there.
How about just changing the html to new data.
$('#mySelect').html('<option value="whatever">text</option>');
Another example:
$('#mySelect').html('
<option value="1" selected>text1</option>
<option value="2">text2</option>
<option value="3" disabled>text3</option>
');
Another way:
$('#select').empty().append($('<option>').text('---------').attr('value',''));
Under this link, there are good practices https://api.jquery.com/select/
First clear all exisiting option execpt the first one(--Select--)
Append new option values using loop one by one
$('#ddlCustomer').find('option:not(:first)').remove();
for (var i = 0; i < oResult.length; i++) {
$("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
}
Uses the jquery prop() to clear the selected option
$('#mySelect option:selected').prop('selected', false);
This will replace your existing mySelect with a new mySelect.
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
You can do simply by replacing html
$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
I saw this code in Select2 -
Clearing Selections
$('#mySelect').val(null).trigger('change');
This code works well with jQuery even without Select2
Cleaner give me Like it
let data= []
let inp = $('#mySelect')
inp.empty()
data.forEach(el=> inp.append( new Option(el.Nombre, el.Id) ))
save the option values to be appended in an object
clear existing options in the select tag
iterate the list object and append the contents to the intended select tag
var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};
$('#selectID').empty();
$.each(listToAppend, function(val, text) {
$('#selectID').append( new Option(text,val) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I used vanilla javascript
let select = document.getElementById("mySelect");
select.innerHTML = "";
Hope it will work
$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
var d = data[i];
var option = $('<option/>').val(d.id).text(d.title);
select.append(option);
}
select.val('');
Try
mySelect.innerHTML = `<option selected value="whatever">text</option>`
function setOne() {
console.log({mySelect});
mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9">
<option value="1">old1</option>
<option value="2">old2</option>
<option value="3">old3</option>
</Select>
The shortest answer:
$('#mySelect option').remove().append('<option selected value="whatever">text</option>');
Try
$('#mySelect')
.html('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected");
OR
$('#mySelect').html('<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
<option value="7">Value 7</option>
<option value="8">Value 8</option>')
.find('option:first')
.prop("selected",true);