how to write onblur and onfocus event in javascript? - javascript

Question:
<body onload="setBlurFocus()">
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
</body>
I wrote :
function setBlurFocus () {
var user_input = document.getElementById('id_username');
var email = document.getElementById('id_email');
var password = document.getElementById('id_password');
user_input.onblur = userSetBlur();
email.onblur = emailSetBlur();
password.onblur = passSetBlur();
user_input.onfocus = function() {
document.getElementById('id_username').value = ''
}
email.onfocus = function() {
document.getElementById('id_email').value = ''
}
password.onfocus = function() {
document.getElementById('id_password').value = ''
}
}
function userSetBlur() {
document.getElementById('id_username').value = 'Username'
}
function emailSetBlur() {
document.getElementById('id_email').value = 'Email'
}
function passSetBlur() {
document.getElementById('id_password').value = 'Password'
}
Question?
How to generalize or optimized this code?

You can always attach the methods in JavaScript:
function setBlurFocus() {
var user_input = document.getElementById('id_username');
user_input.onblur = someFunction;
// or with an anonymous function:
user_input.onfocus = function() {
// do something
}
}
Read more about traditional event handling and events in general.
Further explanation:
You attached the function setBlurFocus to the load event of the document. This is correct if you have to access DOM elements with JavaScript. The load event is fired when all the elements are created.
If you attach the setBlurFocus() to the blur event of the input field, then the function is only executed when the text box looses focus.
From your question I concluded you don't want set the event handlers in the HTML, but you want to set them form inside the setBlurFocus function.
Regarding your update:
This is wrong:
user_input.onblur = userSetBlur();
This assigns the return value of the function to onblur. You want to assign the function itself, so you have to write:
user_input.onblur = userSetBlur;
The () calls the function. You don't want that (in most cases, there are exceptions, see below).
Furthermore, you don't have to use named functions for onblur and anonymous functions for onfocus. It was just an example, to show you the different possibilities you have. E.g. if you assign an event handler to only one element, then there is no need to define it as extra function. But you have to do this if you want to reuse event handlers.
Here is an improved version:
function setBlurFocus () {
var values = ["Username", "Email", "Password"];
var elements = [
document.getElementById('id_username'),
document.getElementById('id_email'),
document.getElementById('id_password')
];
for(var i = elements.length; i--; ) {
elements[i].onblur = setValue(values[i]);
elements[i].onfocus = emptyValue;
}
}
function setValue(defaultValue) {
return function(){this.value = defaultValue;};
}
function emptyValue() {
this.value = '';
}
this inside the event handlers refers to the element the handler is bound to.
Note: Here setValue returns a function, that is why we call setValue in this case (and not just assign it).
Important note: This will also reset the values to Username etc, if the user entered some data. You have to make sure, that you only reset it if the user has not entered data. Something like:
function setValue(defaultValue) {
return function(){
if(this.value !== "") {
this.value = defaultValue;
}
};
}
and you'd have to define emptyValue similar:
function emptyValue(defaultValue) {
return function(){
if(this.value === defaultValue) {
this.value = "";
}
};
}
Now that I know what you actually want to do, have also a look at HTML5's placeholder attribute.

Well you've tagged it with jquery so this is how to do it in jquery:
function setBlurFocus () {
//do stuff here
}
$('#id_username').blur(setBlurFocus);
or
$('#id_username').blur(function(){
//do stuff here
});

Regarding your update
I using jquery as you tab jquery, the code was bellow , you can check a live sample with this link :
http://jsfiddle.net/e3test/zcGgz/
html code :
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
javascript code :
$(function(){
var selector = {
username: $('#id_username'),
email: $('#id_email'),
password: $('#id_password')
};
for (var x in selector) {
selector[x].focus(function(){
$(this).val('');
}).blur(function(){
$(this).val($(this).attr('name'));
});
}
});
Hope it help.

Related

Cannot read property 'input' of null at HTMLDocument.<anonymous> Javascript/HTML 2 part login error

