js reset the variable on change in select-option menu - javascript

i have 2 arrays of data form php and using a select-option menu to get the current key for both arrays.
When the key is chosen from a select menu, i use the key to display this key data for both arrays. If the second array doesnt have the key, it should display nothing.
It works fine when both arrays have identical keys.
But when the 2nd array doesnt have the key, it shows the previous data instead of nothing.
php array is similar to:
$arrays['first']['*random_keys*'] = *random data*;
$arrays['second']['*random_keys*'] = *random data*;
$arrays['keys']['first'] = *list of keys*;
the code:
<select id="selector" name="selected_key" onchange="showContent();">
</select>
<div id="show_selected_option"></div>
<div id="showFirstArrayData"></div>
<div id="showSecondArrayData"></div>
<script>
//both arrays in 1 from php
const arrays = <?php echo json_encode($arrays); ?>;
//keys of first array
const keys_kaunt = <?php echo json_encode(count($arrays['keys']['first'])); ?>;
var text = '<option></option>';
for(var i=0;i<keys_kaunt;i++)
{
text += '<option>' + arrays['keys']['first'][i] + '</option>';
}
//show all options in select
document.getElementById("selector").innerHTML = text;
//show data
function showContent(){
var e = document.getElementById("selector");
var f = e.options[e.selectedIndex].value;
document.getElementById("show_selected_option").value = f;
//first array data
var firstArrayKeys = arrays['first'][f];
var firstKeysOutput= '';
Object.keys(firstArrayKeys).forEach(function (key){
firstKeysOutput += key + arrays['first'][f][key];
});
document.getElementById("showFirstArrayData").innerHTML = firstKeysOutput;
//second array data
var secondArrayKeys = arrays['second'][f];
var secondKeysOutput= '';
Object.keys(secondArrayKeys ).forEach(function (key){
secondKeysOutput += key + arrays['second'][f][key];
});
document.getElementById("showSecondArrayData").innerHTML = secondKeysOutput;
}
</script>
The quastion is how to reset the variable 'f' on changed selector. So it doesnt show the previously selected data if the 2nd array doesnt have the selected key.
thanks, works now. the problem was in generated innerHTML not going away, not in the variable.

If I understand your problem correctly, then you maybe need an if statement.
It sounds like you want to empty the input with id="showSecondArrayData" when arrays['second'] does not contain the key f.
function showContent(){
var e = document.getElementById("selector");
var f = e.options[e.selectedIndex].value;
document.getElementById("show_selected_option").value = f;
// FIRST ARRAY code
//
//second array data
if (f in arrays['second']){
var secondArrayKeys = arrays['second'][f];
var secondKeysOutput= '';
Object.keys(secondArrayKeys ).forEach(function (key){
secondKeysOutput += key + arrays['second'][f][key];
});
document.getElementById("showSecondArrayData").innerHTML = secondKeysOutput;
} else {
document.getElementById("showSecondArrayData").innerHTML = '';
}
}
I'm not an expert in js, so please forgive any mistakes or not keeping with js coding standards.

function showContent(){
document.getElementById("showSecondArrayData").innerHTML = '';
var e = document.getElementById("selector");
var f = e.options[e.selectedIndex].value;
document.getElementById("show_selected_option").value = f;
}
did the trick, ty for the help.

Related

Find specific line in CSV based on 2 values with Javascript

