Given an HTML form element like:
<select id='mydropdown'>
<option value='foo'>Spam</option>
<option value='bar'>Eggs</option>
</select>
I know I can select the first option with
document.getElementById("mydropdown").value='foo'
However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?
var desiredValue = "eggs"
var el = document.getElementById("mydropdown");
for(var i=0; i<el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.selectedIndex = i;
break;
}
}
I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.
document.getElementById("mydropdown").text = 'Eggs';
If you want to get an option by its innertext and not by the value you can do this:
function go(){
var dropdown = document.getElementById('mydropdown');
var textSelected = 'Spam';
for(var i=0, max=dropdown.children.length; i<max; i++) {
if(textSelected == dropdown.children[i].innerHTML){
alert(textSelected);
return;
}
}
}
Older IE does not handle options of a select as child nodes, but all browsers implement the text property of a select's option collection.
function selectbytext(sel, txt){
if(typeof sel== 'string'){
sel= document.getELementById(sel) || document.getELementsByName(sel)[0];
}
var opts= sel.options;
for(var i= 0, L= opts.length; i<L; i++){
if(opts[i].text== txt){
sel.selectedIndex= i;
break;
}
}
return i;
}
Related
var arr = {'ukraine' : ['Киев', 'Одесса', 'Харьков'], 'russia' : ['Петербург', "Москва", "Архангельск"], 'belarus' : ['Минск', 'Витебск', 'Гомель']};
var countries = document.getElementById('country');
var cities = document.getElementById('cities');
cities.style.visibility = 'hidden';
countries.addEventListener('change', func);
function func(){
var temp = countries.value;
var city = arr[temp];
if(cities.options != undefined){
for(var i = 0; i < cities.options.length; i++){
alert(i);
cities.removeChild(cities.options[i]);
}
}
for(var i = 0; i < city.length; i++){
var option = document.createElement('option');
option.innerHTML = city[i];
cities.appendChild(option);
}
cities.style.visibility = 'visible';
}
These russian words mean cities. What I'm trying to do is to display second select depending on the option I choose in the first one. But when I'm trying to delete all old options of cities select, it just deletes the first option, even though I put it in the loop? Why does removeChild only work for the first child?
I have a select element:
function find() {
var schoolList = document.getElementByID("schoolList");
if (schoolList.hasAttributes("[data attribute value]") {
//modify text in found option
};
};
find();
<div id="SelectWrapper" class="menu">
<form>
<select id="schoolList">
<option value='student' data-tier="student" data->Student 1</option>
<option value="teacher" data-tier="faculty" data->Teacher</option>
</form>
</div>
Using pure Javascript, I want to create an if statement within a function that checks to see if an option has an appropriate data attribute value (for instance, "student" or "faculty") and then adds to or modifies the existing innerHTML/text.
You can use querySelectorAll() to find all the options with a particular data value, then loop over them.
function find() {
var options = document.querySelectorAll("#schoolList option[data-tier=student]");
for (var i = 0; i < options.length; i++) {
options[i].innerHTML += " (something)";
}
}
The example for you
function find() {
var schoolList = document.getElementById("schoolList");
if (schoolList.hasAttributes("[data attribute value]")) {
var opts = schoolList.getElementsByTagName("option");
for (var i = 0, len = opts.length; i < len; i++) {
var option = opts[i];
// modify
if (option["data-tier"] === "student") {
option.text = "new text content"
}
}
// add new
for (var i =0; i < 5; i++) {
var opt = document.createElement("option");
opt.value = i;
opt.innerHTML = "Option " + i;
schoolList.appendChild(opt);
}
};
};
find();
Here's my try on implementing this:
var select = document.getElementById(key);
var temp = select.value;
select.options.length = 0; // clear out existing items
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data.Value, data.Key))
}
select.value = temp;
In case of there is no such value anymore I would like to set some default values for selcted option.
This is a simple function called init_select
It clear the selection tag
-remembers the option that was previously selected
if the item that was previously selected item is not in the list of new options..it will select the option that you want (this is the default_opt) parameter
-if the previously item is IN the list it will ignore the default_opt paramater and use the previously selected item.
demo here (previously selected item NOT in list but default_opt is IN list)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
demo here (previously selected item IN list and default_opt is IN list, default options is ignored and the previously selected item is selected)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4","year1"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
Your idea of getting the value of select and resetting it was right. You can achieve your wanted result with jQuery like this.
Note that if the old value is not available, select's value will be set to null.
$("button").on("click", function() {
var def = "4. Option";
var temp = $("select").val();
var select = $("select");
select.empty();
for (i = 2; i <= 10; i++) {
$("<option>").text(i + ". Option").appendTo(select);
}
select.val(temp);
if (select.val() == null)
select.val(def);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>1. Option</option>
<option>2. Option</option>
<option>3. Option</option>
<option>4. Option</option>
<option>5. Option</option>
</select>
<button>Clear and Fill Select</button>
I have two sets of data in a JSON file (ACodes and BCodes), which I want to read and display as the options of two different dropdowns in an HTML file. I want to have one common JavaScript function that I can use to get along with the same (shown below) but I am not getting the desired output.
Help about where I am going wrong is much appreciated!
HTML
<script>
var select, option, arr, i;
function loadJSON(var x){
if(x.match == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x.match == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload="loadJSON('A');laodJSON('B')">
<select id="dd1"></select>
<select id="dd2"></select>
</body>
JSON
ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
remove var at loadJSON(var x) => loadJSON(x)
remove .match at x.match == "A", you seems to want to compare x with specific value, not testing it as regexp, so change to x === "A"
laodJSON('B'); at body onload is typo.
There's some reusable codes, you can attract the value depends on x and make the code shorter. This step is not a must do, as it won't cause your origin code unable to work.
<body onload=" loadJSON('A');loadJSON('B');">
<select id="dd1"></select>
<select id="dd2"></select>
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
var array, select, target;
if (x === 'A') {
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
target = 'Code';
} else if (x === 'B') {
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
target = 'Curr';
}
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i][target];
select.add(option);
}
}
</script>
</body>
Edit: to create it more dynamically, you can make the function accept more params, so you can have more control over it. Demo is on jsfiddle.
// Append options to exist select
function loadJSON(jsonObj, key, selectId) {
var arr = JSON.parse(jsonObj);
// Get by Id
var select = document.querySelector('select#' + selectId);
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
}
// Append select with id to target.
function loadJSON2(jsonObj, key, selectId, appendTarget) {
// Get the target to append
appendTarget = appendTarget ? document.querySelector(appendTarget) : document.body;
var arr = JSON.parse(jsonObj);
// Create select and set id.
var select = document.createElement('select');
if (selectId != null) {
select.id = selectId;
}
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
appendTarget.appendChild(select);
}
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
if(x == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload='loadJSON("A");loadJSON("B")'>
<select id="dd1"></select>
<select id="dd2"></select>
</body>
Now this code will work.
The match() method searches a string for a match against a regular expression. So match() function will not work here. You have to use equal operator for get this done.
I hope, This will help you.
You were well on your way, you just need to make it more dynamic :)
function loadOptions(json) {
json = JSON.parse(json);
var select = document.createElement('select'), option;
for (var i = 0; i < json.length; i++) {
for (var u in json[i]) {
if (json[i].hasOwnProperty(u)) {
option = document.createElement('option');
option.text = json[i][u];
select.add(option);
break;
}
}
}
return select;
}
And to use it:
document.body.appendChild(loadOptions(ACodes));
document.body.appendChild(loadOptions(BCodes));
FIDDLE
http://jsfiddle.net/owgt1v2w/
The answers above will help you, but im strongly recommend you to check some javascript's frameworks that can help you with that kind of situation.. The one im using is knockout.js (http://knockoutjs.com/)
Take a look in the documentation, also there a lot of topics related in stackoverflow http://knockoutjs.com/documentation/options-binding.html
Regards!
I'm feeling my way around using JavaScript to populate a HTML5 page - ultimately to link into a Delphi / Datasnap page.
On my page I have a tag setup to provide a listbox as below:
<select id="FirmList" size="10"></select>
I then have a JavaScript script linked to a button that fires on the OnClick
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
The above seems to work - in that Chrome reports no errors and loops through 10 times. However nothing appears in the listbox on the web page, and the length property of sel.option does not increment
I've tried to use other options such as addressing sel.opt directly with no luck
Any suggestions?
You need to use .append()
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
Use
sel.append(opt);
instead of
sel.add(opt);
DEMO
The reason it doesn't work is because sel is a jQuery object, and you're trying to use the native select.add() method, which only works on the native element.
The easy way to fix that would be to do what you seem to have to tried, use getElementById, but you've typed it wrong.
function getJobFirms() {
var sel = document.getElementById("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
as you're already using jQuery, you could just do something like this
function getJobFirms() {
$("#FirmList").append(function() {
return $.map(' (. Y .) '.split(''), function(_,i) {
return $('<option />', {text : (i+1), value : i});
});
});
}
Use below jQuery script
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
sel.append('<option value="'+i+'">'+(i+1)+'</option>');
}
}
Here is working JSFiddle
Since you're already using jQuery, you can use the following to make it more readable. As noted in the other questions, add is not a jQuery method and you need to use any variation of append.
function getJobFirms()
{
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
$('<option/>', {text: i + 1, value: i})
.appendTo(sel);
}
}
Demo
Use append();
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.append(opt);
}
OR DEMO JQUERY
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
sel.append($('<option/>',{'text' : i+1},{"value":i}));
//OR
sel.append("<option value='"+i+"'>"+(i+1)+"</option>")
}