removing all option of dropdown box in javascript - javascript

How can i dynamically remove all options of a drop down box in javascript?

document.getElementById('id').options.length = 0;
or
document.getElementById('id').innerHTML = "";

var select = document.getElementById('yourSelectBox');
while (select.firstChild) {
select.removeChild(select.firstChild);
}

Setting the length to 0 is probably the best way, but you can also do this:
var mySelect = document.getElementById("select");
var len = mySelect.length;
for (var i = 0; i < len; i++) {
mySelect.remove(0);
}

<select id="thing"><option>fdsjl</option></select>
<script>
var el = document.getElementById('thing');
el.innerHTML = '';
// or this
while ( el.firstChild ) {
el.removeChild( el.firstChild )
}
</script>

Its very easy using JavaScript and DOM:
while (selectBox.firstChild)
selectBox.removeChild(selectBox.firstChild);

The fastest solution I was able to find is the following code (taken from this article):
// Fast javascript function to clear all the options in an HTML select element
// Provide the id of the select element
// References to the old <select> object will become invalidated!
// This function returns a reference to the new select object.
function ClearOptionsFast(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;
}

There is simple and elegant way to do this:
for(var o of document.querySelectorAll('#id > option')) {
o.remove()
}

Related

getElementsByTagName: How to select more than one type of tag?

I have a for loop inside which I check to see if the current element being iterated has any a tags or form tags inside of it and if so I do some stuff to them. Anyway I can check either or like so:
var form_or_a_tag = elem[i].getElementsByTagName('a');
var form_or_a_tag = elem[i].getElementsByTagName('form');
But how can I combine them?
these all fail:
var form_or_a_tag = elem[i].getElementsByTagName('a form');
var form_or_a_tag = elem[i].getElementsByTagName('a, form');
var form_or_a_tag = elem[i].getElementsByTagName('a') || elem[i].getElementsByTagName('form');
Basically I would like to store in the variable form_or_a_tag all form or a tags that reside in the element currently being iterated.
This might work:
var nodelist_a = elem[i].getElementsByTagName('a'); // NodeList
var nodelist_form = elem[i].getElementsByTagName('form'); // NodeList
var array_a = Array.prototype.slice.call(nodelist_a); // Array
var array_form = Array.prototype.slice.call(nodelist_form); // Array
var array_both = array_a.concat(array_form); // Array
Note that the result is no longer a NodeList but an Array; however each item is a Node.
You can use querySelectorAll.
var form_or_a_tag = elem[i].querySelectorAll('a, form');
I do not think that this function supports this feature. AFAIK you can use only getElementsByTagName("*") wildcard to select all nodes. You can try some library like Sizzle to use CSS selectors.
If sequence of nodes is important, here is pure Javascript solution:
var getNodesInTreeByNodeName = function (node, /*Array of Strings*/ allowed_node_names)
{
var childCollection = [];
var getTreeNodes = function (tree_root)
{
if (allowed_node_names.indexOf(tree_root.nodeName) > -1)
childCollection.push(tree_root);
var childs = tree_root.childNodes;
if (childs)
for (var i=0, childs_length=childs.length ; i<childs_length ; i++)
getTreeNodes(childs[i]);
};
getTreeNodes(node);
return childCollection;
};
Example of use:
var node_types = ["A","FORM"];
var nodes = getNodesInTreeByNodeName(window.document, wanted_nodes);

Loop through an Array to enable checkboxes

