live validation input when min>max in jquery - javascript

I want validate input "min" and "max" and give an error. My actual code work when I press submit button. I want validate this in live when the user
complements other fields. When the user go to the next field and max
My actual code:
<!doctype html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>...</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div class="error">
</div>
<form id="a" action="b.php" method="post" enctype="multipart/form-data">
<label>
<input type="number" name="yearMin" value="1900" min="1800" max="2299">
</label>
<label>
<input type="number" name="yearMax" value="2015" min="1800" max="2299">
</label>
<label>
<input type="text">
</label>
<button type="submit" class="button">Start</button>
</form>
<script>
$(document).ready(
function () {
$("form#a").submit(
function () {
var min =$('input[name^="yearMin"]').val();
var max =$('input[name^="yearMax"]').val();
if (min<max)
{
return true;
}
else
{
$('.error').text("min>max");
return false;
}
}
);
}
);
</script>
</body>
</html>
Edit:
<script>
$("input[type=number]").on('keydown keyup',function(e) {
var min = $('input[name^="yearMin"]').val();
var max = $('input[name^="yearMax"]').val();
if (min < max) {
$('.error').text('');
return true;
} else {
$('.error').text("min>max");
return false;
}
});
</script>
Do I think right? text('') doesn't work.

$("input[type=number]").on('keydown keyup',function(e) {
var min = $('input[name^="yearMin"]').val();
var max = $('input[name^="yearMax"]').val();
if (min < max) {
return true;
} else {
$('.error').text("min>max");
return false;
}
});
The keyup event occurs when a keyboard key is released. The keydown event occurs when a keyboard key is pushed. So we will bind this event to the required element.
keyup
keydown

Related

When I hit the submit button, I'm unable to achieve the, "Enjoy your day" on the entire screen after one or all the checkboxes have been checked

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Checklist</title>
<link rel="stylesheet" type="text/css" href="./style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit"
onchange="document.getElementById('formName').submit()">
</div>
<!--<p id="msg"></p> (I tried using this approach and calling the msg within script but I received an error.)-->
</form>
</div>
</body>
<script>
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
var submit = document.getElementById('submit');
var text = document.getElementById('msg');
//My if/else statement alert works perfectly. However, with the presence of const submit, it doesn't work properly (I think it's interfering with my if/else statement). Removing the const submit section allows one to experience the if/else alert statement. The goal of this checklist is to be able to check one or all four checkboxes and have it return the "Enjoy your day" text. However, I would like for that message to cover the screen and be the only thing visible after hitting the submit button. I'm okay with receiving an alert box when it returns false. However, when it returns true, I would like for the message to cover the screen and for the checklist/checkboxes to disappear. I'm not sure where I'm getting my wires crossed.
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
} else {
return true;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
}
</script>
</html>
enter image description here
enter image description here
You are declaring submit twice in the isChecked function. Omit one of the declaration.
Also, you are adding the event listener to the submit button after the return statement, which JS will ignore and won't append any onclick function.
The updated isChecked function should be
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
// Removed the submit variable
var text = document.getElementById('msg');
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
// Returning true after adding the event listener.
return true;
}
Just display the message since it is being called onsubmit
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
if (!workout && !meeting && !lunch && !school) {
alert('Please check a box');
} else {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
}
return false;
}
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit">
</div>
</form>
</div>

How to call function when input value changes?

I have tried to find a way to call a function when the value of the input changes, but so far I haven't found anything. All of the things I have tried seemed to work but didn't.
Html:
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rng Crypto</title>
</head>
<body>
<header>
<h1>Crypto ran from randomness!</h1>
</header>
<div>
<input type="radio" name="AP" id="a" onchange="AP()" checked>Absolute<input type="radio" name="AP" id="p" onchange="AP()">Percent<br>
<input type="number" id="input" HERE TO ADD THINGY>
<p id="AP" style="display:inline;"></p><br>
<button id="submit">Submit</button>
</div>
<script src="RngCrypto.js"></script>
</body>
</html>
The things that I have tried are:
<input type="number" id="input" onchange="input()">
<input type="number" id="input" oninput="input()">
<input type="number" id="input" onkeyup="input()">
document.getElementById("input").onchange=input();
document.getElementById("input").oninput=input();
const inputEle = document.querySelector("#input");
inputEle.addEventListener('input', function(e) {
console.log(e.target.value);
})
<input type="text" id="input">
Have you tried adding the 'change' event on the input element.
Edit: adding 'input' eventListener, is one more way to achieve this result.
(refer following code)
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
document.queryselector("#input").addEventlistener('change', function(e) {
console.log(e.target.value;)
})
When I got you right this is basically what you are looking for:
<input class="js-radio-button" type="radio" name="ab" value="absolute"> Absolute<br>
<input class="js-radio-button" type="radio" name="ab" value="percent"> Percent<br>
<button class="js-check-selection">CHECK</button>
<div>
<span>Result is:</span> <span id="result"></span>
</div>
in your javascript you have:
function checkSelectedRadio() {
// get your radios having the name 'ab'
const radios = document.querySelectorAll('input[type=radio][name=ab]');
// reset result container
document.getElementById('result').innerHTML = '';
// loop through the radios
for (let i = 0; i < radios.length; i += 1) {
// check for each radio if it was selected
if (radios[i].checked) {
// set the value of the selected radio to your result container
document.getElementById('result').innerHTML = `Value: ${radios[i].value}`;
// if you need more logic:
if (radios[i].value === 'absolute') {
// do something here if 'absolute' was checked
} else if (radios[i].value === 'percent') {
// do something here if 'percent' was checked
}
}
}
}
// get your button to check radio status like this or fire the function above by your onchange handler
const checkButton = document.querySelector('.js-check-selection');
checkButton.addEventListener('click', checkSelectedRadio);
EDIT after reading your comment:
To detect change of your input field it works like this:
<input type="number" id="input" value="1">
In your JS:
const field = document.querySelector('#input');
function inputCheck() {
console.log('input changed');
// or do something else
}
field.addEventListener('change', inputCheck);

