How not to lose focus on a login page - javascript

I have a simple login form with 2 input fields: "username" and "password".
"username" field is focused by default. The problem is that when user clicks outside "username" or "password" fields, the focus is gone (it is neither on "username" nor on "password" fields"). How can I force the focus to be on these 2 fields only ?
In my case, this is a really annoying behavior, so I really want to do this :)
Can I do something like:
$("*").focus(function() {
if (!$(this).hasClass("my_inputs_class")) {
// How to stop the focusing process here ?
}
});
?

It sounds like you always want one of your inputs to be focused, fair enough. The way I would do this is to bind each of your inputs blur() events so that if it occurs, it goes to the next element.
Here's the markup:
<body>
<form method="POST" action=".">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
And here's the jQuery:
$(document).ready(function() {
// what are the named fields the user may focus on?
var allowed = ['username', 'password', 'submit'];
$.each(allowed, function(i, val) {
var next = (i + 1) % allowed.length;
$('input[name='+val+']').bind('blur', function(){
$('input[name='+allowed[next]+']').focus();
});
});
$('input[name='+allowed[0]+']').focus();
});

You could use javascript to set the focus on focusout, but you really shoudn't. Forcing focus on those fields would break the normal interaction of the page. It would mean a user couldn't do something as simple as clicking on a link on the page, because focus would always be on those inputs.
Please don't do it :)

