Adding JavaScript events to an HTML input - javascript

This code isn't working in Firefox but working on IE and Chrome. When I click inside the text box it runs the focusOut() and focusIn() functions. Is this behavior expected and is the syntax recommended?
<!doctype html>
<html>
<head>
<title>Page of Cage</title>
<meta charset="UTF-8">
<link rel="icon" href="mkx-logo.png" type="image/x-icon">
<script type="text/javascript">
function focusIn() {
alert("focus In!");
};
function focusOut() {
alert("focus OUT!");
};
</script>
</head>
<body>
<form>
Name:<input onfocus="focusIn()" onblur ="focusOut()" type="text" name="name"/> <br/>
<input type="submit" value ="submit"/>
</form>
</body>
</html>

Replace alert with console.log and watch your web browser console using the developer tools. Just like nnnnnn said in the comments.

Q:Why the code is not working?
A: onfocus is fired when focus is gained and onblur is fired when focus is lost. In your code when you focus on the textbox it generates onfocus and at the same time the alert box is generated and it has lost the focus. So, Both the function are launched.
Check out this Fiddle

Related

Why does Edge mask the onchange event handler when an input has an input event handler that changes the input's value?

In this HTML
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
</head>
<body>
Enter some number here:
<input type="number" min="0"
oninput="console.log(' on input ');
this.value = Math.abs(this.value);"
onchange="console.log(' on change');"/>
</body>
</html>
The input has 2 event handlers
input
change
However onchange is not called.
Note, the oninput handler changes the value of the input. If I remove
this.value = Math.abs(this.value);
both events are fired.
This behaviour seen in Microsoft Edge 44.17763.1.0 (Microsoft EdgeHTML 18.17763)
This does not happen in Chrome nor in Firefox.
Questions
What am I doing wrong?
Is this from an inherited large code base with many input's all with an oninput and an onchange. The onchange is not called. What is the most efficient way to fix this?
(Disclaimer:I'm no HTML / javascript expert.)
oninput event is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.
I try to test your sample code with MS Edge, Chrome and Firefox browser and I am able to produce the issue with MS Edge browser.
Looks like MS Edge browser is working little differently.
I notice that if you try to write the JS code in head part than it can help to solve this issue.
Example:
<!DOCTYPE html>
<html>
<body>
<input type="number" onchange="myFunction1(this.value)" oninput="myFunction(this.value)" />
<p id="demo"></p>
<p id="demo1"></p>
<script>
function myFunction(val) {
document.getElementById("demo").innerHTML = "oninput " + val;
}
function myFunction1(val) {
document.getElementById("demo1").innerHTML = "onchange " + val;
}
</script>
</body>
</html>
Output in MS Edge browser:
User need to press ENTER key or click somewhere else after changing the value to fire the event.

How to activate alert function in html

This is a basic question of javascript.
I'm doing my personal webpage. When people click the button ("botón") this message should appear: "clicked!"
My html5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
<link href="website.css" rel="stylesheet"/>
<script src="script.js"></script>
</head>
This is the specific part of the button:
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button>botón</button>
My javascript code: (stored in the file: "script.js")
$("button").on("click", function() {
alert("clicked!")
});
But i click and no message appear (Chrome or Firefox).
UPDATE 1:
Apparently, i was following a Jquery tutorial.
I need to do that in basic javascript. What should i do. Code examples are welcome.
UPDATE 2: Based on suggestions, my code still does not work.
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
My new script:
document.getElementById('myButton').addEventListener('click', function(){
alert('clicked');
}), false);
document.getElementById('myButton').addEventListener('click',function(){
alert('Clicked!');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
</head>
<body>
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
</body>
</html>
Make sure to place your script right in front of the closing </body> tag, the elements can't be found if the DOM isn't loaded at the time your script gets loaded:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
<link href="website.css" rel="stylesheet"/>
</head>
<body>
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
<script src="script.js"></script>
</body>
</html>
script.js
document.getElementById('myButton').addEventListener('click',function(){
alert('Clicked!');
});
You should add an id to your button, then:
document.querySelector("#mybutton").addEventListener("click",function(){
alert("BUTTON CLICKED");
});
Where mybutton is your button ID. Try to work with IDs so your DOM query isn't getting more than one element.
Example:
http://jsfiddle.net/fthupjpd/
EDIT: Don't use jQuery for that :)
You dont have the jquery lib in your html, but you are using $, which is part of jquery (it's the facade for the api/lib)
add:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
before you cann you click code. You need to also make sure the dom has loaded when you call you event handler, try:
$(function () {
$("button").on("click", function() {
alert("clicked!")
});
});
IF you dont want to use jQuery, give your button an id
<button id="myButton">botón</button>
then in your code
document.getElementById('myButton').addEventListener('click', function(){
alert('clicked');
}), false);
Here are the docs on native event handlers
document.getElementById('myButton').onclick=function(){
alert('clicked');
};
For a good start with JavaScript, I find W3schools very good:
http://www.w3schools.com/js/default.asp
EDIT
see Michael's answer for where to place your scripts when you need them to access the document elements. The body needs to be loaded before you can reference them on your JS code.
You have two problems.
You haven't defined $. It looks like you are trying to use the jQuery library. You need to include that in your page before the script.
You are trying to bind an event handler to all the button elements in the document while the head section is being parsed. At that point, there is no button elements. You need to move the script element to after the button elements (or use a ready or load event hander).

Display input title only "onclick" event

I'm having trouble in displaying my title input only "onclick" event.
When we mouseouver the input box, it will display the title, but i just want this to happen when I click on the input box.
My idea is displaying a title saying "value copied", cause I have a function on "onclick" event that copy the input (read only) value to the clipboard, and when it's done I want to let the user know that this happen displaying that information.
Is that even possible?
(this is for a windows gadget)
Thank you to everyone.
Try .focus()
<!DOCTYPE html>
<html>
<head>
<style>span {display:none;}</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<p><input type="text" /> <span>focus fire</span></p>
<p><input type="password" /> <span>focus fire</span></p>
<script>
$("input").focus(function () {
$(this).next("span").css('display','inline').fadeOut(1000);
});
</script>
</body>
</html>
http://api.jquery.com/focus/

Get selected text on IPad 2 with Javascript

I'am developing a web-application that allows to select parts of an html document and put some kind of annotation on it.
To get hold of the selected text I use window.getSelection() which works pretty fine in IE9, FF, and Safari.
However I run into trouble when using the same page on my IPad 2:
If I just select a word by tapping it for a sec, window.getSelection() returns the proper selection.
If I create a text range ( as discribed here http://blog.laptopmag.com/how-to-select-copy-and-paste-text-on-the-ipad ) always return "null".
I've already examined the window, document and related event objects - but without success...
Any help would be really appreciated!
Edit: Just a small example. Select a text and press the button. On Safari (PC) the function prints the selected value...
<html>
<body>
<script>
function a()
{
alert(window.getSelection());
}
</script>
Hello World! <input type="button" onclick="a();"
</body>
</html>
Okay finally I've solved the problem: As Tim assumed the click events causes to selection to collapse. I consider this as rather strange behavior as on regular Safari this does not happen.
However, the solution is not to use the click event. Instead of I'm using "vlick" provided by the jquery mobile.
Full working example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
</head>
<body>
Hello World! <input type="button" id="button1" />
<script>
function a()
{
alert(window.getSelection());
}
$("#button1").bind("vclick",a);
</script>
</body>
</html>

I get an undefined error in my error console

My myclickHandler function works perfectly but when I go on to my error console I get this error:
document.getElementsByName("prequestion")[0] is undefined;
Below is my code
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
if(validation()){
openSessionPopup();
}
</script>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>10: </strong><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="myClickHandler()"/></p>
</form>
</body>
My question is what do I need to remove this error? because my function works does it matter if it shows an error in the error console?
Chances are you're loading the javascript before the DOM (or even possibly the HTML) has loaded properly.
For example, the following reproduces the same error as described in your question :
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
}
</script>
<input type="" name="prequestion" />
Whereas the following does not. The error is not present and the code works fine.
<input type="" name="prequestion" />
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
}
</script>
Trying to attach the event listener to an element which doesn't technically exist yet causes problems. You can check for the browser reporting the page has been loaded before attaching the event if needs be but be aware that browsers report this in different ways. Librarys such as jQuery provide useful means to test this such as $(document).ready(function(){});
Edit: I've just seen that you've added the relevant HTML too. It appears that this is in fact the case and the reason you're still seeing the expected behavior is because you're also using the onclick="" attribute on the input element. This is where the function is being called on click, and the event handler isn't being attached as you expect.
Edit #2: You also appear to be missing a closing } for your function. And I've now tested with your exact HTML and moving the script to just above the body tag resolves the error and correctly attaches the function to the click event.
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>10: </strong><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" /></p>
</form>
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
} // This was missing
</script>
</body>
I suspect that the problem is that there are no elements with the name attribute set to "prequestion".
If you're getting that error, then your script doesn't actually work, so you should fix it.

Categories