I have a contact form for my website which I would like to auto refresh due to inactivity only if data has been entered. I have managed so far to implement the auto refresh due to inactivity but how do I add an if statement where the auto refresh code runs only when data is entered.
<!-- Timeout -->
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
$('body').mousemove(function (e) {
idleTime = 0;
});
$('body').keypress(function (e) {
idleTime = 0;
});
$('body').click(function() {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 1) { // 1 minute
window.location.assign("");
}
}
</script>
<!-- End of Timeout -->
<!--Contact form -->
<div class="contact-clean" style="background-color: #ffffff;">
<form method="post" name="contactform" action="contact-form.php" enctype="multipart/form-data">
<div class="form-group"><input class="form-control" type="text" name="firstname" placeholder="First Name" required="" minlength="2"></div>
<div class="form-group"><input class="form-control" type="text" name="lastname" placeholder="Last Name" required="" minlength="3"></div>
<div class="form-group"><input class="form-control" type="email"name="email" placeholder="Email" inputmode="email" required=""></div>
<div class="form-group"><textarea class="form-control" name="message" placeholder="Message" rows="14"></textarea></div>
Create an ID for your form and access name attributes with Javascript:
const form = document.getElementById('yourFormId');
const formData = new FormData(form);
// If "firstname" is not empty, do something:
if (formData.get('firstname')) {
// refresh
}
// Do the same with any input from your form or all
You're looking for the... oninput="" ...to catch when the user enters data and it's used like this...
<input oninput="Counter=0;" class="form-control" type="text" name="firstname" placeholder="First Name" required="" minlength="2">
This will trigger every time the user types a character.
In this example I've made the trigger reset a refresh counter variable called "Counter" to zero.
Check if input is not empty
$('#your_form_id').submit(function (e) {
e.PreventDefault();
if ($('[name="your_inut_name"]').text().length >= 1) {
$('#your_form_id').submit();
else {
alert("Text field can not be empty!")
})
Execute function on element change
$(#your_input).change(function () {
do_whatever_you_want();
})
https://www.javatpoint.com/jquery-change
I may be wrong in syntax (not a cool js developer) and approach is like this.
<form id="contact">
<input type="text" value="test" />
<input type="text" value="s" />
<input type="text" value="" />
<input type="text" value="" />
</form>
<script>
let idleInterval = null;
const hasEntries = () => {
let data = new FormData(document.getElementById("contact"));
let entry = data.values();
return entry !== null;
};
const refresh = () => {
if (hasEntries()) {
window.location.href = window.location.href;
}
};
const setInactivityTimer = () => {
idleInterval = setInterval(refresh, 60000);
};
const clearInactivityTimer = () => {
clearInterval(idleInterval);
if (hasEntries) {
setInactivityTimer();
}
};
let inputs = document.querySelectorAll("input");
inputs.forEach(input => {
input.onkeypress = () => clearInactivityTimer();
});
document.body.onmousemove = () => clearInactivityTimer();
document.getElementById("contact").querySelector("input");
</script>
Test: https://codesandbox.io/s/youthful-cache-jo2t2
You can use this code to check if any inputs have a value in them. If they do, the website reloads.
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 1) {
$("input, .form-control").each(function() {
if ($(this).val() != "") {
window.location.assign("");
}
});
$("textarea, .form-control").each(function() {
if ($(this).val() != "") {
window.location.assign("");
}
});
}
}
Related
I have code that displays the number of characters left to type.
This is my code:
<input type="text" name="title" value="" title="This is a required field." placeholder="title" maxlength="64" id="max_length_red" required>
<div class="max_length_red"></div>
<script>
(function(){
document.addEventListener("keyup", function(event){
if(event.target.matches("#max_length_red")){
// get input value and length
const value = event.target.value;
const valueLength = event.target.value.length;
// get data value
const maxChars = parseInt(event.target.getAttribute("maxlength"));
const remainingChars = maxChars - valueLength;
if(valueLength > maxChars){
// limit chars to maxChars
event.target.value = value.substr(0, maxChars);
return; //end function execution
}
event.target.nextElementSibling.innerHTML = remainingChars + " remainingChars";
}
})
})();
</script>
I am trying to change the code that will appear as soon as the page is loaded, because currently as long as I have not started writing text in the input the number of characters does not appear.
You can make use of the DOMContentLoaded event which is fired as soon as the page is fully loaded and rendered.
From the MDN:
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
A very simple solution could be:
<input type="text" name="title" value="Some value" title="This is a required field." placeholder="title" maxlength="64" id="max_length_red" class="limit-input" required>
<div class="max_length_red"></div>
<input type="text" name="title" value="Some other value" title="This is a required field." placeholder="title" maxlength="42" id="max_length_red2" class="limit-input" required>
<div class="max_length_red"></div>
<input type="text" name="title" value="Short" title="This is a required field." placeholder="title" maxlength="10" id="max_length_red3" class="limit-input" required>
<div class="max_length_red"></div>
<script>
function calculateChars(element) {
// get input value and length
const value = element.value;
const valueLength = element.value.length;
// get data value
const maxChars = parseInt(element.getAttribute('maxlength'));
const remainingChars = maxChars - valueLength;
if(valueLength > maxChars){
// limit chars to maxChars
element.value = value.substr(0, maxChars);
return; //end function execution
}
element.nextElementSibling.innerHTML = remainingChars + " remainingChars";
}
(function(){
document.addEventListener("keyup", function(event){
if(event.target.matches(".limit-input")){
calculateChars(event.target);
}
});
// Here initialize the text with maximum chars allowed
window.addEventListener('DOMContentLoaded', function () {
const inputs = document.querySelectorAll('.limit-input');
inputs.forEach((el) => calculateChars(el));
});
})();
</script>
I try to see if the word entered in the form is the correct one. If it is correct then I open another page and otherwise I will get an error message, but I don't know how to make the script for this. Also I don't want to use a submit button.
<form id="form">
<input type="text" name="inputBox" placeholder="Enter your answer"><br>
</form>
Try this:
In this code I check with the key event, if I press enter I call and ask if the answer is "Hello" is correct and I open another page, otherwise I send an alert with an error
<form id="form">
<input id="MyEnter" type="text" name="inputBox" placeholder="Enter your answer"><br>
</form>
<script>
var myenter = document.getElementById("MyEnter");
myenter.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
var answer = 'Hello'
var mytext = document.getElementById("MyEnter").value;
if (mytext==answer) {
alert('opening another page');
window.open("https://www.google.com");
}else{
alert("Incorrect answer");
}
}
});
</script>
const input = document.querySelector('input');
const error = document.querySelector('p.error');
const woohoo = document.querySelector('p.woohoo');
const correctAnswer = 'foo bar baz';
const handleInput = (condition) => {
if (condition) {
error.style.display = 'block';
woohoo.style.display = 'none';
return;
}
error.style.display = 'none';
woohoo.style.display = 'block';
window.open('https://google.com');
};
input.addEventListener('keyup', () => handleInput(input.value !== correctAnswer));
<form id="form">
<input type="text" name="inputBox" placeholder="Enter your answer" />
<p class="error" style="color: red; display: none">Incorrect</p>
<p class="woohoo" style="color: green; display: none">Correct</p>
</form>
I'm trying to write easy validation code and I have trouble. I've created element div '._error-alert' and I cant remove it if the input isn't empty.
When I press submit appears my element '._error-alert' but it doesnt disapear when I try to type something there. I'll be very grateful if u help or at least show me the other path to solve it
const form = document.querySelector('.validation__form'),
reqItems = document.querySelectorAll('._req'),
emailTest = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+[^<>()\.,;:\s#\"]{2,})$/,
onlyTextTest = /^[a-zA-Z0-9#]+$/,
onlyNums = /^[0-9]+$/;
const inputTest = (example, input) => example.test(input.value);
const formAddError = (input) => {
if (input.classList.contains('_req')) {
const createBlock = document.createElement('div');
createBlock.classList.add('_error-alert');
input.parentElement.insertAdjacentElement("beforeend", createBlock);
createBlock.innerText = `Invalid ${input.getAttribute("name")}!`;
}
input.parentElement.classList.add('_error');
input.classList.add('_error');
};
const formRemoveError = (input) => {
input.parentElement.classList.remove('_error');
input.classList.remove('_error');
};
// validates form if function validateForm didn't have any errors and removes my created elements '._error-alert'
const sendValidatedForm = (e) => {
e.preventDefault();
let error = validateForm(form);
if (error === 0) {
console.log('fine');
form.reset();
document.querySelectorAll('._error-alert').forEach((errorAlert) => {
errorAlert.remove();
});
}
};
form.addEventListener('submit', sendValidatedForm);
// there I want to check input and remove '._error-alert' if input isnt wrong
const checkInput = () => {
reqItems.forEach((reqInput, index) => {
reqInput.addEventListener('input', () => {
formRemoveError(reqInput);
});
});
};
checkInput();
const validateForm = (form) => {
let error = 0;
reqItems.forEach(reqInput => {
reqInput.value.trim();
formRemoveError(reqInput);
if (reqInput.getAttribute("name") == "email") {
if (!inputTest(emailTest, reqInput)) {
formAddError(reqInput);
error++;
}
} else if (reqInput.getAttribute("name") == "phone") {
if (!inputTest(onlyNums, reqInput) && reqInput.value.length < 8) {
formAddError(reqInput);
error++;
}
} else if (reqInput.getAttribute("name") == "name") {
if (!inputTest(onlyTextTest, reqInput)) {
formAddError(reqInput);
error++;
}
}
});
console.log(error);
return error;
};
<form action="" class="validation__form">
<div class="validation__input-list">
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="name" placeholder="Name">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input" name="surname" placeholder="Surname">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="phone" placeholder="Phone">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="email" placeholder="Email">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input" name="password" placeholder="Password">
</div>
</div>
<button class="validation__form-btn">Submit</button>
</form>
Set the css visibility property of the element to hidden.
const error_element = document.getElementsByClassName('_error-alert')
error_element.style.visibility = 'hidden'
I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo
I have a registration page and I want to compare two passwords (input fields) to be equal before writing it to a websql database.
I cannot seem to get it to work.
Any ideas?
function addTodo() {
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) {
alert("Yours passwords do not match");
} else {
curatio.webdb.addTodo(todo.value);
todo.value = "";
alert("Your Registration was successfull");
setTimeout(function () {
window.location.href = "login.html";
}, 1000);
}
}
<div data-role="fieldcontain" >
<label for="todo">
Password
</label>
<input name="" id="todo" placeholder="" value="" type="password" required>
</div>
<div data-role="fieldcontain" >
<label for="todo2">
Retype your Password
</label>
<input name="" id="todo2" placeholder="" value="" type="password" required>
</div>
You're comparing the elements instead of their values.
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) { // Oops
todo and todo2 are 2 different <input> elements.
Try using .value:
if(todo.value !== todo2.value) {
You're comparing the actual elements, which will always be true (because they are both TextFields). Compair their values, like so:
var todo = document.getElementById("todo").value;
var todo2 = document.getElementById("todo2").value;
Either this or change
if(todo != todo2)
to
if(todo.value != todo2.value)
Another way is Object.is(password, confirm_password)