I am trying to search, find and fetch some data from a CSV file using HTML/PHP/Javascript.
I want to make a form with 2 dropdowns, one for the FROM Zone name and one for the TO Zone name, and use the Zone codes (102, 104, 105 etc) as values for the dropdown items.
After the user have selected the FROM and TO i want to display the single digit to the far right (col 5).
Example: User choose "Zone1" to "Zone4", then the number "4" should be returned.
FromZoneCode;FromZoneName;ToZoneCode;ToZoneName;Distance;;;;
101;zone1;101;zone1;1;;;;
101;zone1;104;zone4;4;;;;
101;zone1;105;zone5;5;;;;
104;zone4;101;zone1;4;;;;
104;zone4;105;zone5;2;;;;
104;zone4;104;zone4;1;;;;
I have tried to search for a solution for this but i cant seem to find the right info.
Worked out after a long time:
Don't know how you got the CSV data. In the following example, I got it by an ajax request.
No jQuery needed.
Created the dropdowns dynamically.
Set the variable delimeter to ; (or) , as required, because most CSV files contains CSV delimeter.
Give the names of the columns for which dropdowns to be created in the variables dropdownname1 and dropdownname2.
Give the name of the column to be displayed as result on chaning dropdowns in the variable resultname.
Create a <span> element with id="result" in the HTML to display the result.
Variable keys contains column names.
Variable values contains array of arrays as values.
var data = [];
$.ajax({
url:"/Users/Default/Downloads/test.csv",
type:"GET",
datatype:"csv",
success:function(response){
data = response.split(/\r\n/);
start();
}
});
//Logic starts here
//Initializations
var keys = [], values = [], delimiter = ";";
var dropdownname1 = "FromZoneName", dropdownname2 = "ToZoneName", resultname = "Distance";
var resultelem = document.getElementById("result");
//Functionalities
function createDropdown(field)
{
function createOption(option, isselected)
{
var optionelem = document.createElement("option");
optionelem.value=option;
optionelem.text=option;
optionelem.selected = isselected;
return optionelem;
}
var selectelem = document.createElement("select");
selectelem.setAttribute("id",field);
var insertedoptions = [];
for(var i=0;i<values.length;i++)
{
var option = values[i][keys.indexOf(field)];
if(insertedoptions.indexOf(option) == -1)
{
insertedoptions.push(option);
selectelem.appendChild(createOption(option));
}
}
selectelem.appendChild(createOption("",true));
return selectelem;
}
function start()
{
keys = data.splice(0,1)[0].split(delimiter);
values = [];
for(var i=0,n=data.length;i<n;i++)
{
values.push(data[i].split(delimiter));
}
var bodyelem = document.getElementsByTagName("body")[0];
bodyelem.appendChild(createDropdown(dropdownname1));
bodyelem.appendChild(createDropdown(dropdownname2));
document.getElementById(dropdownname1).addEventListener("change",displayData);
document.getElementById(dropdownname2).addEventListener("change",displayData);
}
function displayData()
{
var selectelem1 = document.getElementById(dropdownname1), selectelem2 = document.getElementById(dropdownname2);
var selectedvalue1 = selectelem1.value, selectedvalue2 = selectelem2.value;
for(var i=0,n=values.length;i<n;i++)
{
if(values[i][keys.indexOf(dropdownname1)] == selectedvalue1 && values[i][keys.indexOf(dropdownname2)] == selectedvalue2)
{
resultelem.innerHTML=values[i][keys.indexOf(resultname)];
break;
}
else
{
resultelem.innerHTML="";
}
}
}

Push an object to array, obejct overwritting the previos one

