jQuery: Searching textarea value for words using regex - javascript

I have the following code:
<script type="text/javascript">
$(function(){
var txt = new Array();
var count = 0;
$('textarea[id*="page_parts_attributes_"]').each(function(){
var html = $(this).html($(this).val());
var matches = $(html).match(/\b/g)
if(matches) {
txt[count] = jQuery.trim(matches).length / 2
count++;
}
});
var final_count = eval(txt.join('+'));
console.log(Math.floor(final_count));
})
</script>
I am basically trying to search the textarea for words. I have to convert the value of the textarea to HTML, then I want to search the HTML for words... but its not working...
any ideas?

var html = $(this).html($(this).val());
var matches = $(html).match(/\b/g)
should be
var matches = $(this).val().match(/\b/g);

The value of the textarea is aalready a string. The html method doesn't work the way you think it does. It should be a simple matter of removing the bits where you are attempting to use html.
<script type="text/javascript">
$(function(){
var txt = new Array();
var count = 0;
$('textarea[id*="page_parts_attributes_"]').each(function(){
var text = $(this).val();
var matches = text.match(/\b/g)
if(matches) {
txt[count] = jQuery.trim(matches).length / 2
count++;
}
});
var final_count = eval(txt.join('+'));
console.log(Math.floor(final_count));
})
</script>

Related

Not appending the desired output in jquery

I have the following (very incomplete) code that I want to eventually be a shopping cart using jquery.
This is code for loading items remotely from a json file and parsing them into Html using jquery.
$(document).ready(function () {
"use strict";
// Download the content
var head = $("<h1>Aisan Market</h1>");
var dl = $("<dl>");
$("body")
.append(head)
.append(dl)
for (var i = 0; i <shop.length; i++) {
var item = shop[i];
var dt=$("<dt>").text(item.itemId)
var dt1 = $("<dt>").text(item.name)
var dd = $("<dd>").text(item.price)
var button = $("<button>buy</button>");
dl
.append(button)
.append(dt)
.append(dt1)
.append(dd);
}
Here I'd like to have on a button click to walk the dom tree to the correct item id,item name and price and append that to the cart.but it's not doing that.It's writing the id number repeating it and writing 0.
var cart = $("<div>cart<div>");
$("body").append(cart);
var total = 0;
$("button").on("click", function () {
var a = $(this);
var prev = a.next("dt").text();
var b = $(this);
var prev1 = b.next("dt").text();
var c = $(this);
var prev2 = c.next("dd").text();
total += prev2;
cart
.append(prev)
.append(prev1)
.append(total);
});
});
Where am I going wrong.
Thanks a lot.

how to make space must be remains same after replacing text?

I have text, in which on selection I need to replace the text.
Here my requirement is, the space must be remain same after replacing the characters which contains spaces between them.
JavaScript:
function getSel() {
// obtain the object reference for the textarea>
var txtarea = document.getElementById("mytextarea");
// obtain the index of the first selected character
var start = txtarea.selectionStart;
// obtain the index of the last selected character
var finish = txtarea.selectionEnd;
//obtain all Text
var allText = txtarea.value;
// obtain the selected text
var sel = Array(finish - start).join("*");
//append te text;
var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
txtarea.value = newText;
$('#newpost').offset({ top: 0, left: 0 }).hide();
}
$(document).ready(function () {
var position;
$('#newpost').hide();
$('#mytextarea').on('select', function (e) {
$('#newpost').offset(position).show();
var txtarea = document.getElementById("mytextarea");
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
$('#newpost p').text(Array(finish - start).join("*"));
}).on('mousedown', function (e) {
position = { top: e.pageY-5, left: e.pageX};
});
$('#newpost').hide();
});
Here is my plunker
I am getting output as shown in above image but in expected output the space must not be replaced with asterisk .
Use string.replace instead, try this:
console.log('g2ggg gggGG'.replace(/[a-zA-Z0-9]/g, '*'))
Your all string manipulation logic will be only 1 line:
newText = allText.replace(/[a-zA-Z0-9]/g, '*')
I'm not very good at regex so I used a for-loop but maybe this still helps you.
$(document).ready(function () {
$('#mytextarea').on('select', function (e) {
var $output = $("#output");
var $txtarea = $("#mytextarea");
var start = $txtarea[0].selectionStart;
var finish = $txtarea[0].selectionEnd;
var subtext = $txtarea.text().substr(start, finish);
var out = "";
for (var i = 0; i < subtext.length; i++) {
var char = subtext[i];
if (char == " ") {
out += " ";
} else {
out += "*";
}
}
$output.text(out);
});
});
Based on your code you can see the working example in this fiddle:

How to split a comma seperated string and insert into html using javascript

