I'm doing this on the jsp page of another application. I need to populate values on combobox based on another combo box. I've seen several posts explaining this but can't make it to work for myself.
Here's what I tried.
<script type="text/javascript">
function customChangefunction(){
var target = window.document.getElementsByName("resultCombo");
var src = window.document.getElementById("sampleCombo");
var strUser = src.options[src.selectedIndex].value;
alert(strUser);
var colours = new Array('Black', 'White', 'Blue');
var shapes = new Array('Square', 'Circle', 'Triangle');
var names = new Array('John', 'David', 'Sarah');
switch (strUser) {
case 'one':
target.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(target, colours[i], colours[i]);
}
break;
case 'two':
target.options.length = 0;
for (i = 0; i < shapes.length; i++) {
createOption(target, shapes[i], shapes[i]);
}
break;
case 'three':
target.options.length = 0;
for (i = 0; i < names.length; i++) {
createOption(target, names[i], names[i]);
}
break;
default:
target.options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement("OPTION");
opt.value = value;
opt.text = text;
ddl.options.add(opt);
opt.appendChild(text);
document.getElementById(ddl).appendChild(opt);
}
The above code is not working.I have to do this without using jquery.
My actual requirement is
if Combo1 is India then Combo2 should show Chennai,Delhi,Mumbai
if Combo1 is USA then Combo2 should show New York,CA,etc..
I have one more question. Suppose that Combo2 is already having some values does this replace those with these values.I would like to do this way
Please comment on this before you mark this question as duplicate or closing it.
document.getElementById("food").onchange = function(Event){
var contents = document.getElementById("contents");
contents.innerHTML = "";
for(var i in data[this.value]){
var option = document.createElement("option");
option.setAttribute('value',data[this.value][i]);
option.text = data[this.value][i];
contents.appendChild(option);
}
var expect_data = Event.target.value == "Fruits" ? "Vegetables" : "Fruits";
for(var i in data[expect_data]){
var option = document.createElement("option");
option.setAttribute('value',data[expect_data][i]);
option.text = data[expect_data][i];
contents.appendChild(option);
}
}
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 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;
}
}
}
}
}
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<select id="selectStock">
<option>Choose a stock</option>
</select>
I have multiple Javascript arrays of data (pulled from Excel) and have different functions that basically make calculations based on the row of the array. For example:
var stocks = [['Apple',100,8998,723,7212]['Microsoft,928,1992,821,2381]]
What I need to do is make a dropdown menu that will allow a user to select an option (Microsoft or Apple) and then based on this selection, will pull this value into the formula to make the calculations
document.write(Math.round(stocks[i][1] * 100)/100 + " dollars per share");
where i is the variable based off dropdown menu selection. Does this make sense? I'm not sure how to approach this, it's for a personal project. Thanks for the help!
https://jsfiddle.net/b22y3v85/
var select = document.getElementById("selectStock");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.write(Math.round(stocks[index][1] * 100)/100 + " dollars per share");
};
Here is a working example, although you'll probably want to do something other than document.write the result.
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
function getPrice(stock) {
var price = false;
for (var a = 0; a < stocks.length; a++) {
if (stocks[a][0] == stock) {
price = stocks[a][1];
break;
}
}
if (!price) { alert("Incorrect choice."); return; }
document.getElementById("result").innerText = stock + " is currently " + (Math.round(price * 100)/100 + " dollars per share");
}
<select id="selectStock" onchange="getPrice(this.value);">
<option>Choose a stock</option>
</select>
<br><br>
<div id="result"></div>
EDIT: Shows result in a div on the page, instead of overwriting the page with document.write().
<select id="selectStock"></select>
<script type="text/javascript">
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.innerHTML = opt;
el.value =stocks[i]+'';
select.appendChild(el);
}
select.addEventListener('change', function(e){
var val = e.currentTarget.value;
val = val.split(',');
val.shift();
callYourMethod(val);
});
</script>
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 have 'button' like this
<span data-id="dr21" data-minheight="100" data-maxheight="200" data-minwidth="20" data-maxwidth="50" class="customsizebutton">(edit size)/span>
and script like this
<script>
$('.customsizebutton').click(function ()
{
var id = $(this).data('id');
var minHeight = $(this).data('minheight');
var maxHeight = $(this).data('maxheight');
var minWidth = $(this).data('minwidth');
var maxWidth = $(this).data('maxwidth');
var arrayH = [];
var arrayW = [];
for (var i = minHeight; i <= maxHeight-1; i++) {
arrayH.push(i);
}
for (var i = minWidth; i <= maxWidth-1; i++) {
arrayW.push(i);
}
var selectListH = document.getElementById("h-"+id);
for (var i = 0; i < arrayH.length; i++) {
var option = document.createElement("option");
option.text = arrayH[i];
selectListH.appendChild(option);
}
var selectListW = document.getElementById("w-"+id);
for (var i = 0; i < arrayW.length; i++) {
var option = document.createElement("option");
option.text = arrayW[i];
selectListW.appendChild(option);
}})
</script>
I am trying to fill the two dropdowns with
<option>200</option>
<option>199</option>...
<option>101</option>
<option>100</option>
<option>50</option>
<option>49</option>...
<option>21</option>
<option>20</option>
It currently fills the dropdowns the opposite direction (low to high). I'm new to this and trial and error has got me this far.
Thanks
Just populate the arrays in reverse order.
for (var i = maxHeight-1; i >= minHeight; i--) {
arrayH.push(i);
}
for (var i = maxWidth-1; i >= minWidth; i--) {
arrayW.push(i);
}
If you merely need to populate your dropdowns in reverse order, you can just iterate them in reverse, like so:
for (var i = arrayH.length - 1; i >= 0; i--) {
var option = document.createElement("option");
option.text = arrayH[i];
selectListH.appendChild(option);
}
If you want to actually reverse the items in the array, as the title of your question denotes, that's even easier, with the Array.reverse function:
arrayH = arrayH.reverse();
If you're new, I recommend reviewing the JavaScript documentation over at Mozilla.