I'd like to use jQuery to echo text as it is typed, into a text area below the input line, and as it does, put random pre-selected words on the end of that repeated data. Each time a new letter is typed as input, I'd like some other "random" word appended each of the 3 "repeats", kind of a jumble.
Input= "true blue"
TextArea =
true blue black<br/>
true blue car<br/>
true blue sock<br/>
If the input = "true blues"
TextArea =
true blues snake<br/>
true blues grass<br/>
true blues red<br/>
All new results because "s" was typed. (or as close to "new/random" as can be easily)
I'm going to have 200 words in an array, and with each key press I'd like the appended words to change (onkeyup?). If they can appear random or can be randomly picked from a larger list/file.
Input from the form is repeated for 3 lines in the text area, and 3 random words are also appended basically. Onkeypress echo input + random_word (x3).
Interesting challenge.
I've played with it for a couple of hours and have come up with a rudimentary, inelegant attempt - brute force.
FIDDLE
JS
var spacecount = 0;
var sumcodes = 0;
var wordarray = 0;
var randword = ['gould','horowitz','bach','scarlatti','handel','vivaldi','corelli','albinoni','allegri','pinnock',];
$(function(){
$(document).keyup(function(e){
var char1 = String.fromCharCode(e.keyCode);
$('#keycode').html(e.keyCode);
$('#charcode').html(char1);
$('#texthere').append(char1);
sumcodes = sumcodes + e.keyCode;
if (e.keyCode == 32)
{
spacecount=spacecount + 1;
$('#spacecount').html(spacecount);
}
if (spacecount > 2)
{
spacecount = 0;
wordarr = Math.floor(Math.random() * 10) + 1
$('#texthere').append(randword[wordarr] + ' ');
$('#sumcodes').html(sumcodes);
sumcodes = 0;
}
});
});
The random number generator is not that robust. I tried to relate it to the sum of the ASCII character codes, but was unsuccessful (I'll play a bit more).
Related
I have been working on a Rubik’s Cube Timer website, and I need to make a scrambling algorithm. I’ll go over how the scrambling algorithm should work:
Each face has it’s own letter, it’s initial. for examble, if you want to move the front face, you would write “ F “. If you want to move the the right face, you would write “ R “, and so on. just note that the bottom face is D, as for down. So you have D U R L B F.
If there is nothing after that letter, you turn it clockwise. If there is an appostrophe “ ‘ “, you turn it counter-clockwise. If there is a 2, you turn it two times. Now the thing is that you cannot have 2 same letters next to oneanother, as they would cancel (For example “.. U U’ ...” would be the same as doing nothing. So far, I have this taken care of in my algorithm.
The problem comes when you have one letter, then it’s opposite, then again the first letter, ( For example “.. U D U’...” (would mean Up clockwise, Down clockwise, Up counterclokwise)).
I have no idea how to check for these and avoid them automatically. Here’s the code:
<div id=“Scramble”></div>
<script>
generateScramble();
function generateScramble() {
// Possible Letters
var array = new Array(" U", " D", " R", " L", " F", " B")
// Possible switches
var switches = ["", "\'", "2"];
var array2 = new Array(); // The Scramble.
var last = ''; // Last used letter
var random = 0;
for (var i = 0; i < 20; i++) {
// the following loop runs until the last one
// letter is another of the new one
do {
random = Math.floor(Math.random() * array.length);
} while (last == array[random])
// assigns the new one as the last one
last = array[random];
// the scramble item is the letter
// with (or without) a switch
var scrambleItem = array[random] + switches[parseInt(Math.random()*switches.length)];
array2.push(scrambleItem); // Get letters in random order in the array.
}
var scramble = "Scramble: ";
// Appends all scramble items to scramble variable
for(i=0; i<20; i++) {
scramble += array2[i];
}
document.getElementById("Scramble").innerHTML = scramble; // Display the scramble
}
</script>
For starters God's Number is 20 for Rubik;s cube so you got only 20 moves instead of 25. I assume you are not doing scrambling (as your title suggest) but instead generate solution command strings for genere&test solver type. There are too many sequences that cancel each other and to check for all of them would be most likely slower than try them out actually.
The problem is that even O(n^20) is huge and you need to lower the 20. That is done by LUT holding semi solved states. For example create table holding states for all combinations of 5 turn scrambling. Then use that as end condition turning your solver into O(n^15 + n^5) = O(n^15) ...
i am trying to put a limit on number of characters in a word. i am successful to find, if someone is entering more then 15 character.i am displaying a message right now. what i want to do is, if some one enter more then 15 characters ... the java script display a alert and then delete all letters leaving first 14 characters in that word. i tried to find some helpful functions but never found something useful.
i want to check for the character limit dynamically when the user is still entering.
my code is half complete but it has one flaw. it is displaying the message when a count is reaching more then 15 it displays a alert. now user can still save that string that has more than 15 char in a word. hope i explained it all.thanks to all,for everyone that is gonna put some effort in advance.
<textarea id="txt" name="area" onclick="checkcharactercount()"></textarea>
function checkcharactercount(){
document.body.addEventListener('keyup', function(e) {
var val = document.getElementById("txt").value;
var string = val.split(" ");
for(i=0;i<string.length; i++) {
len = string[i].length;
if (len >= 15) {
alert('you have exceeded the maximum number of charaters in a word!!!');
break;
}
}
});
}
Does this work like you want it to?
var textArea = document.getElementById('txt');
textArea.addEventListener('keyup', function () {
var val = textArea.value;
var words = val.split(' ');
for (var i = 0; i < words.length; i++) {
if (words[i].length > 14) {
// the word is longer than 14 characters, use only the first 14
words[i] = words[i].slice(0, 14);
}
}
// join the words together again and put them into the text area
textArea.value = words.join(' ');
});
<textarea id="txt" name="area"></textarea>
I have a text area where I add the number of orderlist item on click of a button.This is my code,
var addListItem = function() {
if (!this.addListItem.num) {
this.addListItem.num = 0
}
++this.addListItem.num;
var text = document.getElementById('editor').value;
console.log('text', text);
var exp = '\n' + this.addListItem.num + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
As I have used a static variable to increment it increments on every click and so if I delete the list and create a new list again it doesn't starts from '1' and also I couldn't figure out how to update the numbers when a item is added in between.Could anyone suggest me how to fix this?
If you want a more robust solution that handles all sorts of different cases, you can use regular expressions to detect what number you're at in your list.
This solution also allows users to type in their own numbers and the button click WILL STILL WORK!
That's because this solution uses the text area content as the source of truth and doesn't track state on the side.
var addListItem = function() {
var text = document.getElementById('editor').value;
// regex to match against any new line that has a number and a period
// and extracts the number. feel free to use regex101.com to understand
// this in more depth.
var listNumberRegex = /^[0-9]+(?=\.)/gm;
var existingNums = [];
var num;
// get all the matches
while ((num = listNumberRegex.exec(text)) !== null) {
existingNums.push(num);
}
// sort the values
existingNums.sort();
// use the existing biggest number + 1 or use 1.
var addListItemNum;
if (existingNums.length > 0) {
// get last number and add 1
addListItemNum = parseInt(existingNums[existingNums.length - 1], 10) + 1;
} else {
// otherwise if there's nothing, just use 1.
addListItemNum = 1;
}
var exp = '\n' + addListItemNum + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
understanding regular expressions is tricky, feel free to view https://regex101.com/r/gyX7oO/1 to get a better understanding of what is going on.
You can try something like this:
Logic:
On every click, get the text in textarea and split it be new line.
Now that you have line items, you need to get last sentence that starts with a numeric value. But user can enter new lines on his own to format text.
For this, loop on every line and validate it it starts with number followed by ..
If yes, use substring to fetch this number and parse it to int. If no match is found, you can return 0.
This will ensure the numbering system and you do not need a variable to hold last value.
Note: This logic assumes that last value will be the maximum. If you wish to handle that, you can just compare n and parseInt and assign maximum value
Sample:
var addListItem = function() {
var text = document.getElementById('editor').value;
var exp = '\n' + (getLastNumber(text) + 1) + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
function getLastNumber(str){
var list = str.split(/[\r\n]/g);
var n = 0;
list.forEach(function(s){
if(/^\d+\./.test(s)){
n = parseInt(s.substring(0, s.indexOf(".")));
}
});
return n;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
If you delete the list and create a new list again it will start from '1'.
also, counts from whatever the last number is.
var addListItem = function() {
if (!this.addListItem.num) {
this.addListItem.num = 0
}
++this.addListItem.num;
var text = document.getElementById('editor').value;
//HERE start new counting if textarea is empty
if(text.trim() == ''){
this.addListItem.num = 1; //restart counting here
}
//else check if textarea has previous numbers to proceed counting
else {
var lastLine = text.substr(text.lastIndexOf("\n") + 1).trim();
this.addListItem.num = parseInt(lastLine.slice(0, -1)) + 1; //add 1 to last number
}
console.log('text', text);
var exp = '\n' + this.addListItem.num + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
A list of isbn's are entered in the text area and javascript opens an amazon search for each one entered.
Isbn's can be between 10 or 13 digits.
Not all isbn searches start with an isbn, sometimes there can be information in front such as "isbn10:0195433831" so you cant count from the start.
For Example, this is a typical search:
0195433831 Good
0195433831 Poor
0195433831 Excellent
Question
Often times isbn's are entered in a different format breaking it, for example:
1) With spacing between numbers
978 0 132 76682 1 like new
978 0 495 38500 4 very good
2) With additional rating numbers added creating additional unnecessary
searches.
9781118624616 9/10 condition with minimal highlighting
9780415462020 10/10 condition, brand new
So I must find a way to have Javascript filter out these conditions.
Code is here:
//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.com/gp/search/ref=sr_adv_b/?search-alias=stripbooks&field-isbn='
window.open(base + isbn)
}
<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>
ISBNs should be 13 numbers if I remember right so can't you just remove the whitespace and match groups of 13?
var str = "978 111 862 4616 9/10 condition with minimal highlighting\n\n9780415462020 10/10 condition, brand new",
nums = str.replace(/\s/,"").match(/\d{13}/g);
Current
I’ve re-worked this syllable counter script to:
Get the value of textarea 1.
Count the number of syllables in textarea 1.
Display the results in textarea 2.
Update the count every time the value of textarea 1 is edited.
Act as a function (be able to run in multiple instances if wanted).
Example function of current code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
11
Current code
Here is the existing code as a JSFiddle.
Goal
I would like this script to:
Count the syllables of textarea 1 on a per line basis: presumably by splitting the textarea 1 value where there are line breaks e.g. .split('\n');.
Output the results, showing the total number of syllables counted per line.
Example function of desired code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
6
3
2
Problem
I’m quite stuck as to how to do this and would really appreciate any help or JSFiddle showing how to work with the existing code to achieve this.
Notes
For anyone who may be interested using in the syllable count function code itself: it’s not 100% accurate and fails on some words but gives a good general idea.
Try this and let me know if it's what you needed.
Callouts:
I created an array that spits the lines up stores them var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);.
Then loop through that array and do exactly what you did before, but on each array entry. Then store the results in tempArr, and display the tempArr results.
See Fiddle
function $count_how_many_syllables($input) {
$("[name=set_" + $input + "]").keyup(function () {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var word;
var $syllable_count;
var $result;
for(var i = 0; i < arrayOfLines.length; i++){
$content = arrayOfLines[i];
word = $content;
word = word.toLowerCase();
if (word.length <= 3) {
word = 1;
}
if (word.length === 0) {
return 0;
}
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
.replace(/^y/, '')
.match(/[aeiouy]{1,2}/g).length;
$syllable_count = word;
$result = $syllable_count;
tempArr.push($result);
}
$("[name=set_" + $input + "_syllable_count]").val(tempArr);
});
}
(function($) {
$count_how_many_syllables("a");
})(jQuery);