If you really really want to do this (and you shouldn't) use delegate() instead of setting a separate event handler on every single HTML element:
$('body').delegate('*', 'focus', function() {
if (!$(this).hasClass("my_inputs_class")) {
$('#username').focus();
return false;
}
});
But consider that this will make unacessible all elements except the two input fields via keyboard navigation (including the submit button, any links on the page etc.)

Set blur event handler so it brings back focus to one of your inputs.

You could do like this (in psuedo code):
if user || pass blured
if user.len > 0
pass.setFocus
else
user.setFocus
Hope you get it.

Install an onClick handler on the body element (or a div that covers most of the page). Clicking on the div should then set the focus on the username/password field.
I also suggest to bind Return in the "username" to "Set focus on password" and Return in the "password" field to "Submit form".

You could enable the click on links by re-focusing on you inputs after a minimum time interval.
Every time an object gains the focus you check if it has the required class: if not set the focus to the first of the form inputs; this way:
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js" />
<script type="text/javascript" >
$(function() {
$('*').focus(function() { var obj = this; setTimeout(function () {checkFocus(obj)}, 1)});
})
function checkFocus(obj) {
if (!$(obj).hasClass('force_focus')){
$('input.force_focus:first').focus()
}
}
</script>
</head>
<body>
Extrnal link
<form><div>
User: <input type="text" name="user" class="force_focus"/><br/>
Password: <input type="password" name="password" class="force_focus"/><br/>
Other: <input type="text" name="other" class=""/><br/>
<input type="submit" name="submit" value="Login" />
</div></form>
</body>
</html>

this is only an idea, you can use a setInterval function to put the focus in the username field, and you can interrupt it when you want with clearInterval function.
var A = setInterval(function(){ $('#username').focus();}, 100);
... and for interrumpt it, you can do something like this
$('#password').focus(function(){ clearInterval(A);});

Related

I can't get form submit to work in html / JavaScript

I have tried a bunch of different things as well as searching and googling but I just can't see how to make some very basic code work.Trying to let the user submit text input.
This code below should just change the first paragraph to say working.
<HTML>
<CENTER>
<BR>
<H1>Test</H1>
<BR>
<p id="ParaOne"></p>
<BR>
<input type="text" id="TextInput" Value="" onsubmit="Test">
<script>
var CharOne = ["name"]
function Test() {
document.getElementById("ParaOne").innerHTML = "Working";
}
document.getElementById("ParaOne").innerHTML = "Enter Name:";
</script>
</HTML>
Ideally I would able to save whatever they entered into a variable and then display the entered name but as of now I can't get anything to work. not even a basic function to update the paragraph to sy working.
There is no onsubmit event for the textbox. You can use that event on the form (which I don't see in your question). Although not required, I would also add a submit button, because that's a better design.
Also it's wasteful to assign an initial value to ParaOne in JavaScript, simply type the value inside the element.
<form onsubmit="Test();">
<p id="ParaOne">Enter Name:</p>
<input type="text" id="TextInput">
</form>
<script>
function Test() {
document.getElementById("ParaOne").innerHTML = "Working";
}
</script>
Important note: Although the code above is how you should do it, I don't really see the point. The form will be submitted immediately after changing the text of ParaOne which will reload the page and you will see the initial value again (and probably think it didn't work). It will work but very fast so nobody will really see it, so what's the point?
You can use the javascript methods onchange or onkeydown to trigger input from the input field, you don't need to submit a form. But in case you needed just that I added the example. I used jQuery instead of plain javascript to write the functions because now they practically become one-line functions.
onchange will wait for the user to press enter or for the input element to loose focus to call the function.
onkeydown will call the function on every key press.
e.preventDefault() cancels the default action of the element, which in this case is a submit action, and lets us make the decision through code whether to submit or not.
Below are some javascript/jQuery test functions and a sample HTML file so you can test out what works best for you.
EDIT: I added some examples on how to store the current value of an input field into a variable
// get the Value of input element directly into a variable
var myVariable = $('#theInput_1').val();
// myVariable will return empty string since the input element is empty
console.log('This is the starting value of the 1st input element: ' + myVariable);
// Function for onkeydown test
function testKeyDown()
{
// stored in a variable which is not available outside the function
var myVariable = $('#theInput_1').val();
$('#paraOne').text(myVariable);
// test output - $('#theInput_1').val() will return empty
console.log('This is the changed value of the 1st input element: ' + myVariable);
}
// Function for onchange test
function testOnChange()
{
$('#paraTwo').text($('#theInput_2').val());
}
// Function for submit test
$( "#submit" ).on( "click", function(e)
{
e.preventDefault(); // Prevents default action of submit
$('#paraThree').text($('#theInput_3').val());
});
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<p id="paraOne">This text will be replaced on success.</p>
<input type="text" id="theInput_1" onkeydown="testKeyDown();" size="50" value="" placeholder="onkeydown test" />
<p id="paraTwo">This text will be replaced on success.</p>
<input type="text" id="theInput_2" onchange="testOnChange();" size="50" value="" placeholder="onchange test" />
<p id="paraThree">This text will be replaced on success.</p>
<form>
<input type="text" id="theInput_3" size="50" value="" placeholder="form submit test" />
<input type="submit" id="submit" value="Submit me" />
</form>
</body>
</html>

Jquery toggle input visibility on click and focus

Hello I am working on a simple form that also uses place-holder text. I am implementing this behaviour with JQuery and not html attributes, mainly because the place-holder input also shows error messages to the user which need to be styled differently than plain place-holder text.
Right now the form behaves like this.
Clicking on the input hides the the place-holder input and sets focus on the main input field.
If the user has entered data then the place-holder does not show up.
Now this is all fine, but when the user presses the TAB key to change focus, none of the above happens.
Here is the relevant JQuery code and the HTML:
$("#plh_username").click(function(){
$(this).hide();
$("#username").focus();
});
$('body').click(function(e){
var target = $(e.target);
if(!target.is('#plh_username')) {
if ( $("#username").val() == "" ){
$("#plh_username").show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="input" id="plh_username" class="inp_placeholder" value="Username" />
<input type="text" name="username" id="username" value="" />
How can I achieve the same effect when the user selects an input field without actually clicking on one?
You could try using .focus() and .focusout() instead of .click().
$("#plh_username").focus(function(){
$(this).hide();
$("#username").focus();
});
$('#username').focusout(function(){
if ($(this).val() === ""){
$("#plh_username").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="input" id="plh_username" class="inp_placeholder" value="Username" />
<input type="text" name="username" id="username" value="" />
<input value="Press tab or shift+tab" />
Quote from the documentation:
Elements with focus are usually highlighted in some way by the
browser, for example with a dotted line surrounding the element. The
focus is used to determine which element is the first to receive
keyboard-related events.
Dont use .click(). Use .focus().
I think you are looking for onfocus event. This event triggers when a control gains the focus.
$("#plh_username").focus( function(){
alert("focus")
});
for example see http://jsfiddle.net/wb2vef0g/

Sending form text input to console.log for testing

I have a simple form with one text field for testing. I need to have the info the user types in sent to console.log for now. Is this possible and if so what would I write?
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>
var nameInput = document.getElementById('name');
document.querySelector('form.pure-form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
console.log(nameInput.value);
});
Not sure why this question was down-voted. It's basic, but it's still a perfectly valid question.
The simplest way would be to grab the input by the ID then grab it's value and console.log it.
So, in a separate JavaScript file which you are included, or in a block, you would use:
console.log(document.getElementById('name').value);
You'll probably want to hook that to some event as well, so it prints each time they do something. The "change" event is probably the most appropriate. It fires every time the user types something and then changes focus (sometimes it'll also trigger when they stop typing, but not usually). If you want it to print every time a letter changes, you would want to use (one of) the "keydown", "keyup" or "keypress" events instead.
document.getElementById('name').addEventListener('input', function() {
console.log(this.value);
});
Sure
var input = document.getElementById('name');
console.log(input.value);
Here it is with an on change event as well as a keyup (in case you need to see it somewhat 'live').
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" onChange="inputChange(event)" onKeyUp="inputChange(event)" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>
<script type="text/javascript">
function inputChange(e) {
console.log(document.getElementById("name").value);
}
</script>
you can create a function like this and get the value of text box by its id.
function getData() {enter code here
let search = document.getElementById("search").value;
console.log(search);
}

How to make Javascript focus() method work in onBlur event for input text box?

For me Javascript focus() method is working fine if I use it with a button and onClick event, but with onBlur from a text box, it is not working. Can anyone guide me on this?
<html>
<head>
<script type="text/javascript">
function displayResult()
{
var inp1=document.getElementById("text1").value;
var inp2=inp1.length;
if(inp2==0)
{
alert("Field 1 cannot be left Empty");
//document.getElementById("text1").value="";
document.getElementById("text1").focus();
}
}
</script>
</head>
<body>
<input type="text" name="text1" id="text1" onBlur="displayResult();"/>
<input type="text" name="yext2" id="text2" />
</body>
</html>
It's not possible to reapply focus to an element when its blur event triggers. Use a timer with an interval value of 0 to delay the call to focus until afterwards:
function displayResult() {
var inp1 = document.getElementById("text1").value,
inp2 = inp1.length;
if(inp2==0) {
alert("Field 1 cannot be left Empty");
//document.getElementById("text1").value="";
window.setTimeout(function () {
document.getElementById("text1").focus();
}, 0);
}
}
You need to set little delay in the focusing of the field.
setTimeout(function(){field.focus()}, 10);
like :
<html>
<head>
<script type="text/javascript">
function displayResult(obj)
{
var inp1=obj.value;
var inp2=inp1.length;
if(inp2==0)
{
alert("Field 1 cannot be left Empty");
setTimeout(function(){obj.focus()}, 10);
}
}
</script>
</head>
<body>
<form>
<input type="text" name="text1" id="text1" onblur="displayResult(this);"/>
<input type="text" name="yext2" id="text2" />
<input type="submit">
</form>
</body>
</html>
I advise you not to use onblur in validating inputs if you are display notification message as alerts. It's quite annoying , it produces endless alerts .
Validate form onsubmit event.
Since the time you posted the question, I experimented your issue for an hour using different techniques. It now seems to me that through an event on an input, you cannot set focus on itself.
Still, There is another possible workaround. You can call displayResult() when the form is submitted, check if text1 is empty and cancel submit if it is empty and set focus on text1. I have rewritten the code for you.
<html>
<head>
<script type="text/javascript">
function displayResult()
{
var inp1=document.getElementById("text1").value;
var inp2=inp1.length;
if(inp2==0)
{
alert("Field 1 cannot be left Empty");
document.getElementById("text1").focus();
return false;
}
}
</script>
</head>
<body>
<form onsubmit="return displayResult();">
<input type="text" name="text1" id="text1" />
<input type="text" name="yext2" id="text2" />
<input type="submit" />
</form>
</body>
</html>
Hope that helps...
Peace be upon you ...
There's no problem in calling focus() on blur event on the same element, if user tries to focus on any other element that does try to refocus itself on blur event (e.g. a button).
But, if there are more than one input elements of type text, password, number, etc., and all of them try to return focus to themselves on blur event, that causes a blur-focus loop between 2 or more elements.
Let us observe a simple example with 2 input elements of type text:
User fills-in the first input, but it is not valid (e.g. username does not contain at least 6 characters), then moves focus to the second input (presses tab key or clicks on the second input field);
Blur event triggers on the first input element and calls validation function, which tries to return the focus to the first input element, but that causes...
Blur event to trigger on the second input element and calls validation function which tries to return focus to the second input element, which further causes blur on the first input element...
This sequence of events may cause different behavior in different browsers, especially if there's also an alert dialog for each invalid input, but the result is obviously an infinite loop of blur and focus events on at least two input elements, even if calling focus() is delayed.
Thus, the easiest solution is to avoid refocusing itself on blur event.

Page Redirection

I'm working on a script where all I want it to do (right now) is redirect the user based on which button they press. Eventually it will take form input and incorporate that into the redirect, but right now I'm just trying to get the buttons to send the user off to the appropriate site. However, My redirects aren't working.
<html>
<head>
<title>
Home
</title>
</head>
<body>
<script type="text/javascript">
<!--
var textstring;
var btnWhichButton;
//Gets the text from the form
function getQ() {
textstring = document.forms['Search'].elements[0].value;
}
//Does a Google Search
function googleSearch() {
window.location ="http://www.google.com";
}
//Does a YouTube Search
function youtubeSearch() {
window.location = "http://youtube.com";
}
//Figure out which button was pressed
function whichButton() {
if (btnWhichButton.value == 'Google Search' ) {
googleSearch();
} else if (btnWhichButton.value == 'YouTube Search' ){
youtubeSearch();
}
}
//main function to run everything
function main() {
getQ();
whichButton();
}
// -->
</script>
<form name="Search" >
<input type="text" name="q" size="31" maxlength="255" value="" />
<input type="submit" value="Google Search" onclick="btnWhichButton=this; main();" />
<input type="submit" value="YouTube Search" onclick="btnWhichButton=this; main();" />
</form>
</body>
</html>
When either button is clicked, the page just reloads with ?q= appended to the url, it doesn't redirect. Any help?
You want to use a button not an input type='submit'. Your current buttons are submitting the form, not performing their onclick actions.
Or block the submit action in some way. Or you could use your functions to set the form action to the url and just let it submit.
Your scripts seem highly overcomplicated. Why not have three functions: getQ, googleSearch, and youTubeSearch? Then inside the onClick event you can call the exact function, including this.value inside the input parameters and calling getQ from inside that function? Your method seems highly inefficient. If you're going to have separate functions for each of them anyways, there's no use in going through two other functions in order to get to them.
A submit button will always submit the form without a return false at the end of the onClick event, and since the default posting method is GET, its attaching ?q= to the end of your URL because that field is blank and it's the only input field in the form.
For redirecting to new page you no need to use the big javascript function.
<html> <body>
<input type="button" value="Google Search" onclick="javascript:window.location.href='http://www.google.com'" />
<input type="button" value="You tube Search" onclick="javascript:window.location.href='http://youtube.com'" />
</body></html>
Please check whether it helps you.
Well as jasonbar says, change your input to be of type 'button' and not 'submit'. Plus, I'd rather use window.location.href instead of window.location only. I don't know possible this is good practice...happy programming.

Categories