Element not being selected dynamically from datalist - javascript

I have this list on my HTML page of country codes as part of a form:
<input list="countryCodesLst" name="countryCodes">
<datalist id="countryCodesLst">
...
<option value="93">
<option value="355">
<option value="213">
...
And I have this code in javascript after the list mentioned above:
<script type="text/javascript">
var codes = [{"BD": "880", "BE": "32"...}];
var what = $.get("http://ipinfo.io", function(response) { updateResponse(response);}, "jsonp");
function updateResponse(data){
countryCode = data;
}
var CC = countryCode.country;
console.log(CC);
function getValueByKey(key, data) {
var i, len = data.length;
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
return data[i][key];
}
}
return -1;
}
var found = getValueByKey(CC,codes);
console.log(found);
var element = document.getElementById('countryCodesLst');
element.innerHTML = found;
</script>
However, even though I see that the code does found the value, it does not set the value in the dropdown list.
Can you please help me understand why?

Related

Programatically selecting an item from a <select> drop-down

I am a technical writer working to create a knowledgebase with Madcap Flare. I need my users to be able to select the version of the software that they are using so that I can serve the appropriate content.
I am using this guide: Version Filtering with Madcap Flare
Flare allows me to tag content during the writing process, then I can use JS to target those tags to dynamically hide/show content based on the users selection from the drop down by applying display="none" to all versions not selected. This all works but I am not able to have the most recent version preselected. On page load, all content is visible. If I use the item will be select in the drop down, but it doesn't do anything in terms of applying display="none" to all other versioned content. Any ideas?
< script type = "text/javascript" > /*<![CDATA[*/ function getElementsWithAttribute(attr) {
var elementsWithAttribute = [];
var elements = document.body.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute(attr)) {
elementsWithAttribute.push(elements[i]);
}
}
return elementsWithAttribute;
}
function showHideVersion() {
var elements = getElementsWithAttribute('data-mc-conditions');
var e = document.getElementById('version-select');
var selectedVersion = e.options[e.selectedIndex].value;
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute('data-mc-conditions').indexOf(selectedVersion) > -1) {
elements[i].classList.remove("hidden1");
localStorage.id = e.options[e.selectedIndex].value;
} else {
elements[i].classList.add("hidden1");
}
}
}
function myFunction() {
var elements = getElementsWithAttribute('data-mc-conditions');
var locals = localStorage.getItem('id');
if (locals == null) {
localStorage.id = "Default.V9";
locals = localStorage.getItem('id');
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute('data-mc-conditions').indexOf(locals) > -1) {
elements[i].classList.remove("hidden1");
document.getElementById('version-select').value = locals;
} else {
elements[i].classList.add("hidden1");
}
}
} else {
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute('data-mc-conditions').indexOf(locals) > -1) {
elements[i].classList.remove("hidden1");
document.getElementById('version-select').value = locals;
} else {
elements[i].classList.add("hidden1");
}
}
}
} /*]]>*/ < /script>
<div class="version-select">
<select id="version-select" onchange="showHideVersion()" width="100%">
<option value="Default.V8">Version 8</option>
<option value="Default.V9">Version 9</option>
</select>
</div>

JS select correct line in select list

I am using this JS code to do some magic. Working perfect to get a variabele and remove unwanted text and display the correct text in a text field.
values 2 or 3 or 5 or 7 etc. in <input type="text" id="calc_dikte[0][]" name="calc_dikte[]" value="">
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
if(isNaN(elems_1_split_2[0])) { elems_2[i].value = ''; }
else { elems_2[i].value = parseFloat(elems_1_split_2[0]); }
}
}
}
So this works, but now the form field has changed from text to select like:
<select id="calc_dikte[0][]" name="calc_dikte[]">
<option value="">
<option value="2|2000">2</option>
<option value="3|2000">3</option>
<option value="5|2000">5</option>
<option value="7|2000">7</option>
</select>
Therefore I have changed my JS code (with some tips from here) to:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var sel = elems_2[i];
var val = parseFloat(elems_1_split_2[0]);
for(var m=0, n=sel.options.length; m<n; m++)
{
if(sel.options[i].innerHTML === val)
{
sel.selectedIndex = m;
break;
}
}
}
}
}
But this is not working, no item is selected in the select list, no errors are shown.
Please help me out change to a working code to have the correct line selected. It should not select on the value but in the text between the ><
option value="5|2000">5</option
If I check with
for(var m=0, n=sel.options.length; m<n; m++) {
alert('sel = '+sel.options[i].innerHTML+'\nval = '+val);
}
I see that val is correct. But sel is just the number as used in $i so 0 1 2
You are using a strict equals operator to compare a Number (parseFloat) agains .innerHTML, which is always a string.
Convert sel.options[i].innerHTML to a Number aswell:
if (parseFloat(sel.options[i].innerHTML) === val) {
sel.selectedIndex = m;
break;
}
If you want to filter out invalid numbers (NaNs), use !isNaN(val) aswell.
Code to get this working:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var val = parseFloat(elems_1_split_2[0]);
var sel = elems_2[i];
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++)
{
if (opt.text == val)
{
sel.selectedIndex = j;
break;
}
}
}
}
}

