Adding option elements using .innerHTML in IE is not working - javascript

I have a variable ddEmail having value
<option value="cp#cp.ljj" selected="">cp#cp.ljj</option>.
When I try to put it in select element using
document.getElementById("txtEmail").innerHTML = ddEmail;
then in Firefox document.getElementById("txtEmail").innerHTML shows me the same value as of ddEmail while in IE it shows cp#cp.ljj</option>
Is there any way to resolve it?

As you've discovered, you can't reliably use innerHTML to set the options of an existing select.
The best way it through the select's options property:
var option = new Option("cb#cb.ljj", "cb#cb.ljj");
// Option text --------^ ^---- option value
option.selected = true;
document.getElementById("txtEmail").options.add(option);
Note that for historical reasons, it's add, not push. push works on lots of browsers, but not all of them.
Also note that the above assumes that either there are no options in the select, or you just want to add this one, not replace all of the ones already there with it. If you want to remove the previous options:
var sel = document.getElementById("txtEmail");
sel.options.length = 0;
sel.options.add(option);

Related

Error adding options to a select menu with javascript

I was having two problems: the first is that javascript is not adding options to a menu, and the second was an "Unexpected or invalid token" error at the end of my for loop.
Update:
The token error was a weird character thing. I deleted the line that was causing the problem and retyped it and now I am not getting the error anymore, but my script still is not adding options.
I have read about adding options to a select menu but the answers I've found there haven't worked for me. I should point out that this is part of a Joomla website (v3.8), because that can cause some unexpected behaviour.
I have a function which is supposed to pick out a particular select menu based on the string "id", clear its contents, and re-populate it with the elements of the "options" array.
function resetSelectMenu(id, options){
// Selects the correct menu, enables it, and removes all of its options.
var selectMenu = jQuery('#sel-' + id);
selectMenu.prop('disabled', false);
selectMenu.empty();
// Makes an option element and sets its text and value.
var el = document.createElement("option");
el.text = 'blah';
el.value = 'blah';
// Does not succeed in adding an option to menu.
selectMenu.add(el);
// I declared loop variables here to make sure there are no re-declaration issues.
var i;
var opt;
// The loop is entered and the array is iterated through.
for(i = 0; i < options.length; i++){
opt = options[i];
el = document.createElement("option");
el.text = opt;
el.value = i + 1;
// Does not succeed in adding an option to menu.
selectMenu.add(el);
}​
}
The function does target the correct menu and clear its contents, but it is not adding the "blah" option or anything from the "options" array. I've tried using "appendChild(el)" instead of add but I get an error of the form "appendChild() is not a function". I did a lot of console logs to determine that all the parts of the code are working as expected except for "selectMenu.add(el);"
So this was just a noob mistake. I looked a bit harder and found this related question, and the top answer by Matt told me I needed to use append(el) instead of add(el). I looked into the documentation and the add method just affects the jQuery object but doesn't actually affect the DOM at all, whereas append does. If I were to use add I would need to explicitly tell the jQuery object to refresh the DOM.
It's also possible that there is still an issue with me using selectMenu.empty() instead of something like selectMenu.find('option').remove(), but at the moment it's not causing any errors. Since my select element only contains option elements I feel like these two commands would be the same, but on the other hand maybe the latter is better because it allows for the addition of different kinds of elements later.

How in XPages CSJS should I select a ComboBox value?

I am using CSJS in the 'onChange' Event in a ComboBox, and when a user selects a value, I want an EditBox and a second ComboBox to be set (The second ComboBox value is one that is already in the list, I just want to select it).
To set the EditBox in my 'onChange' Event I used:
XSP.getElementById("#{id:fldEditBox}").value = newEditBoxValue;
But selecting a value in the ComboBox was much harder. At first I used the EditBox method:
XSP.getElementById("#{id:fldComboBox2}").value = selectedComboBoxValue;
The on screen value changed, and the ComboBox functioned normally, when the document was saved it still had the old value.
I tried all sorts of things like selectedIndex but nothing worked. Eventually I found that this:
document.getElementsByName("#{id:fldComboBox2}")[0].value = selectedComboBoxValue;
meant the change was saved, but was not visible on screen, so in my final production code I used both and it works:
XSP.getElementById("#{id:fldComboBox2}").value = selectedComboBoxValue;
document.getElementsByName("#{id:fldComboBox2}")[0].value = selectedComboBoxValue;
This seems ugly to me, there must be a better way of doing this in CSJS, does anybody know?
The way you set the value of a select element (combobox) in vanilla JavaScript is to loop through the elements options property to find the option you want to select:
var comboBox = document.getElementById("#{id:comboBox}");
for (var i=0; i < comboBox.options.length; i++) {
if (comboBox.options[i].value == "ValueYouWantSelected") {
comboBox.options.selectedIndex = i;
break;
}
}
If you have JQuery available you can do it more elegantly:
var xpageID = "#{id:comboBox}".replace(/:/gi, "\\:");
var valueYouWantSelected = "someValue";
$('#' + xpageID + ' option[value="' + valueYouWantSelected + '"]').prop('selected', true);
The xpageID variable is there because you have to escape the ':' characters that XPages puts in the generated IDs for it to work with the JQuery selector engine.

