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>
Related
This question already has answers here:
How to prevent a click on a '#' link from jumping to top of page?
(24 answers)
Closed 2 years ago.
I'm student and it hasn't been long since I studied programming.
below code is simplified than real for explain.
'test()' is actually Ajax function to get data.
My goal is making 'a tag' for paging operation.
But when i clicked 'a tag', 'test()' inside of '$(document).ready' is called after 'a tag' click event occurred.
So page is always back to 1.
I don't know why this happen.
Anyone could help me?
Thank you!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
var page = 1;
$(document).ready(function(){
test();
alert(page);
});
function test(){
for(var i = 1; i <= 3; i++) {
var a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
a.preventDefault;
$(a).click(function(){
page = $(this).attr("idx");
test();
alert(page);
});
$("#pageLink").append(a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>
For some reason you're calling test() inside of test(). There are a few minor things you need to change also
Prefix jQuery objects with $. var $a=... to avoid ambiguity.
preventDefault is used on the event, not the jQuery object. $a.click(function(event){event.preventDefault();...});
Otherwise it works as I believe you want it to, alerting the page number on click.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
createLinks();
});
function createLinks(){
for(var i = 1; i <= 3; i++) {
var $a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
$a.click(function(event){
event.preventDefault();
page = $(this).attr("idx");
// why are you calling this again? // test();
// maybe you want to load something // loadSomething(page);
alert(page);
});
$("#pageLink").append($a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>
Edit: Just confirming: I want what the user typed to be saved so that when he reloads/leaves the webpage and comes back what he wrote earlier is still there.
I tried using cookies but it only put one line of Default(variable) when I reloaded the page. Im trying to get it to work with localStorage now but it sets the textarea to "[object HTMLTextAreaElement]" or blank when I reload. I read that this error can be caused by forgetting to add the .value after getElementById() but I did not make this mistake. I am hosting and testing the webpage on Github(pages). What am I doing wrong? here is the code(ignore the comments also it might not work in jsfiddle bc it localstorage didn't work there for me):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>le epic web page</title>
</head>
<body><!--
= "\n"-->
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
<script>
var Default="P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if(localStorage.getItem("P") == ""){
document.getElementById("txt").value=Default;
localStorage.setItem("P")=Default;
}else{
document.getElementById("txt").value=localStorage.getItem("P");
}
//update cookie (called when typed)
function save(){
var txt=document.getElementById("txt").value;
//txt=txt.replace(/\r\n|\r|\n/g,"</br>");
localStorage.setItem("P",txt);//set cookie to innerHTML of textArea, expires in 1 day
}
//when page closed/reloaded
window.onbeforeunload = function(){
localStorage.setItem("P",txt);//update cookie when page is closed https://stackoverflow.com/a/13443562
}
</script>
</body>
</html>
When you are exiting the page, you are referencing the text element and storing that in localstorage. Since localStorage is a string it converts the html element reference into the text you see.
window.onbeforeunload = function(){
localStorage.setItem("P",txt);
}
You are doing it correctly with save, so just call save with the beforeunload event
window.addEventListener('beforeunload', save);
Another bug in the code is the line
if(localStorage.getItem("P") == ""){
when localStorage is not set, it returns null. So the check would need to be a truthy check ( or you can check for nullv)
if(!localStorage.getItem("P")){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>le epic web page</title>
</head>
<body>
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
</body>
<script>
const Default =
"P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if (
localStorage.getItem("P") === "" ||
localStorage.getItem("P") === null ||
localStorage.getItem("P") === undefined
) {
localStorage.setItem("P", Default);
} else {
let currentValue = document.getElementById("txt");
currentValue.value = localStorage.getItem("P");
}
function save() {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
}
window.onbeforeunload = function () {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
};
</script>
</html>
I am new to Javascript.
I am making my first Adventure Game.
I tested the following code out with an onClick and it worked fine:
// JavaScript Document
function changeColour()
{
if (document.getElementById('colourTest').style.backgroundColor='yellow')
{
document.getElementById('colourTest').style.backgroundColor='red';
}
else
{
document.getElementByID('colourTest').style.backgroundColor='yellow';
}
}
var direction;
direction = prompt("Which direction would you like to go ?");
if ( direction == "North" )
{
changeColour();
}
else
{
console.log("You can't go in that direction ?");
}
This is the HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script language="javascript" type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body>
<div id="colourTest">
</div>
</body>
</html>
I want the Yellow div to turn red when the user enters the word North, otherwise, the user is told that they can't go in that direction.
I am sure that this is some kind of syntax error :D
Hi, Here is an update:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<script type="text/javascript" ></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body onload="load();">
<img id="myimg" alt="My Image" src="images/image1.jpg" />
<form>
<input name="heading" type="text" id="which" value="" />
</form>
</body>
</html>
Here is JS:
// JavaScript Document
var img = new Image();
img.src = "images/image1.jpg";
function whichImage(b)
{
var image = document.getElementById("myimg");
if (b == "North")
{
image.src = "images/image2.jpg";
}
else
{
image.src = "images/image1.jpg";
}
}
function whichDirection (x)
{
if (x == "North" || x == "South" || x == "East" || x == "West" )
{
document.write("You choose to go " + direction);
}
else
{
document.write("You can't go in that direction");
}
}
function load()
{
var direction = document.getElementById('which').value;
whichDirection(direction);
whichImage(direction);
}
I don't understand why the input direction from the user isn't allowing the image to change to image2.jpg, when the word, North is input by the user.
Can JS actually capture text input from html and then use this with variables in functions?
More over, with this version, the DOM doesn't seem to have loaded, as there is no image to be seen.
The two errors I see right away (there may be more) are...
if (document.getElementById('colourTest').style.backgroundColor='yellow')
You're assigning instead of comparing. Use == for comparison (as you do elsewhere). And...
document.getElementByID('colourTest').style.backgroundColor='yellow';
JavaScript is case-sensitive. The function name should be getElementById (as you do elsewhere).
In this case there was a logical error and a syntax error. The latter can often be noticed by looking at the JavaScript console in your browser's debugging tools. If it tried to execute that line of code, you'd see an error there. Logical errors, on the other hand, can be trickier to pinpoint. For those you'll want to familiarize yourself with the debugger in your browser's debugging tools.
You can click on a specific line of JavaScript code to set a "breakpoint" where the execution of code will pause. Once paused, you can examine the runtime values of your variables, step through the execution line-by-line to check its behavior, etc. This is how you validate that the code is doing what you expect it to do.
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';
}
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.