html5 required attribute custom validation message not working - javascript

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);
}

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)">

submit input field using enter key

I'm building the weather app and want to submit the city name to the server using the Enter key.
I am getting the error
submit is not a funtion
I want to fix this and i want to know how can i send the value to the express server in order to use it in API calls.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>Weather APP</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<input id="City" placeholder="EnterCity" onclick="u()" action="/" method="post">
</body>
<script>
function u(){
document.getElementById("City").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
var x = document.getElementById("City");
x.submit();
return false;
}
});
}
</script>
</html>
Try putting input inside a form tag, and submitting the form instead of the input tag
...
<body>
<form id="CityForm" onsubmit="u()" action="/" method="post">
<input id="City" placeholder="EnterCity" />
</form>
</body>
<script>
function u(){
document.getElementById("City").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
var x = document.getElementById("CityForm");
x.submit();
return false;
}
});
}
</script>
...
You submit form's, not individual input elements. On your input element you can have an action like onChange which will run every time the input tag get's input, but the actual submission is handled by the form

Trying to learn to combine a form and script to affect my page

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input type="submit">
</form>
<script type="text/javascript">
let actualWord = document.getElementById('word');
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
</script>
</body>
</html>
Im very new to the world of coding and im hoping someone could help me with a "simple" test I was trying to perform.
I want this HTML code to replace the "Placeholder" text at the top of the screen with "oh Yeah" if the user types "yes" in the form.
Im hoping someone can tell me what im doing wrong or point me in the right direction.
https://github.com/Uken81/Form-test.git
1.You need to listen to form submit event and trigger a function
HTML
<form onsubmit="return handleSubmit()">...</form>
Javascript
function handleSubmit(evt) {
...
}
2.You get user's input value like this
document.getElementById('word').value
3.Also you need to prevent form from submitting, By returning false
Full Example
function handleSubmit(evt) {
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
}
return false;
}
<h1>placehold</h1>
<form onsubmit="return handleSubmit()">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
</form>
You can achieve that by adding click event listener to the <submit> button inside the form, and then perform the check on the text <input> and use .value attribute to get the <input> text value, note that I used [e.preventDefault()][3] to prevent the form from redirect, here is a working snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input id="change-placeholder" type="submit">
</form>
<script type="text/javascript">
document.getElementById('change-placeholder').addEventListener('click', function(e){
e.preventDefault();
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
})
</script>
</body>
</html>

JS input value assigning to variable - undefined

I'm really fresh to JS
Need some help because I don't understand a thing.
If I try to assign the whole line to variable, I can use this variable later, but the outcome of that is blank or undefined, when I'm trying to log this to console, or either alert that
using opera/chrome it's still the same, am I doing something wrong?
HTML
<input type="text" id="name" placeholder="username">
JS
not working
var name = document.getElementById('name').value;
console.log(name);
can't do that either
var name = document.getElementById('name');
console.log(name.value);
innerHTML not working
I can do only that
console.log(document.getElementById('name').value);
UPDATING THE CODE TO FULL EXAMPLE
So I've changed the variable name to nameInp but it isn't working
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<input type="text" id="name" placeholder="podaj imię">
<input type="text" id="name2">
<input type="text" id="name3">
<!--
<input type="password" id="password" placeholder="podaj hasło">
<input type="password" id="confPassword" placeholder="powtórz hasło">
-->
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
<!--
<p id="para"></p>
-->
<div class="center"></div>
<div class="center2"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="main.js"></script>
</body>
</html>
var nameInp = document.getElementById('name').value;
var btn = document.getElementById('submit');
function check(){
console.log(nameInp);
}
Here's your code reduced to the relevant parts:
var nameInp = document.getElementById('name').value;
function check() {
console.log(nameInp);
}
<input type="text" id="name" placeholder="podaj imię">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
The problem is that var nameInp = document.getElementById('name').value; is executed right when main.js is loaded (which happens as part of the whole page loading). At that point the input field has no value yet, so this is equivalent to var nameInp = "";.
Later, when the user clicks on the submit button, the check function runs, but nothing has changed the nameInp variable. It still contains "", so you get no output.
Here's a clearer demonstration of the problem, where the initial value is not "" but "initial value":
var nameInp = document.getElementById('name').value;
function check() {
console.log(nameInp);
}
<input type="text" id="name" placeholder="podaj imię" value="initial value">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
Every time you click on wyślij, initial value is printed because that's what nameInp was initially set to.
Fix:
var nameInp = document.getElementById('name');
function check() {
console.log(nameInp.value);
}
<input type="text" id="name" placeholder="podaj imię">
<button id="submit" onclick="check();" value="wyślij">wyślij</button>
Here we only retrieve the .value of the input field at the time check() is run, i.e. when the button is clicked.
You can't see anything in the console because you're outputting the value of the input when the script is called so essentially on page load. At this point the input box hasn't been filled yet. That's the console.log doesn't show anything.
You can, for example, run your function every time the user types inside the input box. For this you will need an event listener:
Select the element you desire to 'watch' and call the addEventListener() method on it. It takes the event type and a callback function as parameters.
Lastly, in the callback function, we get the value of the input box by accessing the target of the event: e.target. e being the event object and e.target the property target of the event.
The code below will call a console.log() every time the user types in the input box:
document.querySelector('#username').addEventListener('keydown', function (e) {
console.log(e.target.value);
});
<input type="text" id="username" placeholder="username">
I have made a script for all three cases, use it according to your need.
<html>
<head>
<script>
function Consolify() {
var firstMethod = document.getElementById('name').value;
console.log('firstMethod = ', firstMethod);
var secondMethod = document.getElementById('name');
console.log('secondMethod = ', secondMethod.value);
console.log('thirdMethod = ', document.getElementById('name').value);
}
</script>
</head>
<body>
<input type="text" id="name" placeholder="username">
<button onclick="Consolify()">Consolify</button>
</body>
</html>

Form textbox content with javascript

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>

Categories