I am trying to create a 2 part login, 1st part where you enter the username, click login, and the login takes you to a page where you enter your password. I have a js function where I check if the username field is null, because I want to require the user to enter something in the text field before clicking the button redirects them to the second part of the login. However, I am getting an error: Uncaught ReferenceError: loginCheck is not defined at HTMLInputElement.onclick
here is my code
var formhtml = '<div class="container"><label for="userNameBox"><b>Username </b></label><input type="text" id="userNameBox" placeholder="Enter Username" required ="required"><br></br> <input type="button" id ="loginButton" value="Login"onclick="javascript:loginCheck()"/></div>'
function loginCheck(){
var x = null;
if(document.getElementById("userNameBox").value !=null){
document.getElementById("loginButton").onclick = function () {
location.href = "myLogin.Part2";
}
}
else{
alert("username required");
location.reload();
}
}
$('.login').click(function(e)
{
e.preventDefault();
if ($('#loginbox').html() == '')
$('#loginbox').html(formhtml);
$('#loginbox').show();
return false;
});
You seem to be mixing a lot of Vanilla JavaScript and jQuery. Although that's not wrong, it might help you with development by choosing one or the other.
Like #Teemu said, the value of an input is never null. If it is empty than the value will be represented as an empty string "".
The loginCheck function will add an event listener to the loginButton element. But that element already has an onclick attribute which calls the loginCheck function. This will not run as you would like it to. Instead of both add an event listener with either addEventListener (Vanilla JavaScript) or with the on method (jQuery)
I've tried to convert your code so that it uses jQuery. Check it out and let me know if your problem has been resolved.
const $document = $(document);
const $login = $("#login");
const $loginBox = $("#loginbox");
const $formElement = $(`
<div class="container">
<label for="userNameBox"><b>Username </b></label>
<input type="text" id="userNameBox" placeholder="Enter Username" required="required"><br>
<input type="button" id="loginButton" value="Login"/>
</div>
`);
$document.on("click", "#loginButton", function() {
const $userNameBox = $("#userNameBox");
if ($userNameBox.val() !== "") {
location.href = "myLogin.Part2";
} else {
alert("username required");
location.reload();
}
});
$login.on("click", function (event) {
if ($loginBox.children().length === 0) {
$loginBox.append($formElement);
}
$("#loginbox").show();
event.preventDefault();
return false;
});

Having trouble displaying an array value within console.log event using .push function in Jquery

The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">

i have code that can be use for subtract the textbox values using javascript?