I'm have a set of checkboxes and an array that contains the index of which checkboxes should be selected. I'm trying to loop through the array and for each index in it. I made a sample jsFiddle to give you guys an idea of what I'm trying to do. I have the JQuery library also if that makes things easier. http://jsfiddle.net/7EetA/1/
Try this:
var arrx=new Array();
arrx[0]=4;
arrx[1]=5;
arrx[2]=3;
arrx[3]=1;
for (var i = 0; i < arrx.length; i++) {
document.getElementsByName('cal')[arrx[i]].checked = true;
}
​
No jQuery needed! jsFiddle example
var arrx=new Array();
arrx[0]=4;
arrx[1]=5;
arrx[2]=3;
arrx[3]=1;
var calArray = document.getElementsByName("cal");
for (var i = 0; i < arrx.length; i++) {
calArray[arrx[i]].checked = true;
}
If you insist on using jQuery:
var arrx=new Array();
arrx[0]=4;
arrx[1]=5;
arrx[2]=3;
arrx[3]=1;
var i = 0;
$('[name=cal]').each(function() {
if ($.inArray(i, arrx) != -1) {
$(this).prop('checked',true);
}
i++;
});
Working example
If you are willing to use jQuery, it can do it quite easily based on the name of the input:
jQuery('[name="cal"]').each(function(i){jQuery(this).attr('checked', 'checked');});
If your goal is to not necessarily select all of them, however, you could use something like this:
jQuery('[name$="_c"]').each(function(i){jQuery(this).attr('checked', 'checked');});
which only checks inputs with _c at the end of the name.
http://jsfiddle.net/7EetA/9/

How to get the index of an option in a select menu by matching the text with plain Javascript?

I have a select menu and I need to dynamically select the option based on the text value of the option element. For example, my select looks like this:
<select id="names">
<option value="">Please Select</option>
<option value="1">John</option>
<option value="2">Steve</option>
<option value="3">Max</option>
</select>
If I have the string "Max", how can I get that the index of the option is 4 so I can dynamically set this as the selectedIndex with JavaScript?
No jQuery.
http://jsfiddle.net/x8f7g/1/
You want to select the element, iterate over the array, find the text value, and return the index.
Don't use InnerHTML, it's slow and breaks and not standards compliant
Dont use innerText, simmilar reasons but not quite as serious
Do use a function so you can do it all over again.
Do select the child text node, and retreives the nodeValue, which is cross-browser friendly
Example:
function indexMatchingText(ele, text) {
for (var i=0; i<ele.length;i++) {
if (ele[i].childNodes[0].nodeValue === text){
return i;
}
}
return undefined;
}
Try this, it should find and then select the relevant option in the select box.
var searchtext = "max";
for (var i = 0; i < listbox.options.length; ++i) {
if (listbox.options[i].text === searchtext) listbox.options[i].selected = true;
}
var opts = document.getElementById("names").options;
for(var i = 0; i < opts.length; i++) {
if(opts[i].innerText == "Max") {
alert("found it at index " + i + " or number " + (i + 1));
break;
}
}
Demo.
in PLAIN js
var sel, opts, opt, x, txt;
txt='Max';
sel=document.getElementById('names');
opts=sel.options;
for (x=0;x<opts.lenght;x++){
if (opts[x].text === txt){
opt=opts[x];
}
}
The options property stores the options in a select menu - iterate over it and compare the contents.
var list = document.getElementById("names").options;
for(var i = 0; i<list.length; i++){
if(list[i].text== "Max") { //Compare
list[i].selected = true; //Select the option.
}
}
JSFiddle: http://jsfiddle.net/cuTxu/2
You could use this short function to do that:
function findIndexfromOptionName( select, optionName ) {
let options = Array.from( select.options );
return options.findIndex( (opt) => opt.label == optionName );
}
Arguments:
select: an HTMLSelect element
optionName: as a string
Explanation:
On the first line of the function body we retrieve the <select> options as an array using Array.from().
This allow us to use Array.prototype.findIndex() to return the index of the first option that match the provided name, if any or return -1 if there is no match.
Want some reasons to use it ?
It has a short implementation and the semantic is pretty clear. Also pure JS.
This should do the trick:
var options = document.getElementsByTagName('select')[0].children,
i,
l = options.length,
index;
for(i = 0; i < l; i++){
if(options[i].firstChild.nodeValue === 'Max'){index = i};
}
Please note that the index is zero based, what mean it is one less than you would expect.
var x = document.getElementById("names");
for(var i = 0; i<x.options.length; i++){
if("Max" == x.options[i].text){
doSomething();
//maybe x.selectedIndex = i;
}
}
[edit - expanded to include non-jquery method]
I strongly recommend using jQuery for this since the solution is a one-liner:
jQuery('#names option:contains("Max")').val()
However, here's a pure JavaScript implementation anyway:
function findOption( select, matchMe ) {
var
// list of child options
options = select.getElementsByTagName('option'),
// iteration vars
i = options.length,
text,
option;
while (i--) {
option = options[i];
text = option.textContent || option.innerText || '';
// (optional) add additional processing to text, such as trimming whitespace
text = text.replace(/^\s+|\s+$/g);
if (text === matchMe) {
return option.getAttribute('value');
}
}
return null;
}
Example usage:
alert(
findOption(
document.getElementsByTagName('select')[0],
"Max"
)
);
Alerts 3

