No output when parsing textarea with JavaScript - javascript

I have a text box that will have a large block of text pasted into it.
Then I parse the text into an array, removing whitespace. I need to pull the data out of certain array elements and put them into separate variables so I can generate a cleaner, formatted output.
The problem is that noting appears to be passed into my variables from the array. I've toyed with it a bit, and the array is being filled correctly, but the elements aren't passing strings to the variable.
HTML:
<p>Contact Name: <b id='contactNameOutput'></b></p>
JavaScript:
function generateOutputfvoc() {
var inputArr = document.getElementById('inputBox').value.split(/[\s]/);
document.getElementById('contactNameOutput').innerHTML = inputArr[0];
}

There are quite a few things going on here wich are hard to understand why you've done them.
My asumption is that inputBox is either a textarea or a input field into wich the user writes something.
Okay so you're splitting that string on whitespaces so for example the string
The quick brown fox
would result in a array which looks like this:
inputArr = ["The", "quick", "brown", "fox"]
Now in your for-loop you're iterating over this array, starting at 0 and incrementing till you reach the end of the array, nothing strange here.
But in the first iteration, in the if-clause that you have, you're trying to access the array with negative values, remember i is 0, this results in an undefined value, also in the last part of the if clause you're trying to access i+1 well what happens when i is at its last value?! You guessed it another undefined! Later the loop will access old values which you've allready gone through, and honestly I can't figure out what you're trying to accomplish.
All your if-statements are a mess really, especially if your gonna do them in that loop.
My guess is that you thought that you needed a for-loop for this, when in fact you do not.
What you have is one array containing the words in your textarea, if you know the order of what you're expecting, (can you really know what the user will put in that textarea?), then you can just access the words directly since you'll know the index of each item in the array. Otherwise, rewrite this to something simpler, always try to keep it simple.
Also why not look up refactoring while you're at it?!
edit
I think that the problem you have now is that the first element in the array is an empty string, that happens if there's a space in the beginning of the input.

Related

Filtering REST API call to first result

I have a question that I feel should be pretty simple to answer, but I cannot find fix anywhere.
I'm querying the Uberchord website for guitar chords (documentation here)
Here is the URL I'm querying:
https://api.uberchord.com/v1/chords?nameLike=${variable}
Where variable is based on what the user types in.
The nameLike lets fuzzy match between the input and the API (For example, the url for an Fmaj7 chord is F_maj7). This works great, but it returns multiple responses. The first response is always the one I want, so I'm trying to just limit the responses to the first one that comes in. So far, I've tried adding a limit or a top filter to the URL to no avail. This is where I'm sure I'm doing something incorrect.
For limit, I've tried:
https://api.uberchord.com/v1/chords?nameLike=${fmaj7}?limit=1
and
https://api.uberchord.com/v1/chords?nameLike=${fmaj7}&limit=1
and for top I've done the same two but just replacing limit with top. The first one returns zero responses, while the second returns all responses.
Any ideas?
It isn't literally "returning multiple responses". It's just returning an array. It ALWAYS returns an array, even if there is only one element. If you only want the first element of that array, then fetch the first element of the array, just like you would with any other array. After you do the JSON decode:
chord = response[0];

Extracting entire column of data from a grid not necessarily HTML but an AgGrid into array using JavaScript

Could not find a clear explanation of how to achieve this. Does JS have a straight forward method for taking the entire column from a grid and populating an array with one cell value per array element. I do know the value of each cell. But I want to make an array of all the individual cell values. I am relatively new to JS and thought it might be wiser to ask here than to go on mashing code together seeing no results.
Thank you so much, Luxy
For example,
My cell value is in params.data["Bug Feature"] // which prints each value 0, 13, text, text, 0...
What I want is to make an array of the single values to an array.
I didn't mean to get a full implementation. I just wanted to know the right way. This is what I am doing currently. But it is making each cell value an array which is not what I am looking for.
var sortBUGFeatures = jQuery.makeArray(params.data["Bug Feature"]);
i did it in jQuery but I thought JS would be little simpler for me

jQuery/JavaScript regex return matched text from string

