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>
Related
I have an history feature for a particular,div on my website. Everything worked fine up to now, I was inserting HTML as strings from javascript and re-display them with .innerHTML. Now I try to clean up the javascript from all HTML strings and I have this problem: history browsing of the div works in FF, Chrome and some other, but not IE (8 to 11), can't understand why. Is it a cloneNode() or a reference issue I don't see ?
Below is a small script to reproduce the behaviour, you can play with here: http://jsfiddle.net/yvecai/7e8tksm3/
My code works as follow: each time I display something in Mydiv, I clone it and append it in an array.
The function prev() or next() append the corresponding nodes from the array for display.
The script first create 5 contents '1' ... '5' that the user can display with the functions prev() and next(). In IE, when you go prev(), then next(), only the first and last records are shown. In other browsers, no problem.
var cache = [];
var i = 0;
function next() {
var hist = document.getElementById('history');
i += 1;
if (i > 4) {
i = 4
};
hist.innerHTML = '';
hist.appendChild(cache[i]);
}
function prev() {
var hist = document.getElementById('history');
i -= 1;
if (i < 0) {
i = 0
};
hist.innerHTML = '';
hist.appendChild(cache[i]);
}
function cacheInHistory(div) {
cache.push(div.cloneNode(true));
}
function populate() {
for (i = 0; i < 5; i++) {
var hist = document.getElementById('history');
hist.innerHTML = '';
var Mydiv = document.createElement('div');
Mydiv.innerHTML = i;
hist.appendChild(Mydiv);
cacheInHistory(Mydiv);
}
i = 4
}
I tried to simplify your code:
In the function populate (onload) create and populate the array cache. As last operation append your child.
In your next or previous function use replaceChild instead of append and remove innerHTML.
var cache=[];
var i = 0;
function next(){
var hist = document.getElementById('history');
i = (++i > 4) ? 4 : i;
hist.replaceChild(cache[i], hist.children[0]);
}
function prev(){
var hist = document.getElementById('history');
i = (--i < 0) ? 0 : i;
hist.replaceChild(cache[i], hist.children[0]);
}
function cacheInHistory(div){
cache.push(div.cloneNode(true));
}
function populate(){
var hist = document.getElementById('history');
for (i=0 ; i<5 ; i++){
hist.innerHTML='';
var Mydiv = document.createElement('div');
Mydiv.innerHTML = i;
cacheInHistory(Mydiv);
}
i = 4
hist.appendChild(cache[i]);
}
<body onload="populate();">
<div id="prev" onclick="prev()">
prev
</div>
<div id="next" onclick="next()">
next
</div>
<hr/>
<div id="history">
</div>
</body>
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>
I am working on a project that takes text that a user inputs in a text box and returns the most common word.
Javascript:
var bestMode = 1;
var currentMode = 0;
var character;
function Find_Word(){
var words = document.getElementById('words').innerText;
var punctuationless = words.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var WordList = finalString.split(" ");
return FindMode(WordList);
}
function FindMode(WordList){
for(var i=0; i<WordList.length; i++){
for(var m=i; m<WordList.length; m++){
if(WordList[i] == WordList[m]){
currentMode += 1;
}
if(bestMode<currentMode){
bestMode = currentMode;
character = WordList[i];
}
}
currentMode = 0;
}
}
console.log(bestMode);
HTML:
<html>
<body>
<h1>Most common word used</h1>
<input type="text" id="words" rows="10" columns="30"></input>
<button type="button" id="FindWord" onclick="Find_Word()">Find Word</button>
<script src="CommonWord.js"> </script>
</body>
</html>
What I can't figure out is the correct way to pull text from the text box into a variable as one string. My function Find_Word takes the received string when the button is pressed and strips away punctuation and leaves an array WordList with with each individual word in the string.
After that, I also can't understand how to pass that array into my second function findMode where I iterate through each value of the array to find the most common word. That is saved in the variable bestMode.
It looks as if you are both getting the current text and passing the array correctly (although perhaps you should get the textbox value using the .value property). What problem are you having exactly? I am not sure what FindMode is supposed to do either.
Here is some script that is based on what you posted that sorts "words" according to how often they appear :
(function(w) {
w.Sort_Words = function(words) {
var o = {}, l = [];
for(var i=0; i<words.length; i++) {
if (typeof o[words[i]] === 'undefined') {
o[words[i]] = 0;
l.push(words[i]);
}
o[words[i]] ++;
}
l.sort(function(a, b) { return o[b] - o[a]; });
return l;
};
w.Find_Word = function() {
var text = document.getElementById('words').value;
var words = text.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"").replace(/\s{2,}/g," ").split(' ');
var sorted = w.Sort_Words(words);
document.getElementById('results').innerText = sorted.length === 0 ?
'You must type at least one word' :
'The most commonly used word was: ' + sorted[0];
};
})(window);
Fiddler: http://jsfiddle.net/4u1mv20h/4/
I need to create 2 arrays in JS from an input value. The first should contain all my inputs values and the second one should contain all my inputs values but for the last one.
I tried this but it doesn't work.
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
var comp = [];
function clickHandler()
{
n = input.value;
for (var i =0; i < 10; i++)
{
valori.push(parseInt(n));
comp = valori.pop();
console.log(valori);
console.log(comp);
break;
}
}
</script>
</body>
The ideea is that I want to check if an input value has been entered before. I thought of doing that by creating 2 arrays like I mentioned before and then compare "n" to the "comp" array
if you are just to check element exist or not.. why dont u why indexOf(n)??
no need to create two array and for loop etc etc.. just indexOf will work for you..
check the below code..
<html>
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
function clickHandler()
{
if(isNaN(input.value))
{
alert('value is not a Number');
}
else
{
var nbr = parseInt(input.value);
if(valori.indexOf(nbr) < 0)
{
valori.push(nbr);
input.value="";
}
else
{
alert('element already exists.');
}
}
}
</script>
</body>
</html>
U are setting value on comp which is array u need to set value at index .
function clickHandler()
{
var is = true;
var n = parseInt(document.getElementById("inp").value);
if(!isNaN(n))
{
for (var i =0; i < valori.length; i++)
{
if(n === valori[i])
{
console.log("duplicate");
is = false;
break;
}
}
if(is)
valori.push(n);
}
console.log(valori);
}
DEMO
On page load, I am randomizing the order of the children divs with this Code:
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
I cannot seem to figure out how to get the posts back in the original order. Here's the demo of my current code http://jsfiddle.net/JsJs2/
Keep original copy like following before calling reorder() function and use that for reorder later.
var orig = $("#team-posts").children();
$("#undo").click(function() {
orderPosts();
});
function orderPosts() {
$("#team-posts").html( orig ) ;
}
Working demo
Full Code
var orig = $("#team-posts").children(); ///caching original
reorder();
$("#undo").click(function(e) {
e.preventDefault();
orderPosts();
});
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
function orderPosts() {
// set original order
$("#team-posts").html(orig);
}
How about an "undo" plugin, assuming it applies?
Just give each item a class with the corresponding order and then get the class name of each div and save it to a variable
$("#team-posts div").each(function() {
var parseIntedClassname = parseInt($(this).attr("class");
arrayName[parseIntedClassname] = $("#team-posts div." + parseIntedClassname).html()
});
You can reorder them from there by saving their html to an array in order
$("#team-posts").html();
for(var i=0;i<arrayName.length;i++){
$("#team-posts").append('<div class="'+i+'">'+arrayName[i]+'</div>');
}
The solution with saving away the original order is probably the best but if you have to dynamically sort it, you can use this:
http://www.w3schools.com/jsref/jsref_sort.asp
function orderPosts() {
var $grp = $("#team-posts"),
ordered = $grp.children().toArray().sort(function(a, b) {
return parseInt($(a).text()) > parseInt($(b).text());
});
$grp.empty().append(ordered);
}