Can't focus an input after "onblur" - javascript

I have three simple texts and I want to make a validation on "onblur" of the second text. It should delete the content just typed and keep focusing on the same input. I can make it delete the content, but it doesn't focus. What could be happening?
function validate() {
document.getElementById("txt-second").value = "";
document.getElementById("txt-second").focus();
}
<input type="text" id="txt-first" />
<input type="text" id="txt-second" onblur="validate();" />
<input type="text" id="txt-third" />

Strange that onblur doesn't work for me either.
<input type="text" id="txt-first"/>
<input type="text" id="txt-second"/>
<input type="text" id="txt-third"/>
<script>
function validate(event){
this.value = "";
this.focus();
}
var txtSeconds = document.getElementById("txt-second");
txtSeconds.onblur = validate;
</script>

Create a 'parent' function that has subroutines
<script>
var ele = document.getElementById("txt-second");
ele.onblur = function(){
ele.value="";
ele.focus();
}
</script>
If that doesnt work out, checkout this question Two onblur for same input id
Edit: I just tested your code out and it worked for me, problem is once it focuses I can't get the cursor out of that input box...

Related

How to validate a content of a field without pressing a button?

I need to validate the integrity of my email and I am doing it by pressing a "validate" button.
I wonder if there is a way to do the same without pressing a button? Say, just exiting the email field, clicking another field for example (field2)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Text Input Field Value in JavaScript</title>
</head>
<body>
<p >Enter an email address:</p>
<input type="text" placeholder="Type your email here..." id="myInput">
<br>
<input type="text" placeholder="Field 2" id="field2">
<br>
<button type="button" onclick="getInputValue();">Validate</button>
<script>
function getInputValue(){
// Selecting the input element and get its value
var inputVal = document.getElementById("myInput").value;
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// return re.test(inputVal);
resultat = re.test(inputVal);
// document.write(resultat);
if (resultat) {
alert(inputVal+" is valid");
} else {
alert(inputVal+" is NOT valid");
}
return false;
}
</script>
</body>
</html>
You could use the built in functionality of html via
<input type="email" required>
If you then applied css through the pseudo-class :invalid, you would see a visual hint.
input:invalid {
background-color: #ffdddd;
}
Check these ressources:
https://developer.mozilla.org/de/docs/Web/CSS/:invalid
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email
Look at onBlur event
const onBlur = () => {
const test = document.getElementById("test");
// here you have your value
test.value = test.value.toUpperCase();
}
<input type="text" id="test" onblur="onBlur()">
Hellma's answer is correct, HTML has this functionality and you'd be hard pressed to come up with an implementation better than the browsers. That said, if you need additional validation on top of what the browser provides you could use the blur event. Instead of the onclick attribute on your button, you could add an onblur attribute to your input to run the getInputValue function whenever the user's focus leaves that input element. This would look like
<input type="text" placeholder="Type your email here..." id="myInput" onBlur="getInputValue()">
You can use the keyUp event, try this:
function validate(e){
inputText = e.target.value;
console.log(inputText);
if(inputText == 'condition'){
console.log('condition passed!')
}
}
<input onkeyup="validate(event)">