Here is the string:
var numbers = "1,2,3,4,5,6,7,8,9,10";
I want this string to be separated and inserted into html.
Each time I refresh the page the numbers should iterate one by one.
Edit: Sorry, ignore the above line. If I have a button clicked it should iterate through the strings and display one by one.
Can anyone help me do this?
Try this,
var numbers = "1,2,3,4,5,6,7,8,9,10";
var n=numbers.split(','),
i=0;
$('#button').on('click', function(){
$('#show').text(n[i++]);
if(i==n.length) i=0;
});
HTML
<div id="show"></div>
<button id="button">Increment me</button>
var numbers = "1,2,3,4,5,6,7,8,9,10";
var n = numbers.split(','),
i = 0;
$('#button').on('click', function() {
$('#show').text(n[i++]);
if(i==n.length) i=0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show"></div>
<button id="button">Increment me</button>
If you want it on canvas then try it like,
Jquery
var numbers = "1,2,3,4,5,6,7,8,9,10";
var n=numbers.split(','),
i=0;
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
ctx.font="18px Arial";
$('#button').on('click', function(){
ctx.clearRect(0,0,300,300);
ctx.fillText(n[i++],20,20);
});
HTML
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<button id="button">Increment me</button>
Hope, this helps,
var indexLetter=0;
function paintletter(retryletter) {
var chars = charscontainer.innerHTML.split('');
// comment the blow code
/*letter = retryletter ||
chars[parseInt(Math.random() * chars.length,10)]; */
// add the below code
letter = retryletter ||
chars[indexLetter++];
if(indexLetter==chars.length) indexLetter=0;
c.width = container.offsetWidth;
......
Demo
Refer this fiddle:
http://jsfiddle.net/e1ky6rtj/
On Click of button:
<button onclick='clicked()'>ClickMe</button>
function clicked(){
var numbers = "1,2,3,4,5,6,7,8,9,10";
var c= numbers.split(','); //Split a string into an array of strings
for(var i=0;i<c.length;i++)
alert(c[i]);
}
html:
<div id="x"></div>
<button id="y">---</button>
js:
var numbers = "1,2,3,4,5,6,7,8,9,10";
$('#y').click(function () {
numbers.split(",").forEach(function(n, i) {
console.log(n + ' ' + i);
setTimeout(function() {
$('<p>').text(n).appendTo('#x');
}, i * 200);
});
});
fiddle
You can use the defualt function
ie,
var array = numbers.split(",");
array would be a normal javascript array
var numbers = "1,2,3,4,5,6,7,8,9,10";
$(numbers.split(',')).each(function(){
$('#main').append('<div>' + this + '</div><br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="main"></div>
use .split(',') this returns array of data which split by ,
var numbers = "1,2,3,4,5,6,7,8,9,10";
$("button").on('click', function () {
var spltValue = String(numbers).split(",");
for (var i = 0; i < spltValue.length; i++) {
var aData = spltValue[i];
console.log(aData);
}
});
JsFiddle
var numbers = "1,2,3,4,5,6,7,8,9,10";
var dataArray = numbers.split(",");
push to an array and handle it accordingly.

Javascript. It is possible to add id on splitted word?? using word.split("")

var wtc = document.getElementById("sw").value;
var cw = wtc.split("").join(' ');
cw.toString();
var x=document.getElementById("demo");
x.innerHTML=cw;
I have this code. how can i add id to the splitted(am i right on my term??) word.. it is possible?
I want is to add id on each letter that is splited. I dont know the exact number of letter because it's depend on the user's inputted word.
for example. i have this word from split.
[W][O][R][M]
i want it to be something it this. or anything that have an id :)
<div id="DIVtext1">W</div>
<div id="DIVtext2">O</div>
<div id="DIVtext3">R</div>
<div id="DIVtext4">M</div>
Thanks!
do you mean something like:
var word = "WORM".split("");
var demoEle = document.getElementById("demo");
for(var w = 0, len = word.length; w < len; w++) {
var divEle = document.createElement("div");
divEle.id = "DIVtext"+(w+1);
divEle.onclick = (function(v) {
return function() { copyDiv( "DIVtext" + (v+1) ) };
})(w);
divEle.innerHTML = word[w];
demoEle.appendChild( divEle );
}
Demo: jsFiddle
Updated Demo:: jsFiddle Updated
You could use a loop (for(i=0;i<splittedArray;i++)) and jQuery to add div tags to the dom with the innerHtml being the word.
Basically, once you have it in your array you can put it wherever you want. I find that jQuery makes it easy; however, you could also do it through jscript alone.
This can be achieved pretty easily using jQuery.
var letters = $('#sw').val().split('');
$.each(letters, function(i, letter) {
$('<div />', {
id: 'DIVtext'+ i,
text: letter
}).appendTo('#demo');
});
JSFiddle
If jQuery isn't an option, here's what you can do with vanilla JS.
var letters = document.getElementById('sw').value.split(''),
demo = document.getElementById('demo');
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('div');
letter.innerHTML = letters[i];
letter.id = 'DIVtext'+ i;
demo.appendChild(letter);
}
JSFiddle

Continuously loop through JavaScript text array onclick

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>

Categories

Resources