I am trying to create a fairly complex system for my website. I want to be able to write some pseudo like code and then parse it to make it do something in my back-end.
My data is inside two $.each loops as this is an Object of data with multiple levels to it.
For instance, I want to take a string like this:
"<!this!> == <!PropertyStreetNumber!>"
Then how I would like for the above code to executed is this:
FormData[parentKey][this] == FormData[parentKey]["PropertyStreetNumber"]
Thanks for any help!
Here's some of my code, the code where this would need to go in (see commented area)
http://jsbin.com/liquvetapibu/1/
Is there any restriction not to use regular expressions on JavaScript?
You could do something like this:
var myString = "<!this!> == <!PropertyStreetNumber!>";
var aux = /<!(.*?)!> == <!(.*?)!>/.exec(myString);
The value of aux will be an array with 3 elements:
The string that was tested.
The first element within <! !>
The second element within <! !>
Then it would depend on what the content on each one is: in your example this is an object, while you seem to use PropertyStreetNumber as a string (maybe a typo?). If you want to use it as an object, you will have to use eval() (e.g.: eval(aux[1])) while if you want to use it as a string, you can use it directly (e.g.: aux[2]).
Conceptually, the first thing you would need to do is determine the type of statement you are working with. In this case, a comparison statement. So you need a regex statement to filter this into a "statement type".
Once you do that, you can figure out what the arguments are. So you create a regex to pull out the arguments on each side of the operator.
Next, the strings that represent action code items need to be parsed. The this argument is actually an object, whereas "PropertyStreetNumber" is a string. You've got to be able to determine which is which. Then you can filter that into a function that has been created specifically to handle those statements types.
If at all possible, I would try to avoid the use of eval(). You can get into trouble with it.
you could try with
var beg = str.indexOf("== <!") + 5;
to find the index of the beggining and then slice counting the chars from beginning like
str.slice(beg, -2);
and from there build the rest.
couldnt that work?`

How can I call an element from an array created by "document.getElementBytag()"?

I am trying to make a page work for my website using the mootools framework. I have looked everywhere I can think of for answers as to why this isn't working, but have come up empty.
I want to populate several arrays with different data types from the html, and then, by calling elements from each array by index number, dynamically link and control those elements within functions. I was testing the simple snippet of code below in mootools jsfiddle utility. Trying to call an element from array "region" directly returns "undefined" and trying to return the index number of an element returns the null value of "-1".
I cannot get useful data out of this array. I can think of three possible reasons why, but cannot figure out how to identify what is really happening here:
1. Perhaps this array is not being populated with any data at all.
2. Perhaps it is being populated, but I am misunderstanding what sort of data is gotten by "document.getElementBytag()" and therefore, the data cannot be displayed with the "document.writeln()" statement. (Or am I forced to slavishly create all my arrays?)
3. Perhaps the problem is that an array created in this way is not indexed. (Or is there something I could do to index this array?)
html:
<div>Florida Virginia</div>
<div>California Nevada</div>
<div>Ohio Indiana</div>
<div>New York Massachussetts</div>
<div>Oregon Washington</div>
js:
var region = $$('div');
document.writeln(region[2]);
document.writeln(region.indexOf('Ohio Indiana'));
Thanks for helping a js newbie figure out what is going on in the guts of this array.
$$ will return a list of DOM elements. If you are only interested in the text of those DOM nodes, then extract that bit out first. As #Dimitar pointed out in the comments, calling get on an object of Elements will return an array possibly by iterating over each element in the collection and getting the property in question.
var region = $$('div').get('text');
console.log(region[2]); // Ohio Indiana
console.log(region.indexOf('Ohio Indiana')); // 2
Also use, console.log instead of document.writeln or document.write, reason being that calling this function will clear the entire document and replace it with whatever string was passed in.
See an example.

jQuery "Autocomplete" plugin is messing up the order of my data

I'm using Jorn Zaefferer's Autocomplete plugin on a couple of different pages. In both instances, the order of displayed strings is a little bit messed up.
Example 1: array of strings: basically they are in alphabetical order except for General Knowledge which has been pushed to the top:
General Knowledge,Art and Design,Business Studies,Citizenship,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Displayed strings:
General Knowledge,Geography,Art and Design,Business Studies,Citizenship,Design and Technology,English,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Note that Geography has been pushed to be the second item, after General Knowledge. The rest are all fine.
Example 2: array of strings: as above but with Cross-curricular instead of General Knowledge.
Cross-curricular,Art and Design,Business Studies,Citizenship,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Displayed strings:
Cross-curricular,Citizenship,Art and Design,Business Studies,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Here, Citizenship has been pushed to the number 2 position.
I've experimented a little, and it seems like there's a bug saying "put things that start with the same letter as the first item after the first item and leave the rest alone". Kind of mystifying. I've tried a bit of debugging by triggering alerts inside the autocomplete plugin code but everywhere i can see, it's using the correct order. it seems to be just when its rendered out that it goes wrong.
Any ideas anyone?
max
EDIT - reply to Clint
Thanks for pointing me at the relevant bit of code btw. To make diagnosis simpler i changed the array of values to ["carrot", "apple", "cherry"], which autocomplete re-orders to ["carrot", "cherry", "apple"].
Here's the array that it generates for stMatchSets:
stMatchSets = ({'':[#1={value:"carrot", data:["carrot"], result:"carrot"}, #3={value:"apple", data:["apple"], result:"apple"}, #2={value:"cherry", data:["cherry"], result:"cherry"}], c:[#1#, #2#], a:[#3#]})
So, it's collecting the first letters together into a map, which makes sense as a first-pass matching strategy. What i'd like it to do though, is to use the given array of values, rather than the map, when it comes to populating the displayed list. I can't quite get my head around what's going on with the cache inside the guts of the code (i'm not very experienced with javascript).
SOLVED - i fixed this by hacking the javascript in the plugin.
On line 549 (or 565) we return a variable csub which is an object holding the matching data. Before it's returned, I reorder this so that the order matches the original array of value we were given, ie that we used to build the index in the first place, which i had put into another variable:
csub = csub.sort(function(a,b){ return originalData.indexOf(a.value) > originalData.indexOf(b.value); })
hacky but it works. Personally i think that this behaviour (possibly coded more cleanly) should be the default behaviour of the plugin: ie, the order of results should match the original passed array of possible values. That way the user can sort their array alphabetically if they want (which is trivial) to get the results in alphabetical order, or they can preserve their own 'custom' order.
What I did instead of your solution was to add
if (!q && data[q]){return data[q];}
just above
var csub = [];
found in line ~535.
What this does, if I understood correctly, is to fetch the cached data for when the input is empty, specified in line ~472: stMatchSets[""] = []. Assuming that the cached data for when the input is empty are the first data you provided to begin with, then its all good.
I'm not sure about this autocomplete plugin in particular, but are you sure it's not just trying to give you the best match possible? My autocomplete plugin does some heuristics and does reordering of that nature.
Which brings me to my other answer: there are a million jQuery autocomplete plugins out there. If this one doesn't satisfy you, I'm sure there is another that will.
edit:
In fact, I'm completely certain that's what it's doing. Take a look around line 474:
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
/* some code */
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
and so on. So, it's a feature.

Categories