I have this code which removes the text from textarea only on first click. It works ok only until I wrote the second textarea tag which is:
<textarea id="textarea2" onfocus="checkOnFocus(this);" onblur="resetInitialText(this);">Your second message</textarea>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var flag = false;
function setInitialText() {
var textarea = document.getElementById('textarea');
if (textarea.value == "") {
textarea.value = text;
}
}
function checkOnFocus(textarea) {
if (!flag) textarea.value = "";
flag = true;
}
function resetInitialText(textarea) {
if (textarea.value == "") {
textarea.value = text;
flag = false;
}
}
</script>
</head>
<body onload="setInitialText();">
<textarea id="textarea" onfocus="checkOnFocus(this);" onblur="resetInitialText(this);">Your first message</textarea>
<textarea id="textarea2" onfocus="checkOnFocus(this);" onblur="resetInitialText(this);">Your second message</textarea>
</body>
</html>
I finally found how to do what I asked:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script>
<script type='text/javascript'>//<![CDATA[
$(function() {
$("textarea").focus(function(event) {
// Erase text from inside textarea
$(this).text("");
// Disable text erase
$(this).unbind(event);
});
});
//]]>
</script>
</head>
<body>
<textarea rows="5" cols="30">Enter text here.</textarea>
<textarea rows="5" cols="30">Enter text here.</textarea>
</body>
</html>
Seeing from your answer, that you're ok with jquery, you could try the following as a very basic placeholder-solution:
$('[data-placeholder]').each(function () {
var placeholder = $(this).data('placeholder');
$(this).val(placeholder).on({
focus: function () {
$(this).val(function (_, value) {
return value === placeholder ? '' : value;
});
},
blur: function () {
$(this).val(function (_, value) {
return value === '' ? placeholder : value;
});
}
});
});
with:
<textarea data-placeholder="Your first message"></textarea>
<textarea data-placeholder="Your second message"></textarea>
http://jsbin.com/iyobiy/1/
function checkOnFocus(textarea){
if(!flag)
textarea.value="";
flag=false;
}
function resetInitialText(textarea){
if(textarea.value==""){
textarea.value='text';
flag=false;
}
two changes are here
1>checkOnFocus() method
flag=false;
2>resetInitialText() method
textarea.value='text';// make your own string to replace
You have only one (global) flag and two textareas, so by the time the second call is made, the flag has already been set to true. Consider using an array or a dictionary type structure to create a generic implementation. One option would be to use an array in the global scope:
var textareasAlreadyHit = new Array();
Then every time you:
function checkOnFocus(textarea)
Instead of checking for the flag, check if the array contains the id of the textarea. If it does, do nothing. If it does not, remove the text from the textarea and add the id of the textarea to the array.
Related
Please have a look at the following code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
//Function to Trim
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,"");
};
//Function to remove punctuation
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
function count()
{
var listOfWords, paragraph, listOfWordsArray, paragraphArray;
var wordCounter=0;
listOfWords = document.getElementById("wordsList").value.trim();
listOfWords = listOfWords.toUpperCase();
//Split the words
listOfWordsArray = listOfWords.split(/\r?\n/);
//Get the paragrah text
paragraph = document.getElementById("paragraph").value.trim();;
paragraph = paragraph.toUpperCase();
//Filter all the punctuations
replaceAll("\"","",paragraph);
replaceAll("[","",paragraph);
replaceAll("]","",paragraph);
replaceAll("{","",paragraph);
replaceAll("}","",paragraph);
replaceAll("(","",paragraph);
replaceAll(")","",paragraph);
replaceAll("<","",paragraph);
replaceAll(">","",paragraph);
replaceAll(":","",paragraph);
replaceAll(",","",paragraph);
replaceAll("-","",paragraph);
replaceAll("...","",paragraph);
replaceAll("!","",paragraph);
replaceAll("<<","",paragraph);
replaceAll(">>","",paragraph);
replaceAll("","",paragraph);
replaceAll(".","",paragraph);
replaceAll("?","",paragraph);
replaceAll("/","",paragraph);
replaceAll("\\","",paragraph);
paragraphArray = paragraph.split(" ");
//check whether paragraph contains words in list
for(var i=0; i<paragraphArray.length; i++)
{
//re = new RegExp("\\b"+paragraphArray[i]+"\\b","i");
if (listOfWordsArray.indexOf(paragraphArray[i]) >= 0)
{
}
else
{
wordCounter++;
}
}
var average =0;
average = (wordCounter/paragraphArray.length)*100;
average = 100-average;
average = Math.round(average*100)/100;
window.alert("Number of Words: "+paragraphArray.length+ "\n"+ "Number of Unmatched words: "+wordCounter+ "\n"+ "Percentage "+average+"%" );
}
</script>
</head>
<body>
<center>
<p> Enter your Word List here </p>
<br />
<textarea id="wordsList" cols="100" rows="10"></textarea>
<br />
<p>Enter your paragraph here</p>
<textarea id="paragraph" cols="100" rows="15"></textarea>
<br />
<br />
<button id="btn1" onclick="count()">Calculate Percentage</button>
</center>
</body>
</html>
In here, I am trying to remove all the punctuation from the text. But my code gives no output. My knowledge lacks when it comes to web scripting languages, so I can't find the solution. How can I remove the punctuation from the text? What am I doing wrong here?
Update
According to Rahul's answer, I edited my code in the following way, but unfortunately still I have no good. I want to remove all the punctuation from the entire text, not just remove the first punctuation.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
//Function to Trim
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,"");
};
//Function to remove punctuation
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
function count()
{
var listOfWords, paragraph, listOfWordsArray, paragraphArray;
var wordCounter=0;
listOfWords = document.getElementById("wordsList").value.trim();
listOfWords = listOfWords.toUpperCase();
//Split the words
listOfWordsArray = listOfWords.split(/\r?\n/);
//Get the paragrah text
paragraph = document.getElementById("paragraph").value.trim();;
paragraph = paragraph.toUpperCase();
//Filter all the punctuations
var newstring= paragraph.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = newstring.replace(/\s{2,}/g," ");
paragraphArray = finalString.split(" ");
//check whether paragraph contains words in list
for(var i=0; i<paragraphArray.length; i++)
{
//re = new RegExp("\\b"+paragraphArray[i]+"\\b","i");
if (listOfWordsArray.indexOf(paragraphArray[i]) >= 0)
{
}
else
{
wordCounter++;
}
}
var average =0;
average = (wordCounter/paragraphArray.length)*100;
average = 100-average;
average = Math.round(average*100)/100;
window.alert("Number of Words: "+paragraphArray.length+ "\n"+ "Number of Unmatched words: "+wordCounter+ "\n"+ "Percentage "+average+"%" );
}
</script>
</head>
<body>
<center>
<p> Enter your Word List here </p>
<br />
<textarea id="wordsList" cols="100" rows="10"></textarea>
<br />
<p>Enter your paragraph here</p>
<textarea id="paragraph" cols="100" rows="15"></textarea>
<br />
<br />
<button id="btn1" onclick="count()">Calculate Percentage</button>
</center>
</body>
</html>
May be you can try like this:-
var s = "Your%^%*^%^&*^% string '"+"'which*^&^&( consists of punctuation";
var st = s.replace(/["']/g, "")
var newstring= st.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`"~()]/g,"");
var finalString = newstring.replace(/\s{2,}/g," ");
alert(finalString);
The above code will replace all the punctuation from your string s
The above code works fine. Please check the JSFIDDLE.
I have the following html and javascript. If I click on simulate event I want the HandleEvents function to post the text into the 'child' page html. So I am essentially trying to latch onto an html element inside a child web page from a parent.
How do I do that?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function _bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
function doconfigure() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="configure.html";
}
}
function doevents() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
}
function dooutbound() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="outbound.html";
}
}
function HandleEvents(data) {
//post data to show_events.html page
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
//post to events field
var elem = top.frames['display'].document.getElementById('event');
if(elem) {
elem.innerHTML = data;
}
}
</script>
<title></title>
</head>
<body>
<fieldset>
<legend>Select</legend>
<input type="button" value="Configure" onclick="doconfigure();">
<input type="button" value="Events" onclick="doevents();">
<input type="button" value="Outbound" onclick="dooutbound();">
<input type="button" value="simulate event" onclick="HandleEvents('my event');">
<br />
</fieldset>
<iframe src="configure.html" name="display" id="ifrm" height="700" width="800">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
Then the show_events.html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<p>Events:</p>
<p id="event"></p>
</body>
</html>
You will not be able to do this unless the IFRAME shares the same origin as the parent script (for CSRF-protection purposes). If this requirement is met, it's all good.
jQuery is strongly recommended for this as things can get very, very messy very quickly.
You can gain access to the DOM of the IFRAME using the following:
jQuery (Fiddle: http://jsfiddle.net/ZYxVA/)
var myIFRAME = $("iframe#test");
var myContent = $("html",myIFRAME.contents());
Native (Fiddle: http://jsfiddle.net/L8Cek/)
var myIFRAME = document.getElementById("test");
var mC = myIFRAME.contentDocument,
mCbody = mC.getElementsByTagName("body")[0];
var docE = document.createElement("div");
docE.innerHTML = "this is a test";
mCbody.appendChild(docE);
As you can probably tell by now, jQuery is strongly recommended due to the fact that your code will get very hairy, very quickly otherwise. The quick run-down is, $("iframe").contents() allows you to get contentDocument. From there, you can run queries against that DOM by passing it as the second parameter.
In addition to this, you also will not be able to do anything until the iframe is fully loaded. You can listen to this by binding an onLoad event on it.
You need to wait for the iframe to be fully loaded before you can access the elements in the iframe.
Basic idea:
function HandleEvents (data) {
var myIframe = document.getElementById('ifrm');
myIframe.onload = function() {
var innerDoc = myIframe.contentDocument || myIframe.contentWindow.document;
var myElement = innerDoc.getElementById('event');
myElement.innerHTML = data;
};
myIframe.src = 'show_events.html';
}
This code is attempting to highlight (by adding 'bold' tag) some characters that are in the HTML body. (These are specified in the JS function)
But instead of the text becoming bold, I get the 'bold' tag as the result in the html page that is getting rendered.
While I want some thing like
This is a test message
I get
This is a test <b>message</>
Any help would be awesome.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
The problem is that you are putting HTML in to a text node, so it is being evaluated strictly as text. One easy fix would be to simply operate on the innerHTML of the body element, like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var highLight = ['abcd', 'edge', 'rss feeds'],
contents = document.body.innerHTML;
for( i = 0; i < highLight.length; i++ ){
contents = delimiter(contents, highLight[i]);
}
document.body.innerHTML = contents;
}
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
A textNode cannot have child elements so it needs to be replaced, one way;
Replace
children[child].nodeValue = output;
With
var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);
Scenario : There is an input element in a HTML page where u can enter any numbers/text. If 2 consecutive characters are entered, then I am calling showModalDialog() method to open a pop up window which is having another input element. Whatever the characters entered in parent page will be copied to that search box.
Issue : If user types a text fast(without break) for searching with more than 2 characters (for ex. apple) then 3rd and/or 4th character/s typed are missed out(not traced by keyUp event). I mean only aple word is copied into search box present in pop up. So user need to retype the text.
Solution needed : Whenever user types any text, pop up needs to be triggered and all the characters need to be copied into search box in pop up
Environment : Reproducing only in IE9
Languages : HTML, Javascript
Note : What I have analysed is, since there is a delay in triggering pop up window, characters typed after 2 charaters are missed out. I don't know why this is occuring only in IE9 also I can not upgrade to IE10 for resolving issue.
Still I am stucked up with this issue. Is there any alternative solution for this? Any other way to get all the functionality of modal dialog with some other element/s?
Here is the sample code snippet of parent HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Page</title>
<script type="text/javascript">
var checkSeq = new RegExp("[a-zA-Z]{2}", "i");
function handleShowModalPopUp(fieldValue){
if(checkSeq.test(fieldValue)){
window.showModalDialog("popUpPage.html", document.getElementById('searchElem').value, "");
}
}
</script>
</head>
<body>
Enter Search Term :
<input type="text" id="searchElem" value="" onkeyup="handleShowModalPopUp(this.value)">
</body>
</html>
Here is the pop up window HTML (popUpPage.html) :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search Dialog</title>
<script type="text/javascript">
function handleOnload(){
var searchVal = window.dialogArguments;
if(null!= searchVal){
document.getElementById('searchElem').value = searchVal;
}
}
</script>
</head>
<body onload="handleOnload()">
<input type="text" id="searchElem">
<input type="button" value="Search">
</body>
</html>
What you actually want to do is delay the opening of the popup until your user has stopped typing. Detecting if a user has stopped typing is simply a matter of detecting if nothing has happened in the time a keystroke could have happened. So instead of opening the modal window, open it only after a delay on the condition that no keystroke happened in the meantime.
Here is some code I cooked up that should help you. I've set the delay 500ms.
<html>
<head>
<script>
function DelayedPopup(delayThreshold) {
this.delay = delayThreshold;
this.lastSearchValue = undefined;
this.popEvent = 0;
}
DelayedPopup.prototype = {
needsDelay: function() {
return this.searchValue() != this.lastSearchValue;
},
searchValue: function() {
return document.getElementById('searchElem').value;
},
openPopup: function() {
window.showModalDialog("popUpPage.html", "");
},
popupOrDelay: function() {
if (this.needsDelay()) {
this.popup();
}
else {
this.openPopup();
this.popEvent = 0;
}
},
popup: function() {
this.lastSearchValue = this.searchValue();
if (this.popEvent) {
clearInterval(this.popEvent);
}
var self = this;
this.popEvent = setTimeout(function() { self.popupOrDelay(); }, this.delay);
}
};
var delayedPopup = new DelayedPopup(500);
</script>
</head>
<body>
<input type="text" id="searchElem" onkeyup="if (this.value.length > 2) delayedPopup.popup()">
</body>
</html>
I try to use for loop as the substitution of list all
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
relaced by
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('editBox'+i));
}
}
but it seems it doesn't work for me. How to correct it?
Below is fully working code without "for loop":
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> New Document </title>
<meta name="title" content="" />
<meta name="author" content="0xs.cn" />
<meta name="subject" content="" />
<meta name="language" content="zh-cn" />
<meta name="keywords" content="" />
<style type="text/css" >
/* default css rule */
body { font: 12px "Verdana"; }
</style>
<script type="text/javascript" >
// shortcut
function $(s){
return typeof s == 'object'?s:document.getElementById(s);
}
var dEdit = function(el){
var me = this;
this.save = function (txt){
el.innerHTML = txt;
};
this.edit = function (e){
var e = e || event;
var target = e.target || e.srcElement;
if(target.tagName.toLowerCase() == 'input'){
return;
}
var ipt = document.createElement('input');
ipt.value = target.innerHTML;
ipt.onkeydown = function(){
if((arguments[0]||event).keyCode==13){
me.save(this.value);
}
};
ipt.onblur = function(){
me.save(this.value);
};
target.innerHTML = '';
target.appendChild(ipt);
ipt.focus();
};
el.onclick = this.edit;
};
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
window.onload = init;
</script>
</head>
<body>
<span id="editBox">This is sample text.</span> <br/><br/>
<span id="editBox2">This is sample text 222.</span> <br/><br/>
<span id="editBox3">This is sample text 333.</span>
</body>
</html>
Change the ids on your span tags to "editBox0", "editBox1" and "editBox2". Also, you posted this exact same question not 20-30 minutes ago and someone gave you the correct answer then too.
You need to add # prefix for ID selectors. Change your code to:
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}
Among other issues like what happens when you call dEdit(...) on an empty jQuery object...
You need a # prefix to select an ID:
$('#editBox2')
Your loop goes from 0 to 1000 and editBoxN is not a valid ID selector, so you end with
new dEdit($('editBox0'));
new dEdit($('editBox1'));
new dEdit($('editBox2'));
...
change first editBox ID, the loop variable and add a hash to the jquery selector to match the IDs
function init(){
for(var i = 1; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}
The problem is the init is throwing an expection on the first value, since 'editBox0' does not exist. To fix this you can wrap each loop iteration in a try/catch.
e.g.
function init(){
for(var i = 0; i < 1000; i++){
try {
new dEdit($('editBox'+i));
} catch (e) {}
}
}
This way, if an id is undefined, the script still runs. Also, you should change <span id="editBox"> for <span id="editBox0"> or <span id="editBox1"> if you intend to have it assigned on the loop.