Selecting elements without jQuery

I guess this will be voted down, as it doesn't contain enough jQuery, but here it goes :)
What is the most effective way to get the element(s) returned by the jQuery selector below using plain old javascript?
$('a[title="some title text here"]', top.document)
If you're using a modern browser, you could use this:
window.top.document.querySelectorAll('a[title="some title text here"]')
Not sure if it’s the most effective, but at least it works.
var links = top.document.getElementsByTagName('a');
var result = [];
var linkcount = links.length;
for ( var i = 0; i < linkcount; i++) {
if (links[i].getAttribute('title') === 'some title text here') {
result.push(links[i]);
}
}
Here is an example
var getElements = function(tagName, attribute, value, callback) {
var tags = window.document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tag = tags[i];
if (tag.getAttribute(attribute) == value) {
callback(tag);
}
};
};
getElements("a", "title", "PHP power player at Hettema & Bergsten. Click to learn more.", function(tag) {
console.log(tag);
});

How do I clear the contents of a div without innerHTML = "";

I have a div that is filled by JS created DOM elements,
I want the div to be cleared upon the JS function repeating, however I have heard that using document.getElementById('elName').innerHTML = ""; is not a good idea,
What is a valid alternative to doing this to clear the div's contents?
If you have jQuery then:
$('#elName').empty();
Otherwise:
var node = document.getElementById('elName');
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
The Prototype way is Element.update() e.g.:
$('my_container').update()
If you're using jQuery have a look at the .empty() method http://api.jquery.com/empty/
You could loop through its children and remove then, ie.
var parDiv = document.getElementById('elName'),
parChildren = parDiv.children, tmpChildren = [], i, e;
for (i = 0, e = parChildren.length; i < e; i++) {
tmpArr.push(parChildren[i]);
}
for (i = 0; i < e; i++) {
parDiv.removeChild(tmpChildren[i]);
}
Or use .empty() if you are using jQuery.
This is just an alternative solution, a while loop is much more elegant.
You can redefine .innerHTML. In Firefox and Chrome, it's not a problem to clear the elements with .innerHTML = "". In IE, it is, because any child elements are immediately cleared. In this example, "mydiv.innerHTML" would normally return "undefined". (without the redefine, that is, and in IE 11 as of the date of this post creation)
if (/(msie|trident)/i.test(navigator.userAgent)) {
var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
Object.defineProperty(HTMLElement.prototype, "innerHTML", {
get: function () {return innerhtml_get.call (this)},
set: function(new_html) {
var childNodes = this.childNodes
for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
this.removeChild (childNodes[0])
}
innerhtml_set.call (this, new_html)
}
})
}
var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)
document.body.innerHTML = ""
console.log (mydiv.innerHTML)
http://jsfiddle.net/DLLbc/9/
2022 Answer:
Use element.replaceChildren()
Emptying a node
replaceChildren() provides a very convenient mechanism for emptying a node of all its children. You call it on the parent node without any argument specified:
Doc

Categories