I am trying to push the object resultOBJ to the array resultArray
when the button "Добавить обозначение" is clicked.
first object has been sent well, the data is the same what I am looking for, but when I push another object the second object is rewriting the previous one, the third object is rewriting the first and the second and so on.
here is my code. Please, tell me what I am doing wrong.
Thanks in advance.
var color = {red:"#ff0000",purple:"#990099",green:"#33cc33",yellow:"#ffff00",blue:"#0000ff",orange:"#ff8000",pink:"#ff0080",
skyblue:"#00ffff",black:"#000000",gray:"#808080",brown:"#4d1f00"};
var diams = ["60","65","68","69","70","75","76","80","81","82","85","90"];
//show hidden elements
$(document).ready(function(){
$("#addRowDDL").click(function(){
$("#DDL,#deleteRowDDl,#useIt").fadeIn("slow");
});
});
var resultOBJ=new Object();
var resultArray = new Array();
var finalobj = {} ;
var obj = new Object();
function addDropDownLists(){
var myObject = $("#htmltoget").children().clone();
$("#DDL").append(myObject);
$.each(diams,function(key,value){
myObject.find(".chooseDiams").append($("<option></option>").attr("value",key)
.text(value));
});
$.each(color,function(key,value){
myObject.find(".chooseColor").append($("<option></option>").attr("value",key)
.text(key));
});
myObject.find(".chooseColor").change(function(){
displayColors(this);
});
myObject.find(".chooseDiams").change(function(){
displayDiams(this);
});
resultArray.push(obj);
}//End of addDropDownLists function
function displayColors(param){
var colorValues = $(param).val();
resultOBJ.color=colorValues;
}
function displayDiams(param){
var diamsValues = $(param).val() || [];
resultOBJ.diams=diamsValues;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="htmltoget" style="display: none;">
<div class="DDL-Con">
<div class="diams">
<p>Диаметр</p>
<select class="chooseDiams" multiple>
<option selected hidden> Выбрать Диаметр</option>
</select>
</div>
<div class="color">
<p>Цвет</p>
<select class="chooseColor">
<option selected hidden>Выбрать Цвет</option>
</select>
</div>
</div>
</div>
<button type="button" id="addRowDDL" onclick="addDropDownLists()" style="margin-bottom: 20px;">Добавить обозначение</button>
<div id="bigwrapper">
<div id="DDL">
</div>
</div>
</body>
Having a hard time telling what you're trying to accomplish but you push obj which is empty and should be giving you an array of empty objects.
Also, you need to create a new object for each call of addDropDownLists() otherwise you are just passing a reference and the changes will effect every object in the array.
//show hidden elements
$(document).ready(function(){
$("#addRowDDL").click(function(){
$("#DDL,#deleteRowDDl,#useIt").fadeIn("slow");
addDropDownLists();
});
});
var resultArray = new Array();
function addDropDownLists(){
var resultOBJ=new Object();
var myObject = $("#htmltoget").children().clone();
$("#DDL").append(myObject);
$.each(diams,function(key,value){
myObject.find(".chooseDiams").append($("<option></option>").attr("value",key)
.text(value));
});
$.each(color,function(key,value){
myObject.find(".chooseColor").append($("<option></option>").attr("value",key)
.text(key));
});
myObject.find(".chooseColor").change(function(){
resultOBJ.color = $(this).val();
});
myObject.find(".chooseDiams").change(function(){
resultOBJ.diams = $(this).val() || [];
});
resultArray.push(resultOBJ);
console.log(JSON.stringify(resultArray));
}//End of addDropDownLists function
This setup does insert an empty object into the array the first time the button is clicked, or if there is no change. Not sure what you're trying to accomplish though so I left it as is.
Demo: https://jsfiddle.net/3p37znq1/2/
You don't push resultOBJ, you push obj which is always empty as you don't do anything with it after initialization.
When you push obj each time you just push a reference to the same instance instead of creating a new one. Any change to obj will affect all items in resultArray.
In change handler you always update the same instance of resultOBJ and this update always overwrites previous change. Actually, the values in this object mean "last selected color anywhere" and "last selected diam anywhere".
Something like this should work:
var resultArray = [];
function renderOption(value, name) {
var option = document.createElement("option");
option.value = value;
option.innerHTML = undefined === name ? value : name;
return option;
}
function updateResult(index) {
var item = resultArray[index],
node = document.querySelector("#DDL").childNodes.item(index);
item.diam = node.querySelector(".chooseDiams").value;
item.color = node.querySelector(".chooseColor").value;
}
function addDropDownLists() {
var container = document.querySelector("#DDL"),
index = resultArray.length,
changeHandler = updateResult.bind(null, index),
tpl = document.querySelector(".DDL-Con"),
node = tpl.cloneNode(true),
list, key, len
;
list = node.querySelector(".chooseDiams");
for (key = 0, len = diams.length; key < len; key++) {
list.appendChild(renderOption(diams[key]));
}
list.onchange = changeHandler;
list = node.querySelector(".chooseColor");
for (key in color) {
list.appendChild(renderOption(key, color[key]));
}
list.onchange = changeHandler;
container.appendChild(node);
resultArray.push({
diam: null,
color: null
});
updateResult(index);
}
PS: Sorry, I see you use jQuery... I'm too lazy to remember it's API. Haven't used it for a long time. Hope, you'll catch the main idea.
PPS: if you plan to delete items, maybe it's better to bind the whole node and search for it's index via isSameNode() method. Bound indexes will become invalid after removing item, they will shift.

javascript variable assignment

Utterly stumped as to why the below javascript doesnt assign the variables as expected
Maybe I am missing something very simple due to staring at it for hours on end !!
Any help appreciated.
Cheers
var $name;
var $district;
var $distance;
var myArray = [];
jQuery('.getrowdata').on('click', function(){
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
var value;
jQuery.each($columns, function(i, item){
value = item.innerHTML;
if(i < 3){
myArray.push(value); // adds first 3 elements to the array
}
}
);
$name = myArray[0]; // trying to set value of these variables to value of array element
$district = myArray[1];
$distance = myArray[2];
alert(myArray.join(", ")); // this works - displays data as expected !!
});
document.write($name); // these don't work - print out as undefined ?
document.write($district);
document.write($distance);
The variables are undefined as they only have values after the "click" event handler is called.
Try moving your document.write statements into the "click" handler:
jQuery('.getrowdata').on('click', function() {
...
document.write($name);
document.write($district);
document.write($distance);
});

Save and print list with array

I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.

Javascript: How to re-arrange content display of text field?

I have a text field (not a date field) who contain simply a value such "2013-08-27" and my goal would be to reverse the order and get "27-08-2013". So is matter to re-arrange the content but I don't have enough javascript knowledge. I tried using some "date" variable but without success much probably because my field is not a date field.
The html related to the field look like this:
<input type="text" value="2013-08-27" name="my_field" id="my-field" readonly="">
If you can give me an example of code based of this:
var my_field = document.getElementById('my_field');
thank
PS: I precise I don't have access to html of this field because is located to a remote server. I can only interact by adding code in a JS file planned for that. The field have also a "readonly" property because is not planned for be modified.
This code should do the trick:
var revert = function(str) {
var parts = str.split("-");
var newArr = [];
for(var i=parts.length-1; p=parts[i]; i--) {
newArr.push(p);
}
return newArr.join("-");
}
var replaceValueInInputField = function(id) {
var field = document.getElementById(id);
field.value = revert(field.value);
}
var replaceValueInDomNode = function(id) {
var el = document.getElementById(id);
var value = el.innerHTML, newValue = '';
var matches = value.match(/(\d{4})-(\d{2})\-(\d{2})/g);
for(var i=0; m=matches[i]; i++) {
value = value.replace(m, revert(m));
}
el.innerHTML = value;
}
replaceValueInInputField("my-field");
replaceValueInDomNode("my-field2");
jsfiddle http://jsfiddle.net/qtDjF/2/
split('-') will return an array of number strings
reverse() will order array backwards
join("-") will join array back with '-' symbol
var my_field_value = document.getElementById('my_field').value;
my_field_value.split('-').reverse().join("-");
You can use the split function.
var my_field = document.getElementById('my_field').split("-");
the var my_field will be an array of string like : "YYYY,mm,dd"
and then you can re-arrange it in the order you want.
Try this
var date = document.getElementById("my-field").value;
//alert(date);
var sp = date.split("-");
alert(sp[2]+"-"+sp[1]+"-"+sp[0]);
With Jquery
var parts =$('#my-field').val().split("-");
$('#my-field').val(parts[2]+"-"+parts[1]+"-"+parts[0]);
Simple regex:
var res;
test.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/,function(all,a,b,c){res=c+"-"+b+"-"+a;});
JSFiddle: http://jsfiddle.net/dzdA7/8/
You could try splitting the string into array and inverting it's items in a loop:
var my_field = document.getElementById('my_field').value.split("-"),
length = my_field.length,
date = [];
for(i = length - 1; i >= 0; i--){
date.push(my_field[i]);
}
console.log(date.toString().replace(/,/g,"-"));

Categories

Resources