Javascript clear content of selectbox

As part of my populating selectbox function I am clearing the contents of the populated select box and then inserting options to a empty box. Although the select box is not being cleared correctly and a lot of options are not removed. I am using the following code to clear the contents of the select box:
for(var i = 0; i < document.getElementById(selectbox).options.length; i++)
document.getElementById(selectbox).options[i] = null;
Why not all the options are removed from the selectbox?
You can simply do
document.getElementById(selectbox).options.length = 0;
You could also have removed the elements one by one, almost like you did, but you must take into account the fact the length of options changes when you iterate. The correct way to remove while iterating would have been
for (var i=document.getElementById(selectbox).options.length; i-->0;)
document.getElementById(selectbox).options[i] = null;
But the first solution is simpler of course.
var selectbox = document.getElementById(selectbox);
document.getElementById("emptyBox").innerHTML = selectbox.innerHTML;
selectbox.innerHTML = "";
As an alternative and more terse method of clearing all options of a select list, we can take advantage of JavaScript's falsey value of zero and then simply remove the option from the Dom:
function clearSelectList(list) {
// when length is 0, the evaluation will return false.
while (list.options.length) {
// continue to remove the first option until no options remain.
list.remove(0);
}
}
Usage would then be:
var list = document.getElementById("selectbox");
clearSelectList(list);
Or more succinctly:
clearSelectList(document.getElementById("selectbox"));
this example with new generation JavaScript. I do recommend to use.
[...cbrCenterSelectbox.options].forEach(option => option.remove())

Switching HTML menu value before submit?

So I have a menu with a list of every country and its abbreviation. I want to send the full name (the text of the menu option) instead of the value. So I tried to make a function, switchval(), to do this but it did not switch the values. Any ideas?
function switchval(){
var countries = document.getElementById('countries');
countries = countries.options[countries.selectedIndex].text;
document.getElementById('countries').value = countries;
}
Set the value of the option element. I changed the variable names so they make more sense. Please consider your coding style and use good variable names, and don't use a variable twice for a different datatype (that is insane). Also, setting the value of the option element is just plain wrong, I felt dirty typing this.
function switchval(){
var selectEl = document.getElementById('countries');
var optionEl = selectEl.options[selectEl.selectedIndex];
var country = optionEl.text;
optionEl.value = country;
}
I'll second what buddhabrot showed and said - changing the value property is wrong and might not be supported in all browsers.
I would use a hidden element and set the text property into that, changing the name of the select element to something like "countries-select" and making the hidden element "countries".
That way when your form posts, it will have the proper "name" for the form processor, plus you'll have a reliable method in your code.

Internet Explorer doesn't know how to add options tag to a select in jQuery

Im facing a problem with jQuery in the Internet Explorer 7 and 8, while trying to add a option to a existing select:
var s = document.getElementById("category");
s.options.add(select_option);
But IE just says:
Object doesn't support this property or method
and points to s.options.add(select_option);
Assuming the element with id "category" is actually a <select>, the easiest way is the the following time-honoured code for adding an option to a select list in any browser:
var s = document.getElementById("category");
s.options[s.options.length] = new Option("Option text", "optionValue");
try
$('#category').append('<option value="foo" selected="selected">Foo</option>');
or
var options = $('#category').attr('options');
options[options.length] = new Option('Foo', 'foo', true, true);
This soulution is working fine under IE8 - copied from MIcrosoft forum -
"I assume you already got the answer you needed, but for anyone else who finds this post when searching this problem (like I did), here's the solution that worked for me. All it took was setting the properties on opt AFTER adding it to the options collection. I also found that MSDN's page on the add function (for the options collection) explicitly states that for IE, the properties must be set after the option is added, but most of the examples I found online don't do it that way. I think your way may have worked in older versions of IE."
var opt = document.createElement('option');
select.options.add(opt);
opt.innerHTML = 'Foo';
opt.value = 'Bar';
Should the add() call not be on the select element, rather than the collection of options? I.e.:
s.add(select_option);

Categories