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>
Related
How can I put a input with a oninput that only works when I have a minlength defined?
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction()"><br><br>
If I understand your question correctly, you want to run some code only when your minlength="8" is satisfied.
You can check if the input is correctly validated using the validity object. It contains the state of all the validation flags. See https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
<p id="demo"></p>
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction(this)"><br><br>
<script>
function myFunction(el) {
// Check if input is tooShort
if (el.validity.tooShort) {
// You can just leave this empty
document.getElementById("demo").innerHTML = "Too Short"
} else {
// Run this code if minlength is satisfied
document.getElementById("demo").innerHTML = el.value;
}
}
</script>
You could however also just check the length of the value like this:
<p id="demo"></p>
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction(this)"><br><br>
<script>
function myFunction(el) {
// Check if value is at least 8 characters....
if (el.value.length < 8) {
// You can just leave this empty
document.getElementById("demo").innerHTML = "Too Short"
} else {
// Run this code if length is at least 8
document.getElementById("demo").innerHTML = el.value;
}
}
</script>
read attribute value using this.getAttribute method and then relatively call function
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="this.getAttribute('minlength') !== undefined ? myFunction() : null">
you can try this:
html: <input type="text" minlength="3" id="input">
Javascript:
let val = document.querySelector("#input");
val.addEventListener('input', () => {
let vaLength = document.querySelector("#input").value
if(vaLength.length >= 5){
console.log("the input has more than 4 character...")
}
})
I am trying to write a function in jQuery.
var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
$("#lname").text("Bob");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Please check my fiddle here
What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.
Three things:
You need to add an event listener to the first input to constantly keep checking when someone inputs something.
Before selecting elements in the DOM, make sure the DOM is ready.
You don't need jQuery at all here. Like most things, very easy to do without jQuery.
const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
fname.addEventListener('input', function(event) {
lname.value = names.includes(fname.value) ? 'Bob' : '';
});
});
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
If you insist on jQuery (which I do strongly recommend you shouldn't until you are proficient with the native DOM API):
const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
const $fname = $('#fname');
const $lname = $('#lname');
$fname.on('input', function(event) {
if ($.inArray($fname.val(), names) > -1) {
$lname.val('Bob');
} else {
$lname.val('');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Try this:
<body>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
<button onclick="checkValue()">Click</button>
<script>
var arr1 = ["Jcob", "Pete", "Fin", "John"];
function checkValue() {
var str = $("#fname").val();
var val = jQuery.inArray(str, arr1);
if (val === -1) {
console.log("no value");
}
else {
$("#lname").val("Bob");
}
}
</script>
</body>
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("");
}
});
}
}
I am trying to pass data from a form into a Google Apps Script but when I press submit I am greeted by I blank screen.
Form:
<div id="nameDiv">
<form action="https://script.google.com/a/umbc.edu/macros/s/AKfycbztum1ImJZeXXYt0fFhwOAMUsB5zCsJQohrum4W7qiH/dev">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="google.script.run.nameSearch()">
</form>
</div>
Script:
function nameSearch(){
try {
var firstName = document.getElementById("fname").value
var lastName = document.getElementById("lname").value
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15]
}
}
document.getElementById('nameDiv').innerHTML =
"<center>Last Name:" + lastName + "</center>" +
"</br><center>First Name:" + firstName + "</center>"
} catch(e) {
alert(e)
}
}
I am trying to pass this data to the script so that it can use it to search a google sheet so I cannot just place the script in the html as a client side script. Any thought?
All the HTML-related methods (getElementById, innerHTML, etc.) should be in client-side script, and Apps Script methods should be in the server-side.
If I understand you correctly, you want to do the following:
When this form gets submitted, look for the row whose columns K and L match the inputted fields (indexes 10 and 11 from inputData array).
For this row, return data from columns O and P (indexes 14 and 15 from inputData array).
Write this returned data to the HTML.
If all this is correct, then you could do this:
Add an onclick event in the submit input that will fire a client-side function (a function that is declared inside the tags in the HTML). There is no need to use a for this. The HTML body could be something like this:
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
From this client-side function called clientNameSearch(), retrieve the values from fname and lname, and use these as parameters when you call a server-side function called nameSearch):
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
This server-side function iterates through all rows with content in the spreadsheet, and returns the result for the first row whose columns K and L match the inputted data:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
This result is then passed as a parameter to a client-side function called onSuccess via a success handler. This is necessary since server-side functions called by google.script.run don't return anything directly, as specified here. Then onSuccess writes the result to the HTML:
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
Full code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
</body>
<script>
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
</script>
</html>
And the Code.gs would be like:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("your-html-name");
}
I'm not sure you want to write the result to the HTML, but in any case, at this point it shouldn't be difficult to modify this so that it writes exactly what you want and where you want.
Reference:
google.script.run.myFunction(...) (any server-side function)
withSuccessHandler(function)
I hope this is of any help.
Try this:
Launch the dialog fill the text boxes and click submit. The view logs and see the next dialog.
function launchADialog() {
var html='<form><br /><input type="text" name="Name" /> Name: <br /><input type="text" name="Age" /> Age: <br />';
html+='<select name="Children" ><option value="0">None</option><option value="1">One</option><option value="2">Two</option></select> Children:<br />';
html+='<input type="button" value="Submit" onClick="google.script.run.processForm(this.parentNode);" /></form>';
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The Form");
}
function processForm(form) {
Logger.log(JSON.stringify(form));
var s=Utilities.formatString('<br />Name: %s <br />Age:%s <br />Number Of Children: %s', form.Name, form.Age, form.Children);
s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Form Data")
}
If I enter something into t1, t2 is changed.
But if t2 already has manual input, it is not changed any more (and vice versa).
How can I change an input field that has already an manual input with javascript (without reloading the page!)?
<!DOCTYPE html>
<html>
<body>
inputfields are not changed, if they have/had an input already!<br />
<br />
t1: <input type="text" id="t1" value="" onchange="upd1()"><br /><br />
t2: <input type="text" id="t2" value="" onchange="upd2()">
<script>
function upd1() {
t2.setAttribute("value", "changed");
return true;
}
function upd2() {
t1.setAttribute("value", "changed");
return true;
}
</script>
</body>
</html>
You can also save an old value of each field to continue editing. Also it will show editing status on another field each time. It will be more comfortable for users.
inputfields are not changed, if they have/had an input already!<br />
<br />
<input type="text" id="t1" value="" onClick="renderFirstEl()" onInput="upd1()"><br /><br />
<input type="text" id="t2" value="" onClick="renderSecondEl()" onInput="upd2()">
<script>
let firstElValue = '';
let secondElValue = '';
function upd1() {
let el = document.querySelector('#t2');
el.value = 'changed';
return true;
}
function upd2() {
let el = document.querySelector('#t1');
el.value = 'changed';
return true;
}
function renderFirstEl() {
let el = document.querySelector('#t1');
secondElValue = document.querySelector('#t2').value;
el.value = firstElValue;
}
function renderSecondEl() {
let el = document.querySelector('#t2');
firstElValue = document.querySelector('#t1').value;
el.value = secondElValue;
}
</script>
The simple answer is use this:
function upd1() {
t2.value = 'changed';
return true;
}
function upd2() {
t1.value = 'changed';
return true;
}
t1: <input type="text" id="t1" value="" onchange="upd1()"><br /><br />
t2: <input type="text" id="t2" value="" onchange="upd2()">
Value changes after you type in one of the inputs and press Enter.
Because as said here: https://www.w3schools.com/jsref/met_element_setattribute.asp .
"The setAttribute() method adds the specified attribute to an element, and gives it the specified value.
If the specified attribute already exists, only the value is set/changed."