Javascript filtering variables - javascript

This code uses ISBN's to search query Amazon such as "128584632X". It doesnt work with spaced isbn's so I need to have them filtered with spaces removed such as with "12 858 463 2X". I need "var items" to be filtered of spaces.
JSFiddle here: https://jsfiddle.net/jfjd8a3h/
//the input box.
var input = document.getElementById('numbers');
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.replace(/\r?\n/g, ' ').split(' ');
length = items.length;
console.log('your collection', items);
for (var i = 0; i < length; i++) {
if ( items[i] && !isNaN(items[i]) ) {
console.log('opening page for isbn ', items[i])
openPage(items[i]);
}
}
}
//opens the tab for one isbn number
function openPage (isbn) {
var base = 'https://www.amazon.ca/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
window.open(base + isbn)
}
<h1>Amazon Bulk ISBN Search</h1>
<p>... note, after paste you may need to click outside the text area or tab out to fire the change event.</p>
<textarea id=numbers placeholder="paste isbn numbers as csv here">
</textarea>

I think that what you want is this:
var items = input.value.replace(/\r?\n/g, '!').replace(/\s/g, '').split('!')
I had to use ! as a replace for newline first because it seems that \s is striping the newlines too.
Well, at least this should get you started.
Another way may be first using split on newlines, then running the replace on each item in the collection. Would be more readable I guess.
EDIT: This condition is preventing the code that opens the page to run, becase the ISBN ends in X,so it is not a number: && !isNaN(items[i])
https://jsfiddle.net/jfjd8a3h/1/

Related

js loses chars if typed too quickly

OK, I got this completed and working and I've removed mention of some of the issues I had to assist with easy reading.
I am obfuscating the characters entered to a text box (id='user_pin_code') such that they appear to be ' * ' or ' **** ' according to the number of chars.
It's for the entry of a PIN code.
The first part takes the chars entered and replaces each with an ' * ' asterisk. So a 6 char PIN will show ' ****** '
All good so far, regardless of how quickly I type.
The next part takes the actual chars entered and populates another textbox (id='PINcode'), with the actual characters entered.
Trouble is, if I type quickly some are missed out.
so 'wxymdo' can be entered as 'wxmd'.
<script>
$(document).ready(function(e) {
var actualTextEntered = "";
$("#user_pin_code").keyup(function(e) {
var x = document.getElementById("user_pin_code").value;
actualTextEntered += x.replace(/\\*/g,"");
addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if ( key === "Backspace" ) {
// Do something
actualTextEntered = '';
x='';
}
});
document.getElementById("user_pin_code").value = "";
for (var i=0;i<actualTextEntered.length;i++)
{
document.getElementById("user_pin_code").value += "*";
document.getElementById("PINcode").value = actualTextEntered;
}
});
});
The problem is just how the keyup event works, it tends not to be able capture some very fast inputs. Just the way onmousemove works, when the mouse moves very fast, some element will be skipped.
Why not use input type="password" or I think using oninput event can be a work around for you.

How do I display a single new word of a paragraph at a time, moving by keypress or mouseclick?

Say I have something like this:
<p>Here are several words in a sentence.</p>
I'm trying to figure out how to display each word, one by one, via keypress or mouseclick, till it reaches the end.
So for example:
Here (click)
Here are (click)
Here are several , etc.
This may be basic, but I'm not very good and I'd love some help!
Thanks!
I just want to make some interventions on #Dean.DePue answer and make the code so you paste it in your project and does the trick:
Your html should look like this:
<div id="adiv"></div>
And you should add this javascript code too:
var index, newsentence, sentence, words;
sentence = "Here are several words in a sentence";
words = sentence.split(" ");
index = 0;
newsentence = "";
$(document).click(function(e) {
if (e.button === 0 && index < words.length) {
newsentence += words[index];
newsentence += " ";
$("#adiv").html(newsentence);
index = index + 1;
}
});
If you've got any doubt of the code just ask!
This has been turned into a jQuery Plugin: word-reveal.
While the other two answers will work (sort of), they aren't very reusable. What happens when you have more than one container you'd like to reveal with more than one sentence? I created a jQuery plugin that can easily be reused throughout the page.
The Setup
Include jQuery on the page
Download the plugin from GitHub, and include it on the page
You're set and ready to go!
The HTML
Set an id for each div or p tag. An example of multiple uses:
<p id="firstRevealer"></p>
<p id="secondRevealer"></p>
<p id="thirdRevealer"></p>
The jQuery
$(document).ready(function() {
$("#firstRevealer").wordReveal({text:"This reveals one word at a time."});
$("#secondRevealer").wordReveal({text:"Adding more text is easy!"});
$("#thirdRevealer").wordReveal({text:"It <b>also</b> works on <em>some</em> tags, since it splits on <b>spaces</b>!"});
});
The CSS
I added CSS on the example, to make clear where you're clicking to reveal the next word. A different answer registered clicks on the document, but any clicks (for a expandable menu, for example) would add a word.
p {
padding: 10px;
margin:10px;
min-height:25px;
background-color:#BADA55
}
The fiddle.
Note
This can easily be extended to act on other events (keypress).
<script type="text/javascript">
var sentence = "Here are several words in a sentence";
var words = sentence.split(" ");
var index = 0;
var newsentence = "";
function clickit() {
newsentence += sentence[index];
index = index + 1;
}

