I have made a code that needs to make page-breaks after certain number of new lines or words. I have set up an array that tell me where it should cut in my element. As you can see in my jsFiddle you can see a console.log(); that shows I need to cut the text.
I would like to get help on how to create a closing </div> inserted after the specific string from my array(). I would like to have a closing </div> and a creation of a new <div>
More details about the code
// $(this)
$(this) = $('.c_84');
The HTML example
<div class=" onerow counting_1"><div class="newDiv"></div>
<div class="onefield c_6937">
<!-- This is where I want to generate the new divs -->
<table class="textarea" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="value"><!-- Content String --></td>
</tr>
</tbody>
</table>
</div>
</div>
Here is my code logic so far.
// The class c_6937 is the class test in my jsFiddle
// I did this just to remove extra html and focus on the problem
// Start
$(this).find('.c_6937').parent().prepend('<div class="newDiv">');
var countReqNumberOfPages = newChunk.length;
for (var key in newChunk) {
// If we find the first chunk, insert </div><div class="newDiv"> after it.
}
// End
$(this).find('.c_6937').parent().append('</div>');
Could it be possible to run a str_replace() function inside my array() and replace the current string with the exact same string plus the closing divs?
EDIT 1 : I added extra comments in the code for a better understanding of the problem and added a possible solution.
I'm not sure whether you are after something like this
<script type="text/javascript">
var wordsPerLine = 15;
var minWordsPerLine = 5;
var linesPerPage = 30;
var linesToStopAfter = [];
function checkForDot(pos,masterArray){
if(pos < 0){
return false;
}
var line = masterArray[pos];
if(line.indexOf('.') !== -1){
return line;
}
else{
return checkForDot(pos-1,masterArray);
}
}
function chunk(lines) {
var masterLines = [];
for (i = 0; i < lines.length; i++) {
var sentence = [];
var wordsList = lines[i].split(" ");
var wordCount = 0;
for (j = 0; j < wordsList.length; j++) {
if(wordCount >= wordsPerLine){
wordCount = 0;
masterLines.push(sentence.join(" "));
sentence = [];
sentence.push(wordsList[j]);
}
else{
sentence.push(wordsList[j]);
}
wordCount++;
}
masterLines.push(sentence.join(" "));
}
return masterLines
}
$(document).ready(function()
{
var html = $("#test").html();
$("#test").html('<div class="newDiv">'+html+'</div>');
var lines = chunk($("#test").text().split("\n"));
var count = 0;
for (k = 0; k < lines.length; k++) {
count++;
if(count >= linesPerPage){
count = 0;
linesToStopAfter.push(checkForDot(k,lines));
}
}
for(j=0; j<linesToStopAfter.length;j++)
{
toreplace = $("#test").html().replace(linesToStopAfter[j], linesToStopAfter[j]+"</div><div class='newDiv'>");
$("#test").html(toreplace)
}
cleanedhtml = $("#test").html().replace(/<\s*div[^>]*><\s*\/\s*div>/g,"");
$("#test").html(cleanedhtml)
});
</script>
Related
I am using the p5.js library, and I am working on a speech recognition - text to speech project. Kind of a chatbot.
Input is voice input which becomes a string.
I am outputting the result from a txt file, using a markov chain. Output is a string contained in a div.
My question is:
Is there a way to hide/show the div containing my input/output (.myMessage and .robotMessage) in intervals?
I want the whole screen first showing only the input when I am talking, then input disappears and only output showing, then when the computer voice finishes speaking my input is shown in the screen and so on...
Here some parts of the code, let me know if it is clear enough.
//bot
function setup() {
noCanvas();
//reads and checks into the text file
for (var j = 0; j < names.length; j++) {
var txt = names[j];
for (var i = 0; i <= txt.length - order; i++) {
var gram = txt.substring(i, i + order);
if (i == 0) {
beginnings.push(gram);
}
if (!ngrams[gram]) {
ngrams[gram] = [];
}
ngrams[gram].push(txt.charAt(i + order));
}
}
//voice recognition
let lang = 'en-US';
let speechRec = new p5.SpeechRec(lang, gotSpeech);
let continuous = true;
let interim = false;
speechRec.start(continuous, interim);
//text-to-speach
speech = new p5.Speech();
speech.onLoad = voiceReady;
function voiceReady() {
console.log('voice ready');
}
//input-ouput
function gotSpeech() {
if (speechRec.resultValue) {
var p = createP(speechRec.resultString);
p.class('myMessage');
}
markovIt();
chooseVoice();
speech.speak(answer);
}
}
and
function markovIt() {
var currentGram = random(beginnings);
var result = currentGram;
for (var i = 0; i < 100; i++) {
var possibilities = ngrams[currentGram];
if (!possibilities) {
break;
}
var next = random(possibilities);
result += next;
var len = result.length;
currentGram = result.substring(len - order, len);
}
var answer = result;
window.answer = answer;
var p2 = createP(answer);
p2.class('robotMessage');
}
how the HTML looks
<div class="container">
<div class="myMessage"></div>
<div class="robotMessage"></div>
</div>
Use select() to get a document element by its id, class, or tag name. e.g:
let my_div = select("myMessage");
Change the style of an element by style().
e.g hide:
my_div.style("display", "none");
e.g. show:
my_div.style("display", "block");
See also Toggle Hide and Show
How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
I have a html textarea and i need to extract the word from the text in it, depending on where the caret is.
So, if the caret is in a word, or just at the end of beginning (or end) of a word, i need to get that.
How can i do that? Im not looking for a library, just plain javascript.
Please help.
Here is some code that will do the job. Basically, extract the caret position. Convert sentence to array. Loop array adding words lengths together, when length is greater than caret position you have found your word.
<html>
<script>
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}
function getWord()
{
var el = document.getElementById('myText');
var carret = getCaret(el);
var words = el.value.split(' ');
var x = 0;
for(var i = 0; i < words.length; i++)
{
debugger;
x += words[i].length + 1;
if(x > carret){ return words[i]; }
}
}
function myWord()
{
var word = getWord();
alert(word);
}
</script>
<body>
<button onclick="myWord();" >Get word</button>
<textarea id="myText">This is a hallo world sentence</textarea>
</body>
</html>
I'm trying to find out what characters has the user changed in a string. I luckily can assume there's only one, consequent change block.
I've even failed to find where the changed area begins:
var originalVal, val; //strings
//The ranges
var original = [0,0];
var new_rang = [0,0];
//Old length, new length
var ol = originalVal.length;
var nl = val.length;
//Find where the change begins (that should be the same for both arrays)
for(var i=0; ; i++) {
//If end of string was reached or the strings are different
if((i>=ol||i>=nl) || originalVal[i]!=val[i]) {
original[0] = new_rang[0] = i;
//Set these to i too, assuming there was no change
original[1] = new_rang[1] = i;
break;
}
}
This totally breaks if there's a row of same characters and user deletes one in the middle:
mmmmx
mmmmx
mmmx
Script will say that the change occured at 4, where the x moved. But in fact, it doesn't even seem to be possible to say which m was deleted.
I can however tell where the cursor position was at the beginning and where it is in the end. That way it looks more promising, but I still don't know what to do:
mm|mmx
mm|mmx
m|mmx
This time I can see which m was deleted. But I still don't know how to explain it to a computer.
Here is what I think you might be looking for. Please clarify your question.
var Console = function() {
this.log = function(msg) {
debug(msg)
};
};
var console = new Console();
function diffLengths(longer, shorter) {
var indexes = [];
var isTheSame = true;
for (var i = 0; i < shorter.length; i++) {
if (shorter[i] != longer[i]) {
isTheSame = false;
indexes.push(i);
}
};
if (isTheSame) {
// The shorter string is exactly the same as the longer string
// except for the extra characters in the longer string
indexes.push(shorter.length);
}
return indexes;
}
function getDiffRange(first_string, second_string) {
var indexes = [];
if (first_string.length > second_string.length) {
return diffLengths(first_string, second_string);
} else if (first_string.length < second_string.length) {
return diffLengths(second_string, first_string);
} else {
for (var i = 0; i < first_string.length; i++) {
if (second_string[i] != first_string[i]) {
indexes.push(i);
}
};
}
return indexes;
}
var range = getDiffRange('mmmmx', 'mmmx');
document.getElementById('result-1').innerHTML = range[0] + " - " + range[range.length - 1];
var range = getDiffRange('mmmmx', 'mmmxc');
document.getElementById('result-2').innerHTML = range[0] + " - " + range[range.length - 1];
var range = getDiffRange('mm', 'mmx');
document.getElementById('result-3').innerHTML = range[0] + " - " + range[range.length - 1];
table, th, td {
border-collapse: collapse;
border: 1px solid #ddd;
text-align: left;
padding: 7px;
}
<html>
<body>
<table>
<tr>
<th>input</th>
<th>result</th>
</tr>
<tr>
<td>'mmmmx', 'mmmx':</td>
<td id='result-1'></td>
</tr>
<tr>
<td>'mmmmx','mmmxc':</td>
<td id='result-2'></td>
</tr>
<tr>
<td>'mm','mmx':</td>
<td id='result-3'></td>
</tr>
</table>
</body>
</html>
I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
Here's what I have
$(document).ready(function(){
var arr = new Array("One","Two","Three");
var len=arr.length;
$('#next').click(function(){
for(var i=0; i<len; i++) {
$('#quote').html(arr[i]);
}
});
});
Something like the following should do the trick:
<script type="text/javascript">
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var count = -1;
return function() {
return wordArray[++count % wordArray.length];
}
}());
</script>
<p id="foo"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
Radomised version:
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var copy;
return function() {
if (!copy || !copy.length) copy = wordArray.slice();
return copy.splice(Math.random() * copy.length | 0, 1);
}
}());
The following should do it http://jsfiddle.net/mendesjuan/9jERn/1
$(document).ready(function(){
var arr = ["One","Two","Three"];
var index = 0;
$('#next').click(function(){
$('#quote').html(arr[index]);
index = (index + 1) % arr.length ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
I think something like this would work
The javascript would look like:
// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
textDisplayIndex += 1;
if (textDisplayIndex > maxTextArrayIndex)
{
textDisplayIndex = 0;
}
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}
The html would look like:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>