I am fairly new to javascript and have tried to work this out on my own, but I am new to some the objects and properties. I believe that the code I have below would work for changing "all" "option" text in the document, but I need it to only change the text value of empty option tags eg; <option></option>
, to <option>Choose One</option>
. I would like it to do this on page load, as the page is generated dynamically by asp.
<script type="text/javascript">
function changeEmpty(){
document.getElementByTagName('option')options[0].text='Choose One';
}
</script>
If it is going to be the first option on the page for one select it would be
document.getElementsByTagName('option')[0].text='Choose One';
It would be better to specify the element so if someone in the future adds a select before it, it will not matter.
document.getElementById("MyId").getElementsByTagName('option')[0].text='Choose One';
"I need it to only change the text value of empty option tags..."
Your syntax is invalid, so I'm not sure why you think it would change all option
elements.
But what you can do is simply iterate them, and test the text content.
var opts = document.getElementsByTagName('option');
for (var i = 0, len = opts.length; i < len; i++)
if (opts[i].text === "")
opts[i].text = "Choose One";
If you really want to change all <option>
s without content, you can use this code
function changeEmpty(){
var els = document.querySelectorAll( 'option' );
for ( var i=els.length; i--; ) {
if ( els.innerHTML.trim() == '' ) {
els.innerHTML = 'choose one';
}
}
}
Assuming that the empty <option>
s will always be the first within each <select>
tag, change to
var els = document.querySelectorAll( 'select > option' );
to save some computations.
EDIT
querySelectorAll()
is supported on all modern browsers, but not in IE7 and previous versions! See caniuse.com .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.