Javascript (using jQuery):
var paragraphs = [
['This is my first paragraph content of the first array', 'This is my second paragraph content of the first array', 'This is my third paragraph content of the first array'],
['This is my first paragraph content of the second array', 'This is my second paragraph content of the second array', 'This is my third paragraph content of the second array']
],
text_box_value,
unused_paragraphs = null;
$(document).ready(function(){
$('input#text_box').keyup(function(){
text_box_value = $(this).val();
});
$('input#submit_button').click(function(){
if(unused_paragraphs === null) {
unused_paragraphs = paragraphs;
}
for(var i = 0; i < unused_paragraphs.length; i++) {
if(unused_paragraphs[i].length == 0)
unused_paragraphs[i] = paragraphs[i];
while(unused_paragraphs[i].length != 0) {
var rand = Math.floor(Math.random() * unused_paragraphs[i].length);
if(unused_paragraphs[i][rand].search(text_box_value) !== -1) {
$("#paragraphs_container").append('<p>' + unused_paragraphs[i][rand] + '</p>');
break;
}
unused_paragraphs[i].splice(rand, 1);
}
}
console.log(unused_paragraphs);
console.log(paragraphs);
});
});
My question is why when I use splice method on unused_paragraphs variable it also remove the value from the paragraphs variable
Later edit JSFiddle
javascript objects/array are stored by reference.
If you want a copy that's a trick:
if(typeof unused_paragraphs == "undefined") {
var unused_paragraphs = [];
for(var i = 0; i<paragraphs.length; i++) {
unused_paragraphs[i] = paragraphs[i].slice(0);
}
}
and
unused_paragraphs[i] = paragraphs[i].slice(0);
to copy the obect to new object..
try this..
var unused_paragraphs= jQuery.extend(true, {}, paragraphs);
here is just an example of copied objects.. check it out
http://jsfiddle.net/5ExKF/3/
Related
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 have a div with multiple images inside and i need to click on a random image then again click on a random picture and when i clicked the second image to change images with each other. All images are interchangeable.Heres what i've done so far:
EDIT FIDDLE: http://jsfiddle.net/w53Ls/5/
$("#image1").click(function(){
imagePath = $("#image2").attr("src");
if(imagePath == "http://s15.postimg.org/oznwrj0az/image.jpg"){
$("#image3").attr("src", "http://s21.postimg.org/ojn1m2eev/image.jpg");
}else{
$("#image4").attr("src", "http://s23.postimg.org/epckxn8uz/image.jpg");
}
});
EDIT: The code i have tryed for check function is in EDIT FIDDLE and with the alert i check src of pictures.Now i simply need to make a condition to alert something after i change all the pieces in order and found the whole picture.Any hint?
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
$("img.element").click(function(){
if (clickCount == 0)
{
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
}
else {
$("#"+lastImgId).attr("src",$(this).attr("src"));
$(this).attr("src",imgSrc)
clickCount = 0;
}
});
Updated
This let's you know when you're done with the puzzle
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
// Function for Comparing Arrays
// source: http://stackoverflow.com/questions/7837456/
Array.prototype.compare = function (array) {
if (!array) return false;
if (this.length != array.length) return false;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].compare(array[i])) return false;
} else if (this[i] != array[i]) {
return false;
}
}
return true;
}
$(document).ready(function () {
// Store the correct order first in an array.
var correctOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Randomize your images
var a = $("#puzzle > img").remove().toArray();
for (var i = a.length - 1; i >= 1; i--) {
var j = Math.floor(Math.random() * (i + 1));
var bi = a[i];
var bj = a[j];
a[i] = bj;
a[j] = bi;
}
$("#puzzle").append(a);
$("img.element").click(function () {
if (clickCount == 0) {
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
} else {
$("#" + lastImgId).attr("src", $(this).attr("src"));
$(this).attr("src", imgSrc);
clickCount = 0;
// Get the current order of the images
var currentOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Compare the current order with the correct order
if (currentOrder.compare(correctOrder)) alert("Puzzle completed");
}
});
});
http://jsfiddle.net/w53Ls/2/
var counter = 0;
The code was improvised but works XD
you try improve it
Here is a new version of your jsfiddle that I think will do what you want.
It applies the same click handler to every object with the class swapable. Each time a swapable element is clicked, the handler checks whether another element was previously clicked first. If so, it swaps them. If not, it just remembers that this element is the first one.
var firstId = ''; // Initially, no element has been clicked first
var firstSrc = '';
// Apply the following function to every element with 'class="swapable"
$('.swapable').click(function(){
if (firstId !== '') { // There is already a first element clicked
// Remember the information of the currently clicked element
var secondId = $(this).attr('id');
var secondSrc = $(this).attr('src');
// Replace the currently clicked element with the first one
$('#' + secondId).attr('src', firstSrc);
// Replace the first one with the current one
$('#' + firstId).attr('src', secondSrc);
// Forget the first one, so that the next click will produce a new first
firstId = '';
firstSrc = '';
}
else // This is the first element clicked (this sequence)
{
// Remember this information for when a second is clicked
firstId = $(this).attr('id');
firstSrc = $(this).attr('src');
}
});
I'm parsing a document that has a known repeating structure. There is a heading (1 line), a sub-heading(1 line), and a content area (unknown # of lines).
The format for each item in the document is shown below:
=========================
Head Text
=========================
SubHead Text
=========================
Content Text Line 1
Content Text Line 2
...
Content Text Line 8
I want to create an Array that contains an Object for each section.
Something like:
var item = [];
items[0] = {
head: "head1 text",
subHead: "subHead1 text",
content: "content1 text"};
items[1] = {
head: "head2 text",
subHead: "subHead2 text",
content: "content2 text"};
I am having trouble efficiently traversing the document and dynamically adding each Object into the Array. I get an error under section 2 telling me that "page is null or not an object".
var count = 0;
while( !stream.AtEndOfStream ){
page[count] = stream.ReadLine();
count++;
}
var item = [{}];
var section = 0;
var i = 0, k = 0;
while (i < page.length) {
if (~page[i].indexOf("=====")) {
if(section == 0) {
item[k].head = page[i+1];
section++;
} else
if (section == 1) {
item[k].subHead1 = page[i+1];
section++;
i++;
} else
if (section == 2) {
var j = i+1;
while(!~page[j].indexOf("=====")) {
item[k].content += page[j] + "\n";
j++;
}
section = 0;
k++;
}
}
i++;
}
Change this:
var item = [{}];
to this:
var item = [];
Next, change this:
if (~page[i].indexOf("=====")) {
to this:
if (~page[i].indexOf("=====")) {
item[k] = {};
I am not sure if that will work, but the basic idea is to create a blank array (var item = [];) and then add objects when needed (item[k] = {}). Previously you were trying to add properties to undefined objects.
page is null because it has not been declared, in your snippet at least.
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>
How can I get the list of attributes of an HTML string using Javascript? Here's my code so far.
function traverse_test(){
var root=document.getElementById('arbre0').childNodes;
for(var i=0;i<root.length;i++){
var lis = root[i];
if (lis =='[object HTMLUListElement]') {
for (var member in lis) {
if (typeof lis[member] == "string") {
var assertion = lis[member];
var resultat = assertion.search(/..Bookmarks/);
if (resultat != -1) {
output.innerHTML+= lis[member];
// Here I'd like to have the list of lis[member] attributes
for(var attr in lis[member].attributes) {
output.innerHTML+=lis[member].attributes[attr].name + "=\""+ lis[member].attributes[attr].value + "\"";
}
break;
}
}
}
}
}
}
Use the Node.attributes property of a DOM element. Example:
var foo = document.getElementById('foo'),
attrs = foo.attributes,
i = attrs.length,
attr;
while (i--)
{
attr = attrs[i];
console.log(attr.name + '="' + attr.value + '"');
}
Demo: http://jsfiddle.net/mattball/j8AVq/
Seems like all these answers point to how to get an attr list from a node but the question asks for attrs from an HTML string. Here is my 2cents.
//turn your string into a node and get your html strings NamedNodeMap
var temp = document.createElement("div");
temp.innerHTML = "<div attr-1 attr-2 attr-3 attr-4></div>";
temp = temp.firstElementChild.attributes;
//put the attributes in a an array
var list = Object.keys(temp).map( function( index ) { return temp[ index ] } );
console.log( list );
If you know the attributes to get the value you can do:
var MyValue = document.getElementById("myimage").getAttribute("src")
In JavaScript to loop all attributes:
var el = document.getElementById("someId");
var arr = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
arr.push(attrs.item(i).nodeName);
}
The above code was taken from this question
Jquery might be another option:
http://plugins.jquery.com/project/getAttributes
[].slice
.apply(document.querySelector('something').attributes)
.forEach(function(item){
console.log(item, item.name, item.value);
});