i have code that can be use for subtract and additional textbox values using javascript and it is working but problem is that javascript again and again executed function whenever onfocus textbox i want only one time javascript should be executed function?
javascript function again and again additional onMouseOver="return B(0);"
javascript function again and again subtraction onfocus="return C();"
javascript function again and again additional onfocus="return D();"
function getObj(objID){
return document.getElementById(objID);
}
function B(){
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
}
function C() {
getObj("balance").value=parseFloat(getObj("total").value || 0)-
(parseFloat(getObj("advance").value || 0)) ;
getObj("balance").value=parseFloat(getObj("balance").value || 0)-
(parseFloat(getObj("discount").value)||0) ;
return false;
}
function D() {
getObj("total").value=parseFloat(getObj("total").value || 0)+
(parseFloat(getObj("openbal").value || 0)) ;
return false;
}
Opening Balance:<input class="input_field2"
type="text" name="openbal" id="openbal"><br />
Total:<input class="input_field2" type="text"
readonly name="total" id="total" value="5000"><br />
Advance:<input class="input_field2" type="text"
readonly name="advance" id="advance" value="500"
onMouseOver="return B(0);"><br />
Balance:<input class="input_field2" readonly type="text"
name="balance" id="balance" onfocus="return C();"><br />
Rem Amount:<input class="input_field2" type="text"
name="recamt" id="recamt"><br />
Discount: <input class="input_field2"
style="background-color:#FFF !important;"
type="text" name="discount" id="discount" >
You could have:
var executedAlready = false;
An inside functions B and C have:
if(executedAlready != true){ executedAlready = true; }
else { return; }
Or maybe you could detach the events instead? I guess there are a few different ways to do this.
What the other answers tell you that the "quickest" way to get results is to make your functions only execute once.
You can do that like this:
Make a flag (just a variable that knows if your function has been triggered already).
When executing your functions, first check on this flag.
Here's an example how to do it with function B():
(Note: I didn't change your function, don't wanna get into that now)
// setup fired as false
var hasBFired = false;
function B(){
// if B is true, we do nothing
if (hasBFired) {
return;
// else if it is not true, basically only the first time you call this, flip the flag and execute the rest of the code.
} else {
hasBFired = true;
}
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
Now, repeat the same with C and D functions (setup two more flags).
This is not the best way - it's not good to setup global objects and stuff, but since you probably aren't getting any side library in, it will help you solve your issue for now. For long term solution, you should use an Event library (like YUI Event) and have it handle attaching and detaching actions to onfocus events for you.
you can use one or more flag(s) :
in the begenning of the page :
<script>
var flag = false;
</script>
and on your element:
<div .... onMouseOver="if(!flag) { flag = true; return B(0);}" > .... </div>
same for onFocus...

How to convert from javascript form action to jquery?

I have a code javascript of a action form:
<form name="myform" onsubmit="return OnSubmitForm();" method="post">
<input type="text" value="" id="type" />
<input type="submit" value="submit" />
</form>
And javascript:
function OnSubmitForm() {
var type = document.getElementById('type').value;
if(type == '1') {
document.myform.action = "index.php?type=1";
}
if(type == '2') {
document.myform.action = "index.php?type=2";
}
return false;
}
How to convert this javascript to jquery, please this ideas?
$("form[name='myform']").submit(function() {
this.action = "index.php?type=" + this.type.value;
return false;
});
form[name='myForm'] selects a form with the name myForm.
Calling .submit(function () { ... }) binds an event handler for the submit event.
Inside the function, this refers to the form.
Example: http://jsfiddle.net/4SZrH/ (check out the form action in Firebug or similar).
First note that this function always returns false, so your form will never submit. But to answer your question, you could use jQuery's submit event
$("form[name='myform']").submit(function(){
var type = this.type.value;
if (type === '1' || type === '2')
this.action = "index.php?type=" + type;
return false;
});
Or more simply:
$("#myForm").submit(OnSubmitForm);
Also note that, for dom level 0 event handlers, you don't want the return statement inline. In the future just do
<form name="myform" onsubmit="OnSubmitForm();"
And let OnSubmitForm return true or false
Finally, note that in JavaScript, functions starting with a capital letter by convention denote a constructor. Consider renaming this function to onSubmitForm

Delete default value of an input text on click

I have an input text:
<input name="Email" type="text" id="Email" value="email#abc.example" />
I want to put a default value like "What's your programming question? be specific." in Stack Overflow, and when the user click on it the default value disapear.
For future reference, I have to include the HTML5 way to do this.
<input name="Email" type="text" id="Email" value="email#abc.example" placeholder="What's your programming question ? be specific." />
If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see JQuery HTML5 placeholder fix « Kamikazemusic.com for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.
Also, the provided link is a well-tested and well-developed solution, which should work out of the box.
Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder-attribute and a JavaScript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the jQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus and onblur events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="email#abc.example" name="Email" id="Email"
onblur="if (this.value == '') {this.value = 'email#abc.example';}"
onfocus="if (this.value == 'email#abc.example') {this.value = '';}" />
This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>
Using jQuery, you can do:
$("input:text").each(function ()
{
// store default value
var v = this.value;
$(this).blur(function ()
{
// if input is empty, reset value to default
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
// when input is focused, clear its contents
this.value = "";
});
});
And you could stuff all this into a custom plug-in, like so:
jQuery.fn.hideObtrusiveText = function ()
{
return this.each(function ()
{
var v = this.value;
$(this).blur(function ()
{
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
this.value = "";
});
});
};
Here's how you would use the plug-in:
$("input:text").hideObtrusiveText();
Advantages to using this code is:
Its unobtrusive and doesn't pollute the DOM
Code re-use: it works on multiple fields
It figures out the default value of inputs by itself
Non-jQuery approach:
function hideObtrusiveText(id)
{
var e = document.getElementById(id);
var v = e.value;
e.onfocus = function ()
{
e.value = "";
};
e.onblur = function ()
{
if (e.value.length == 0) e.value = v;
};
}
Enter the following
inside the tag, just add onFocus="value=''" so that your final code looks like this:
<input type="email" id="Email" onFocus="value=''">
This makes use of the javascript onFocus() event holder.
Just use a placeholder tag in your input instead of value
we can do it without using js in the following way using the "placeholder" attribute of HTML5
( the default text disappears when the user starts to type in, but not on just clicking )
<input type="email" id="email" placeholder="xyz#abc.example">
see this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_placeholder
<input name="Email" type="text" id="Email" placeholder="enter your question" />
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).
The short hint is displayed in the input field before the user enters a value.
Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.
I think this will help.
Why remove value? its useful, but why not try CSS
input[submit] {
font-size: 0 !important;
}
Value is important to check & validate ur PHP
Here is a jQuery solution. I always let the default value reappear when a user clears the input field.
<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="email#abc.com" />
<script>
$("#Email").blur(
function (){
if ($(this).val() == "")
$(this).val($(this).prop("defaultValue"));
}
).focus(
function (){
if ($(this).val() == $(this).prop("defaultValue"))
$(this).val("");
}
);
</script>
I didn't see any really simple answers like this one, so maybe it will help someone out.
var inputText = document.getElementById("inputText");
inputText.onfocus = function(){ if (inputText.value != ""){ inputText.value = "";}; }
inputText.onblur = function(){ if (inputText.value != "default value"){ inputText.value = "default value";}; }
Here is an easy way.
#animal represents any buttons from the DOM.
#animal-value is the input id that being targeted.
$("#animal").on('click', function(){
var userVal = $("#animal-value").val(); // storing that value
console.log(userVal); // logging the stored value to the console
$("#animal-value").val('') // reseting it to empty
});
Here is very simple javascript. It works fine for me :
// JavaScript:
function sFocus (field) {
if(field.value == 'Enter your search') {
field.value = '';
}
field.className = "darkinput";
}
function sBlur (field) {
if (field.value == '') {
field.value = 'Enter your search';
field.className = "lightinput";
}
else {
field.className = "darkinput";
}
}
// HTML
<form>
<label class="screen-reader-text" for="s">Search for</label>
<input
type="text"
class="lightinput"
onfocus="sFocus(this)"
onblur="sBlur(this)"
value="Enter your search" name="s" id="s"
/>
</form>

Categories