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);
});
Related
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.
I have a piece of Javascript code that assigns string of values to a string array.
Unfortunately if I try to add more than one string to the array, my UI simulator(which runs on JS code) closes unexpectedly. I have tried debugging but I cannot find anything. I am attaching that piece of code where the issue is. may be you guys could find some flaw? On the pop up button click the values I selcted on the UI should get stored in the array and I have a corressponding variable on the server side to handle this string array.
_popupButtonClick: function (button) {
var solutions = this._stateModel.get('solutionName');
var i;
var solutionsLength = solutions.length;
var selectedSolution = [solutionsLength];
this.clearPopupTimer();
if (button.position === StatusViewModel.ResponseType.Ok) {
for(i=0;i<solutionsLength;i++)
{
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
this._stateModel.save({
selectedsolutions: selectedSolution,
viewResponse: StatusViewModel.ResponseType.Ok
});
} else {
this._stateModel.save({
viewResponse: StatusViewModel.ResponseType.Cancel
});
}
}
Change
var selectedSolution = [solutionsLength];
to
var selectedSolution = [];
This makes your array have an extra item that might be causing a crash.
Also,
you have an
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
But no corresponding else, so your array has undefined values for i which are not entering the if.
Maybe adding an empty string might solve it:
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
else
{
selectedSolution[i] = "";
}
The code is looking fine but there seems to be a piece of code which can cause error. For example, you are assigning var selectedSolution = [solutionsLength]; and for example solutionsLength is 5 then your loop runs for 5 times
for(i=0;i<solutionsLength;i++) // runs for 5 times
{
if(this._list.listItems[i].selected)
{
// but selectedSolution = [5]; which is on 0th index and from 1st to 4th index it is undefined
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
So you can try to use push() like
selectedSolution.push(this._list.listItems[i].options.value);
and on initialization change it like,
var selectedSolution = [];
Hopefully this will solve your problem.
var selectedSolution = [solutionsLength];
keeps the value in the selectedSolution variable.
var selectedSolution = [3];
selectedSolution[0] gives the values as 3
So make it simple
var selectedSolution = [];
DISCLAIMER: I know how to do it when it's JSON, I need to know how to do it as being a STRING
I'm trying to get "ID":s and "children":, I kind of can get both but not in sequence. For now I can only get "ID":s or "children":s not both, how can I do it, any help is appreciated?
What I'm getting:
1,3,2
What I'd like to get
1,children,3,2
What I'm asking, basically, is to do these two in one (well, in a way that it will bring them in sequence).
var t1 = data.match(/"id":[0-9]+(,|})*/g);
var t2 = data.match(/"children":/g);
My code is right below:
var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child1","id":2}]}]';
var arrays = [];
var t1 = data.match(/"id":[0-9]+(,|})*/g);
//arrays = t1;
for (var x = 0; x < t1.length; x++) {
arrays.push(t1[x].match(/\d+/));
}
//var t2=data.match(/"children":/g);
alert(arrays /*+"\n\n\n\n\n"+t2*/ );
"Live long and prosper"
Thanks in advance.
I am using jQuery. I presume you use it because of the tag you created.
DEMO
var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child1","id":2}]}]';
var arrays = [];
//convert you string to object
//or you can simply change your first row.
data = $.parseJSON(data);
//function to loop the array
function listNodes(inputVal){
if(jQuery.isArray( inputVal )){
$.each(inputVal, function(i,elem){
arrays.push(elem.id);
console.log(elem);
if(jQuery.isArray( elem.children )){
arrays.push('children');
listNodes(elem.children);
}
})
}
}
listNodes(data);
alert(arrays /*+"\n\n\n\n\n"+t2*/ );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I have a question about my JavaScript (vanilla JS, no library answers please).
setup
I have two .txt files, names and data.
names contains a list of 100 last names, one name per line, ie:
Nader
Sanford
Kovacek
Lynch
etc...
data contains a much longer list, of first names, last names, a comma and a value, ie:
Kailee Huel,2
Arianna Runolfsson,4
Marshall Kuhn,3
Cristina Huel,4
Garnett Medhurst,3
etc...
task
Iterate through data.txt using the last names in names.txt. If any of the last names from names.txt have a match in data.txt, increment a counter with the value on that line (after the comma). Some last names are repeated in both names.txt and data.txt.
problem I am encountering:
I have been given that my sample data set must return a value of 443, however the result I am getting is 500. this tells me I am making a blunder with my processing somewhere in my code below.
my code:
// doc rdy
document.onreadystatechange = function(){
if( document.readyState == "complete" ){
init();
}
}
// setup
function init(){
var base = "data/sample/",
namesFile = base+"names.txt",
dataFile = base+"data.txt";
loadFile(namesFile, function(e){
names = e;
loadFile(dataFile, function(ev){
processData(ev);
});
});
}
function processData(e){
var counter = 0;
// for each last name,
for( var i=0; i<names.length; i++ ){
// if "data object" contains "this name", add its val to counter
if( e.hasOwnProperty(names[i]) ){
// console.log( 'match: ' + names[i] );
counter += e[names[i]];
}
}
// The Final Output:
console.log(counter);
}
// ajax loading
function loadFile( filename, callback ){
var client = new XMLHttpRequest();
var result;
client.open('GET', filename);
client.onreadystatechange = function() {
if( client.readyState==4 && client.status==200 ){
result = client.responseText.split("\n");
// custom handling for the data set..
if( result[0].search(',') !== -1 ){
result = arrCSVtoObj(result);
}
callback(result);
}
}
client.send();
}
// converts an array of CSV to a key:value object
function arrCSVtoObj(csvArr) {
var obj = {};
// for each line in the array,
for( var i=0; i<csvArr.length; i++ ){
// split into key:value on comma
var split = csvArr[i].split(",");
var key = getLastName(split[0]);
var val = parseInt(split[1]);
// assign the new property to the object
if( ! obj.hasOwnProperty(key) ){
obj[key] = val;
}else{
obj[key] += val;
}
}
return obj;
}
function getLastName(e){
var nameArr = e.split(" ");
return nameArr[1];
}
question:
What in the above code could be causing my result to return higher than anticipated?
========
EDIT:
Here is the sample data I am using. It is returning a value of "500" when it should be returning a value of "443".
names.txt
data.txt
If a name appears in names.txt multiple times, you're adding it to the counter each time. If you don't want to do that, you need to keep track of which names you've already processed, and skip them when they occur again:
var namesProcessed = {};
function processData(e){
var counter = 0;
// for each last name,
for( var i=0; i<names.length; i++ ){
// if "data object" contains "this name", add its val to counter
if( e.hasOwnProperty(names[i]) && !namesProcessed.hasOwnProperty(names[i]) ){
// console.log( 'match: ' + names[i] );
counter += e[names[i]];
namesProcessed[names[i]] = true;
}
}
// The Final Output:
console.log(counter);
}
If you're using a library like jQuery or Underscore.js, they provide functions to get the unique elements of a list: $.unique() and _.uniq(). Use this on the names array before iterating.
i have a url
http://www.example.com/
and i want to pass an array to $.bbq.pushState
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
how can i pass this array by $.bbq.pushState
please help ........................
try this js code..
obj ={}
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
for(i=0;i<myCars.length;i++){
obj.newcars.push(myCars[i]);
}
I've come across this problem and quickly used the two functions as a way to add and remove information to the fragment in the form of an array.
function AddItemToFragment(newItem) {
var items = $.bbq.getState("itemArray");
if (!items)
items = new Array();
items.push(newItem);
$.bbq.pushState({itemArrray: items});
}
function RemoveItemFromFragment(itemToRemove) {
var items = $.bbq.getState("itemArray");
for (var i = items.length - 1; i >= 0; i--) {
if (items[i] === itemToRemove)
items.splice(i, 1);
}
$.bbq.pushState(items);
}
I'm not quite happy on how these functions work, there must be a nicer way than creating an array object and rewriting the string. I'll have another look at this later and if I come to anything I'll post it up here.
This is how I did in BBQ v1.2.1, and it worked fine for me.
Pushing the state:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
$.bbq.pushState({ 'myCars': myCars });
Getting the state in the hashchange event:
$(window).on('hashchange', function (e) {
var myCars2 = e.getState('myCars');
}
var checkedBoxes = {}; // new object outside of function
function toggleLayer(layer) { // layer is your key variable
var val = $('#'+layer).prop('checked'); // val is the value variable
checkedBoxes[layer] = val; // add pairs to the object
$.each( checkedBoxes, function( key, value ) { // foreach
$.bbq.pushState(checkedBoxes); // create a new parameter for each key value
});
}