how can i enable form's save button if fields have values in JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have simple html form (2 text fields & 1 selection set & save button)
i want to set this button to disable till the text fields and selection set have values, if these fields have values button become active when clicked it show alert message (I need this using JavaScript)
Try this one to enable the button if the two fields have values through JavaScript using the querySelector() method for the DOM manipulation.
var submitBtn = document.querySelector('#submitBtn');
var nameInput = document.querySelector('#nameInput');
var addressInput = document.querySelector('#addressInput');
var myOption = document.querySelector('#mySelect');
function validateInputs() {
if (nameInput.value && addressInput.value && myOption.value)
submitBtn.disabled = false;
else
submitBtn.disabled = true;
}
function showData(){
alert("Data is :"+nameInput.value);
}
<form>
<label for="nameInput">Name</label>
<input id="nameInput" type="text" name="name" onkeyup="validateInputs();" required>
<label for="addressInput">Address</label>
<input id="addressInput" type="text" name="address" onkeyup="validateInputs();" required>
<br><br>
<select onchange="validateInputs();" id="mySelect">
<option disabled selected value> -- select an option -- </option>
<option>New York</option>
<option>Chicago</option>
</select>
<br><br>
<button id="submitBtn" onclick="showData();" disabled>Submit</button>
</form>
This worked for me.
var errors = 0;
$('#idOfYourSubmitButton').prop('disabled', true); //Make your button disabled
$('#idOfYourFirstTextField').keyup(function(){ //triggered when keyup is detected on the text field
if($(this).val().length < 0) { //Check if Text field is empty
errors += 1; //add an error
}
else { //if text field is not empty
errors -= 1; //remove error
}
);
$('#idOfYourSecondTextField').keyup(function(){ //triggered when keyup is detected on the text field
if($(this).val().length < 0) { //Check if Text field is empty
errors += 1; //add an error
}
else {
errors -= 1; //remove error
}
);
if(errors <= 0) { //check if there are any errors
$('#idOfYourSubmitButton').prop('disabled', false); //remove disabled from the button
}
If you want to go the jQuery route, you could do it this way
You'll notice that if you do it this way, the button will disable again if any of the form info is deleted.
$('.js-get-info').on('mouseover keyup', (event) => {
if ($('.js-name').val() && $('.js-age').val() && $('[name=sex]:checked').val()) {
$('.js-submit').prop('disabled',false);
} else {
$('.js-submit').prop('disabled',true);
}
})
<!doctype html>
<html>
<head>
</head>
<body>
<form class='js-get-info'>
<input class='js-name js-input' placeholder='Name'>
<br>
<input class='js-age js-input' placeholder= 'Age'>
<br>
<label for='female'>Female</label>
<input type='radio' class='js-input js-sex-input' id='female' name='sex'>
<label for='male'>Male</label>
<input type='radio' class='js-input js-sex-input' id= 'male' name='sex'>
<br>
<input type='submit' class='js-submit' disabled>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='index.js'></script>
</body>
</html>
Here's an example of how you could achieve this with JavaScript. This may not be the best way to do this, but as an example it's a good place to start.
http://plnkr.co/edit/LLg9DklQFMFFB7XRzX7t?p=info
<!DOCTYPE html>
<html>
<head>
<style>
button#submit:disabled {
color: #bbb;
background-color: #ddd;
}
</style>
</head>
<body>
<h1>Form Example</h1>
<form>
<div>
<label>Input 1</label>
<input type="text" required="required" name="input1" id="input1" onkeyup="validate()" />
</div>
<br />
<div>
<label>Input 2</label>
<input type="text" required="required" name="input2" id="input2" onkeyup="validate()" />
</div>
<br />
<button id="submit" type="submit" disabled>Submit</button>
</form>
<script>
var button = document.getElementById('submit');
button.disabled = true;
function validate() {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (input1.value && input2.value)
button.disabled = false;
else
button.disabled = true;
}
</script>
</body>
</html>
Note: The disabled attribute on the button element and the button.disabled = true are redundant. You should be able to remove either and the example still work as expected.
EDIT
If you want to use the onblur and onfocus events instead of onkeyup, the only change from the above example is to mark these attributes as using the validate function like so:
<input type="text" required="required" name="input1" id="input1" onblur="validate()" onfocus="validate()" />
See this updated plunk for the full example: http://plnkr.co/edit/lc0vO8kBnhMyKD3xgPxo?p=info
Please note the behavior here, however, is such that if you type in the first input, then move to the second, the submit doesn't become enabled until you leave the second. Similarly in reverse, if the user removed what they provided in either box after having been validated in this setup, if they did not trigger the blur event, the submit button would remain enabled. This, I think, could be confusing, and really suggests that you should also have onclick on your submit button if this is really what you need. This is the reason I initially suggested using onkeyup, as it catches the values as they are typed and avoids additional confusion or programming.

Javascript - How to add form's input into the dom properly?

I'm just trying to make a simple javascript form where everytime you type and submit something, it shows up in the page.
<form id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="submit">
</form>
javascript:
document.getElementById("myForm").addEventListener('submit', function(){
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
});
This shows up for a second then disappears. I understand it's happening because the dom manipulation is happening inside the submit event. But I'm not sure how to go around that.
My first instinct was to use
return output;
then reference the whole function once I appendChild from outside it. But that didn't work either. I'm guessing cause It's an Eventlistener and not a normal function... any ideas on how to go with this?
You are ignoring the form primordial sense that is to send data over a server.
You don't need aform for what you intend. you need only input elements and a handler on the button.
function handler (){
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
document.getElementById("text").value='';
}
document.getElementById("submit").addEventListener('click', handler);
document.getElementById("text").addEventListener('keypress', function(e){ (e.charCode == 13) && handler();});
<div id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="submit">
</div>
Add return false; at the end of the event listener. This stops the submit from actually happening which refreshes the page
Try this instead:
document.getElementById("myForm").addEventListener('submit', function(event){
event.preventDefault();
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
});
the simplest way of getting input and display on the same page is
function display()
{
var input=document.getElementById("text").value;
document.getElementById("display").innerHTML=input;
}
<form id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="button" onclick=display() value="submit">
<div id="display"></div>
</form>
if you want to display multiple inputs i.e. each input entered by the user.
document.getElementById("display").innerHTML += input+"<br>";
Note: Always try to write easiest and shortest code for the optimized result.
yes it behaves how it should. it's form and what it does it submits all information to new page. you didn't provide action='' parameter and means it sends information on same page. when you click submit what happens is first you append h1 element and then it reloads, that's why it disappears. if you don't have other page to submit information get rid of forms.
<input id="text" type="text" name="name" value="">
<input id="submit" onclick='return getoutup();' type="submit">
<h1 id='output'></h1>
<script type="text/javascript">
function getoutup(){
document.getElementById('output').innerText=document.getElementById('text').value;
return false;
}
</script>
so you see that i have pre-created h1 tag, so you don't need much coding to append as function goes. just pre create with value of none and then change with one line of code. hope it helps. maybe it's not correct answer kind of changed your way.

How to force "enter key" to act as "tab key" using javascript?

I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do.
I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on
<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />
<script type="text/javascript">
function noNumbers(e) {
keynum = e.which;
if (keynum == 13)
document.getElementById("Text2").focus();
}
</script>
I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript
This will handle multiple input fields.
Here is the jQuery version:
http://jsfiddle.net/TnEB5/3/
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
Here is the pure javascript version:
http://jsfiddle.net/TnEB5/5/
(you probably want to get the sibling differently)
function tab(e) {
if (e.which == 13) {
e.target.nextSibling.nextSibling.focus();
e.preventDefault();
}
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
var input = inputs[x];
input.onkeypress = tab;
}
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
handle keypress instead and return false back to the browser:
http://jsfiddle.net/EeyTL/
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<script type="text/javascript">
document.getElementById('Text1').onkeypress = function (e) {
if (e.which === 13) {
document.getElementById("Text2").focus();
return false;
}
};
</script>
You'll need to explicitly set the tabindex property of the input fields for a generic solution. Something like
<input id="Text1" type="text" tabindex="1" />
<input id="Text2" type="text" tabindex="2" />
<script type="text/javascript">
$('input').keypress(function(e){
if(e.which==13){
$("[tabindex='"+($(this).attr("tabindex")+1)+"']").focus();
e.preventDefault();
}
});
</script>
this solution uses jquery to assign the event handler for all input type elements on the page, sets focus to the element with the next highest tabindex property, and prevents the form from submitting when enter is pressed using e.preventDefault(). Here's a jfiddle
<input type="text" value="" onkeyup="doNext(this);"> a <br>
<input type="text" value="" onkeyup="doNext(this);"> b <br>
<input type="text" value="" onkeyup="doNext(this);"> c <br>
function doNext(el){
if(event.keyCode=='13'){
var nextEl = el.form.elements[el.tabIndex+1];
if (nextEl && nextEl.focus) nextEl.focus();
}
}
Althought the post is old, I hope my answer can help someone in need. I have a smilar situation:
I have a very large form for an employee scheduler application with different types of input fields. Some of the input fields are hidden sometimes and not other times. I was asked to make the enter key behave as the tab key so the users of the form could use the 10-key when creating thier employees schedule.
Here is how I solved my problem:
$(document).ready(function () {
var allInputs = $(':text:visible'); //(1)collection of all the inputs I want (not all the inputs on my form)
$(":text").on("keydown", function () {//(2)When an input field detects a keydown event
if (event.keyCode == 13) {
event.preventDefault();
var nextInput = allInputs.get(allInputs.index(this) + 1);//(3)The next input in my collection of all inputs
if (nextInput) {
nextInput.focus(); //(4)focus that next input if the input is not null
}
}
});
});
What I had to do was:
Create a collection of all the inputs I want to consider when tabbing. in my case it is text inputs that are visible.
Listen for a keydown event on the inputs in question, in my case all text field inputs
When the enter is pressed on my text input, determine what input is next to be focused.
If that input is valid, bring it into focus.
I am using this code for advancing to next input field. I hate to press TAB key. And this solution works in IE & Firefox:
<script type="text/javascript">
function tabE(obj,e){
var e=(typeof event!='undefined')?window.event:e;// IE : Moz
if(e.keyCode==13){
var ele = document.forms[0].elements;
for(var i=0;i<ele.length;i++){
var q=(i==ele.length-1)?0:i+1;// if last element : if any other
if(obj==ele[i]){ele[q].focus();break}
}
return false;
}
}
</script>
HTML Content
<form id="main">
<input name="" type="text" onkeypress="return tabE(this,event)">
<input type="submit" value="Ok">
</form>
Here is a easy solution for you.
Basically you include the enter2tab.js file and then add the enter2tab class on each object where you want enter to be treated as js.
https://github.com/AndreasGrip/enter2tab
You can obviously look at the code to understand what it does and how..
I believe using e.preventDefault(); is safer than returning false.

clear inputbox onclick image

this line renews the captcha image, it should clear the inputbox 'captcha' aswell.
<div id="refresh_button"><img src="refresh.gif"/></div>
<input type="text" maxlength="6" name="captcha" id="captcha" class="captcha_inputbox" />
So I have to modify the onClick, but I can't find this, not even with google.
Your help is much appreciated
You can clear out the textbox's value by using:
document.getElementById('captcha').value = '';
Alternatively, if you're using jQuery:
$('#captcha').val('');
it would be better to do this in script tags instead. For instance you can do something like this:
<script type='text/javascript'>
function refreshimg() {
// do the refreshing here
// since your input text has an id of 'captcha'
document.getElementById("captcha").value = "";
return false;
}
</script>
then in your HTML, you would do
<div id="refresh_button"><img src="refresh.gif"/></div>
<input type="text" maxlength="6" name="captcha" id="captcha" class="captcha_inputbox" />

Categories