HTML check user input in form for letters

Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>

live update value if checkbox is checked or not

I am trying to update a textbox based on whether or not a checkbox is checked or not. Thanks to this post I got a text box working fine, but I can't get a checkbox to update the value. What am I missing?
<html>
<head>
<title>sum totals</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
$('input[name="selectedItems1"]').click(function(){
var j = document.getElementById("output");
if (this.checked) {
j.value=j.value+300
}else{
j.value=j.value-300
}
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Place the <script> tag after <form>
Reason:
When the html page loads, it'll be interpreted line by line. When it come to click(), jQuery will try to find the element input[name="selectedItems1"] which won't be loaded into the DOM at that time. So, jQuery won't attach the click() event handle to that checkbox. That's the reason why your code didn't work.
Try this :
<html>
<head>
<title>sum totals</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script type="text/javascript">
function calculate(){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var tons = $('#tons').val();
if ( rege.test(tons) ) {
val = parseInt(tons);
var treesSaved = val * 17;
if($('input[name="selectedItems1"]').is(":checked"))
{
treesSaved = treesSaved +300;
}
else
{
treesSaved = treesSaved -300;
}
if(isNaN(treesSaved))
j.value=0
else
j.value=treesSaved;
}
else
alert("Error in input");
}
$(function(){
$('input[name="selectedItems1"]').change(function(){
calculate();
});
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate()"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>

how to not submit a form in js

I want to not submit the form if the inputs are empty, here is my code:
<html>
<head>
<title>
The X/O Game
</title>
<script type="text/javascript">
var check = function () {
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x==""&&o=="")){
alert("fill the form!");
return false;
}
return true;
};
$('#formm').submit(function(e){
var shouldSubmit = check();
if (!shouldSubmit) {
e.preventDefault();
}
});
$('#emotion input:radio').addClass('input_hidden');
$('#emotion label').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<body>
<div>
Please enter your name & choose your character before start playing:
</div>
<div>
<form method=post action=game.php name="formm">
Name:<br>
<input type=text name=player id=p>
</div>
<div>
Character:<br>
<input
type="radio" name="emotion" value="xChar"
id="x" class="input-hidden" />
<label for="x">
<img src="images/x.png " />
</label>
<input
type="radio" name="emotion" value="oChar"
id="o" class="input-hidden" />
<label for="o">
<img src="images/o.png" />
</label>
</div>
<div>
<input type=submit value=Play>
</form>
</div>
</body>
</html>
$('#formm').submit(function(){
return f;
});
this function is called when the user clicks on the submit button.
the form is subbmited even though the inputs are empty, where is the wrong?
f is defined when you call check(), they will not magically update. Do the checks inside the submit function.
You'd better use HTML5 required attribute here:
<form>
<input type="text" name="x" required>
<input type="submit">
</form>
If you want more complex validation, you should have a look at html5rocks.com. The form validation should move from Javascript to HTML now (or in the near future).
But if you want to do it your way, do as epascarello suggests here:
$('#formm').submit(function(){
check();
return f;
});
Try this:
$('#yoursubmitbtnid').click(function(){
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x=="" && o=="")){
alert("fill the form!");
return false;
}
});
You need to run the check function in the submit handler to determine whether or not the submit should be allowed.
var check = function () {
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x==""&&o=="")){
alert("fill the form!");
return false;
}
return true;
};
$('#formm').submit(function(e){
var shouldSubmit = check();
if (!shouldSubmit) {
e.preventDefault();
}
});
You may want to look into using a validation plugin (such as this) if you plan on doing any extensive client side validation.
You need to call the check function when the form is being submitted
$('#formm').submit(function(){
return check();
});
If the check function returns false then the form should not submit.

Categories

Resources