How to keep textarea text static when adding new text

I have a <textarea> that has text added to it based on some javascript. It all works great. The only problem is, when the text is added, it replaces what was already there. Not sure how to stop this from happening, and make it just add to what is in there already.
js:
function addNote0(text, element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('.note').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('','tabText');
};
textarea that is being added to:
<textarea rows="6" cols="24" id="tabText" name="text">--
--
--
--
--
--</textarea>
So every time I click on a <td> it replaces the current "--" that is in there. I want it to just add to that. Any thoughts?
here is a jsFiddle of it. You will see what I mean when you click on the Xs
Instead of just putting in new content, grab the old content and concatenate it with your new content, then put that inside your textarea.
The easiest way to do this would be to just initialize your tabTextRows array in the beginning to:
var tabTextRows = ['--', '--', '--', '--', '--', '--'];
jsFiddle

Run Function Every Time a Value is Entered or Deleted from a Textarea to Instantly Find Sum

I wrote a simple JavaScript that solves addition problems (1 + 1 OR 1 + 5 + 2 + 9, etc.). It works fine.
The problem is I want it to continuously run as new values are entered. As soon as I type "1 + 1" it should display 2, if I continue to type and type "+ 1" it should display 3 and so on.
The continuously running part works somewhat. If I enter "1 + 1" the sum is not displayed until I press the spacebar --- but it should immediately display 2 without having to press the spacebar. What am I missing?
Fiddle: http://jsfiddle.net/z26eg/
HTML
<textarea cols="50" rows="10" id="addThis"></textarea>
<div id="sum"></div>
JavaScript
var input = document.getElementById("addThis");
input.onkeypress = function() {
var finalAnswer = 0;
// Get form input
var processAddThis = addThis.value;
// Remove all spaces in problem
// Example problem: 10 + 3 + 2
processAddThis = processAddThis.replace(/\s/g,''); // 10+3+2
// Split numbers into an array
var addTheseValues = processAddThis.split("+");
// Go through numbers and add them up
for (var i = 0; i < addTheseValues.length; i++) {
finalAnswer += Number(addTheseValues[i]);
}
// Display sum
sum.innerHTML = finalAnswer;
}
You should use on keyup instead :
http://jsfiddle.net/z26eg/1/
input.onkeyup = function() {
.....
};
You should call the function onkeyup like the below:
input.onkeyup = function() {
/* The rest of your current code as it already works fine */
};
The keydown event occurs when the key is pressed, followed immediately by the keypress event. During both these times, the value of the key that has been pressed is still not available for calculation.
Then the keyup event is generated when the key is released. At this point of time, the value of the key that has been pressed is available for calculation.
In this fiddle, input any value in the textarea and have a look at the console to see the difference between the three events.
Try the 'onkeyup' event. It works for me.

Getting the last entered word from a contentEditable div

I have a div tag with contenteditable set to true.
I am trying to find out the last entered word in the div.
For example, if I type in This is a test and I hit a space, I want to be able to get the word test
I want to be able to use this logic so that I can test each word being typed (after the space is pressed).
It would be great if someone could help me with this.
An easy solution would be the following
var str = "This is a test "; // Content of the div
var lastWord = str.substr(str.trim().lastIndexOf(" ")+1);
trim might need a shim for older browsers. (.replace(/\s$/,""))
To strip punctuation like " Test!!! " you could additionally do a replace like following:
lastWord.replace(/[\W]/g,"");
You might want to do a more specific definition of the characters to omit than \W, depending on your needs.
If you want to trigger your eventhandler also on punctuation characters and not only on space, the last replace is not needed.
You first have to know when the content is edited. Using jQuery, that can be done with
​$("div").on("keyup", function(){ /* code */ });
Then, you'll have to get the whole text and split it into words
var words = $(this).text().trim().split(' ');
And getting the last word is as complicated as getting the last element of the words array.
Here's the whole code
HTML
​<div contenteditable="true">Add text here</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
JavaScript (using jQuery)
​
$("div").on("keyup", function(){
var words = $(this).text().trim().split(' '),
lastWord = words[words.length - 1];
console.log(lastWord);
});​​​​​​​
Demo
This is the ultimate way:
// listen to changes (do it any way you want...)
document.querySelectorAll('div')[0].addEventListener('input', function(e) {
console.log( getLastWord(this.textContent) );
}, false);
function getLastWord(str){
// strip punctuations
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\_`~()]/g,' ');
// get the last word
return str.trim().split(' ').reverse()[0];
}
DEMO PAGE
You can try this to get last word from a editable div.
HTML
<div id='edit' contenteditable='true' onkeypress="getLastWord(event,this)">
</div>
JS
function getLastWord(event,element){
var keyPressed = event.which;
if(keyPressed == 32){ //Hits Space
var val = element.innerText.trim();
val = val.replace(/(\r\n|\n|\r)/gm," ");
var idx = val.lastIndexOf(' ');
var lastWord = val.substring(idx+1);
console.log("Last Word " + lastWord);
}
}
Try this link http://jsfiddle.net/vV2mN/18/

Categories