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)">
Related
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.
I would like to know if there is better way to this exercice.
Here it is : Create a form that contain a textbox ;after the user enter the text ,all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form( hint: use change onChange event handler).
I have written this code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event</title>
</head>
<body>
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>
</body>
</html>
Basically i'm replacing the content of the textbox by the formatted
Might be too easy, but setting the text over a style to lowercase transform doesn't allow uppercase :)
function toLower(element) {
if (element && element.value) {
element.value = element.value.toLowerCase();
var target = document.getElementById('realvalue');
target.innerHTML = element.value;
}
}
<input type="text" onblur="toLower(this)" />
<div id="realvalue"></div>
But, if all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form, your code work correctly...
http://jsfiddle.net/b6xwde62/
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>
I have a simple form with two inputs and a submit button. I need to display the message depending on the lang attribute. When I click on submit button it displays the message even though the field is filled with valid data.
<!DOCTYPE html5>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="" method="get">
<input type="text" value="" oninvalid="check(event)" required/>
<input type="text" value="" oninvalid="check(event)" required/>
<input type="submit" value="Save">
</form>
<script type="text/javascript">
function check(e) {
var a=document.documentElement.lang;
var validateMsg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
var input = e.target;
if(input.validity.valid){
return true;
}else{
input.setCustomValidity(validateMsg);
return false;
}
}
</script>
</body>
</html>
check(event) is meaningless. The event parameter is passed internally
checking validity inside the oninvalid handler is useless
If you use only oninvalid, you won't be able to change back the validation message once the user starts filling the field. You should use the change, keyup or keydown event for that, depending on the reactivity you want.
This could work:
<input type="text" value="" onchange="check" required />
// ...
function check(e) {
var input = e.target;
var msg = "";
if(!input.validity.valid) {
var a=document.documentElement.lang;
msg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
}
input.setCustomValidity(msg);
}
I have a textbox and save button. If anything changed on textbox then only save button should be enabled. I am able to take care this using javascript event, but when i select some text and right click and delete that selected text then, I do not get any event. Below is my sample code:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var hiddenfield = document.getElementById("hide").value;
var textboxval = document.getElementById("me").value;
if (textboxval != hiddenfield) {
document.getElementById("xx").disabled = false;
} else {
document.getElementById("xx").disabled = true;
}
}
function load() {
document.getElementById("hide").value = document.getElementById("me").value;
}
</script>
</head>
<body onload="load();">
<input id="me" type="text" value="test test" onkeyup="myFunction()" onmouseup="myFunction()"
onmousedown="myFunction()">
<input type="button" id="xx" value="Save" disabled="disabled" />
<br>
<input id="hide" type="hidden" value="">
</body>
</html>
Is there way to detect if user delete the text via right button click?
Try onchange, since the context-menu control changes the contents.
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.