How to retain a selected value in dynamically generated dropdown box to the next jsp page?

I have a drop down box where the options are coming from the configured properties file.The options are generated on load of the page.I have used the following code.
In JSP
<select name="IDNo" id="IDNo">
</select>
function loading()
{
var d = document.getElementById("system");
var df=document.getElementById("IDNo");
var i = 0;
var disp = document.getElementById("Range");
var numberOfOptions = df.options.length;
for (i = 0; i < numberOfOptions; i++) {
df.remove(0);
}
if (d.value == "Apple") {
df.options[df.options.length] = new Option("ALL","");
for(i=1;i<=disp.value;i++)
{
var option = document.createElement("option");
option.text=i;
option.value=i;
df.add(option, df.options[null]);
}
}
Add something like the following at the end of the code:
<c:if test="${!empty param.IDNo}">
for (var i = 0; i < df.options.length; i++) {
if (df.options[i].value == '${param.IDNo}') {
df.selectedIndex = i;
break;
}
}
</c:if>
Use the simple java script function to set selected value of combo or drop down box in the other page
function setSelected()
{
var Num = "<%=NumID%>";
if(Num != null && Num !='' )
{
var secondCombo = document.getElementById("combo_id");
secondCombo.value = Num;
}
}

Setting One Drop Down after Selecting from Another

I have a couple select elements:
<select name="empID" onchange='setSupervisor(this);'>
<option value="111" sid="222">Eric Employee</option>
...
</select>
<select name="supervisorID">
<option value="333">Susie Supervisor</option>
<option value="222">Stan Supervisor</option>
</select>
And a javascript function:
function setSupervisor(sender)
{
??
}
How can I set the supervisor dropdown after the user selects from the employee dropdown? The tricky part here (at least to me) is having to use a custom sid and not the value from the employee dropdown.
function setSupervisor(sender) {
var selectedOption = sender.getElementsByTagName("option")[sender.selectedIndex];
var sid = selectedOption.getAttribute("sid");
var supervisorSelect = document.getElementsByName("supervisorID")[0];
for (var i = 0, len = supervisorSelect.options.length, option; i < len; ++i) {
option = supervisorSelect.options[i];
if (option.value == sid) {
option.selected = true;
return;
}
}
}
Try this:
var empID = document.getElementsByName("empID").item(0);
var supervisorID = document.getElementsByName("supervisorID").item(0); //This becomes a bit easier if you set an ID as well as a name in your HTML
var index = empID.selectedIndex;
var sid = empID.options[index].getAttribute("sid");
for(var i=0; i<supervisorID.options.length; i++)
{
if(supervisorID.options[i].value == sid)
{
supervisorID.selectedIndex = i;
break;
}
}

Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)?

I have multiple selects:
<select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.
Here's the JS I have currently:
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled attribute on the option I want to remove, but that doesn't work with IE6.
I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change.
Here's the final code that I ended up using, the flag (changeOnce) worked great, thanks #Jason.
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
var changeOnce = false;
$one.change(function () {
if (changeOnce) return;
changeOnce = true;
var selectedValue = $("option:selected", this).val();
filterSelect(selectedValue, $two, 1);
changeOnce = false;
});
$two.change(function () {
if (changeOnce) return;
changeOnce = true;
var selectedValue = $("option:selected", this).val();
filterSelect(selectedValue, $one, 0);
changeOnce = false;
});
function filterSelect(selectedValue, $selectToFilter, selectIndex) {
for (var i = 0; i < selectOptions[selectIndex].length; i++) {
var exists = false;
for (var x = 0; x < $selectToFilter[0].options.length; x++) {
if ($selectToFilter[0].options[x].value == selectOptions[selectIndex][i].value)
exists = true;
}
if (!exists)
$selectToFilter.append(selectOptions[selectIndex][i]);
}
$("option[value='" + selectedValue + "']", $selectToFilter).remove();
sortSelect($selectToFilter[0]);
}
function sortSelect(selectToSort) {
var arrOptions = [];
for (var i = 0; i < selectToSort.options.length; i++) {
arrOptions[i] = [];
arrOptions[i][0] = selectToSort.options[i].value;
arrOptions[i][1] = selectToSort.options[i].text;
arrOptions[i][2] = selectToSort.options[i].selected;
}
arrOptions.sort();
for (var i = 0; i < selectToSort.options.length; i++) {
selectToSort.options[i].value = arrOptions[i][0];
selectToSort.options[i].text = arrOptions[i][1];
selectToSort.options[i].selected = arrOptions[i][2];
}
}
});
Or you can just hide the option you don't want to show...
function hideSelected($one, $two)
{
$one.bind('change', function()
{
var val = $one.val();
$two.find('option:not(:visible)').show().end()
.find('option[value='+val+']').hide().end();
})
}
hideSelected($one, $two);
hideSelected($two, $one);
EDIT: Oh sorry, this code does not work with IE6...

Categories