This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Closed 6 years ago.
I am trying to pass a complete JavaScript statement to a function to prevent typing the same code again. I am using a variable but this code does not seem to work. The HTML input is given below.
var e2;
e2 = document.getElementById("num2");
e2.addEventListener('blur', checko(e2));
function checko(k){
alert("Hey you have entered - "+k.value)
}
<input type="text" class="form-control" id="num2" placeholder="0">
This is just a small code of the web page I am building and to validate other inputs I would like to KEEP use a function.
Change event to change and use this.value as parameter see Snippet. The behavior of change is that it has 3 distinct characteristics:
The event.target needs to be a form input (that includes textarea as well). ✔
It needs user input. ✔
It fires when the event.target has lost focus (a.k.a. blur). ✔
SNIPPET
var e2 = document.getElementById("num2")
e2.addEventListener('change', function(e) {
checko(this.value);
}, false);
function checko(k) {
alert("Hey you have entered - " + k);
}
<input type="text" class="form-control" id="num2" placeholder="0">
I am trying to pass a complete JavaScript statement to a function
It seems you are trying to pass the value of e2 which is the id of the DOM element
Also checko(e2) will execute the function as soon as event is attached to the DOM.
Instead you need to delegate the event.
Beside you can also use Event object to find out the target on which event is executed.
This snippet may be useful
var e2;
e2 = document.getElementById("num2");
e2.addEventListener('blur', checko);
function checko(event){
alert("Hey you have entered - "+event.target.value)
}
JSFIDDLE
You can' pass arguments directly when using addEventListener you can use function() {yourfuncttion(args);}
var e2;
e2 = document.getElementById("num2");
e2.addEventListener('blur', function () {
checko(e2)
});
function checko(k) {
alert("Hey you have entered - " + k.value)
}
function checko(){
var e2 = document.getElementById("num2").value;
alert("Hey you have entered - "+e2);
}
<input type="text" class="form-control" id="num2" placeholder="0" onblur="checko()">
You can also use Onblur Event Listener on direct field.
<!DOCTYPE html>
<html>
<body>
Enter your lastname: <input type="text" id="firstname" >
Enter your fnmae : <input type="text" id="lastname">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
var firstname = document.getElementById('firstname');
firstname.addEventListener('blur', function() {
myFunction(firstname)
});
var lastname = document.getElementById('lastname');
lastname.addEventListener('blur', function() {
myFunction(lastname)
});
function myFunction(k){
alert("Hey you have entered - "+k.value)
}
</script>
</body>
</html>
Related
This question already has answers here:
How can I add an event for a one time click to a function?
(9 answers)
Closed 10 months ago.
I am building a simple todo app and I am new in JavaScript and I am stuck in a problem.
I am trying to run function only once for a particular element ID. like,
There are 5 divs with IDs 1,2,3,4,5. so I am accessing them by className and then their ID.
Then I am storing their id in a variable and storing it to prevent the function from running with the previous id.
page.html
function myFunction() {
// Used for getting last element of all the classes
var element = Array.from(document.querySelectorAll(".fields")).pop();
var previousId = element.id;
var executed = false
if (previousId === element.id) {
if (!executed) {
executed = true;
console.log("Run only once");
console.log(previousId);
}
}
}
<input type="text" id="1" oninput="myFunction(id)" class="fields">
<input type="text" id="2" class="fields">
What I am trying to do ?
I am trying to run the function only once for the current input field user is typing in.
I tried removing if (previousId === element.id) { and running only if(!executed){ but it also didn't worked.
But Whenever I type in input field then it executing every time I press the key.
I have tried many times but it is still not working. Any help would be much Appreciated. Thank You in Advance.
You can save an array of already runned id and chek it
let alreadyRunned = []
function myFunction(id) {
if (alreadyRunned.includes(id)) {
return;
}
alreadyRunned = [...alreadyRunned, id]
console.log("Run only once");
console.log(id);
}
<input type="text" id="1" oninput="myFunction(1)" class="fields">
<input type="text" id="2" class="fields" oninput="myFunction(2)">
I have this problem to solve
In this form a user types in a value. (Actually,
a scanner scans a number and virtually types it - without
sending extra keys like Enter)
I need to contantly check - while typing is going on - if the value in the input
box is a 8 digit number (starting with "4") and if it
is, fire the submit action.
I tried to log any changes. But the code below only logs changes after I leave the input box.
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" onChange="console.log(this.value);">
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
</form>
Is there a Javascript way to pass the value of the box to a function whenever a single letter is typed?
Note: While the form displays a "scan" button, the goal is to have that button automatically clicked as soon as 8 digits have been entered and been declared valid by a validator function.
It is generally not a good idea to use inline event handlers.
Actually, a scanner scans a number and virtually types it
So, as far as I understand you want to show the result of some scanning function that inputs values and check the input value. Looks like there's not really a need for a change handler. Here's a minimal reproducable example for a dummy scanning function. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function scan(i = 0) {
const inp = document.querySelector(`[name='boarding_id']`);
const showIt = document.querySelector(`#showIt`);
if (i < 1) {
inp.value = 4;
i += 1;
} else {
const nr = 1 + Math.floor(Math.random() * 9);
const currentValue = inp.value;
inp.value += nr;
}
if (i < 8) {
showIt.textContent = `Scanning ...`;
return setTimeout( () => scan(i + 1), 100)
}
showIt.textContent = `Done!`;
document.querySelector(`#scan`).removeAttribute(`disabled`);
}
function handle(evt)
{
if (evt.target.id === `scan`) {
evt.target.setAttribute(`disabled`, `disabled`);
return scan();
}
}
<input name="boarding_id" value="" width="600px" readonly>
<span id="showIt"></span>
<p><button id="scan">Scan</button></p>
const input = document.querySelector('input');
const demo_variable = document.getElementById('demo_variable');
input.addEventListener('input', updateValue);
function updateValue(e) {
demo_variable.textContent = e.target.value;
}
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" >
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
<p id="demo_variable"></p>
</form>
You can use the input event, which also triggers when editing happens without the keyboard (mouse drag/drop, context menu, other device...).
Use a regular expression to do the verification. You can access the form via the form property of the input element:
<input name="boarding_id" oninput="/^4\d{7}$/.test(this.value) && this.form.submit()">
It is however better practice to bind events not with HTML attributes, but with JS code. For that purpose give the form element an id attribute (like id="frm"), and then:
const form = document.getElementById("frm");
form.boarding_id.addEventListener("input", (e) => /^4\d{7}$/.test(e.target.value) && form.submit());
You can achieve this in multiple ways. I have shown one below
function myFunction() {
const userInput = document.getElementById("numberinput").value;
document.getElementById("displaynumber").innerHTML = "You typed: " + userInput;
}
function submtValue(value) {
const submitValue =document.getElementById("numberinput").value;
if(submitValue.length === 8) {
// do your validation
alert("Bingo..!!")
}
else {
alert("Minimum length required is 8")
}
}
<input type="number" id="numberinput" oninput="myFunction()">
<p id="displaynumber"></p>
<button type="submit" value="Submit" onclick="submtValue()">Submit</button>
You can add key event like onkeydown or onkeypress on input which will trigger everytime type inside input and once condition fulfilled submit form
This question already has answers here:
Javascript if syntax
(5 answers)
Closed 5 years ago.
It's fixed now.
It's basically a textbox that when the right text is entered should cause something to happen, i have code for it, this is my first time playing around with html. It's not really for anything and just for fun
<body>
<center>
<input id="passfield" type="text" value="" />
<input id="check" type="button" value="Check" onclick="check();"/>
<script>
var field = document.getElementById("passfield").value;
var pass = "password";
function check() {
if field === pass then {
window.location.href = 'the site i want it to go to';
};
};
document.getElementById("check").onclick = check();
</script>
<center>
</body>
The console says: check() isn't a function
You have a couple problems:
You should move the variables field and pass into the function, so that they're defined when the function is called. Otherwise, they won't update - which means field will always be empty (since it was set as soon as the page loaded, when the input's value was '')
Add an event listener in your Javascript, rather than using the 'onclick' attribute. It's nicer because it keeps all of your Javascript together, and you won't have to skim through your HTML every time you hit a JS error.
You have some formatting issues - the if in particular should use the following syntax:
if (condition) {
then do this
} else {
do this
}
You can check out this example on CodePen.
<body>
<center>
<input id="passfield" type="text" value="" />
<input id="check" type="button" value="Check" />
<center>
<script>
function check() {
var field = document.getElementById("passfield").value;
var pass = "password";
if (field === pass) {
window.location.href = "the site i want it to go to";
}
}
document.getElementById("check").addEventListener('click', check)
</script>
</body>
I have a function that currently works with an input to prevent customers from inputting a P.O. Box into an address field. The input that works has an inline onKeyPress event, however the input I need to run the function on doesn't (and I can't access it).
My question is how to incorporate the correct event listener so that my function runs on this inaccessible input?
My JS Fiddle is here: http://jsfiddle.net/ZQQS9/4/
function killPObox(id) {
var idValue = document.getElementById('v65-onepage-shipaddr1').value;
if (id == 'v65-onepage-shipaddr1') {
function runVal() {
if (idValue.substr(0,4).toUpperCase() === "PO B" || idValue.substr(0,5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
setInterval(runVal(),1);
}
}
<!-- Practice input that works -->
1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" onKeyPress="killPObox(this.name)">
<br>
<br>
<!-- Actual input that I need to hook into, cannot edit -->
2. <input type="text" size="25" maxlength="75" name="ShipAddress1" id="v65-onepage-shipaddr1" value="" style="" onkeydown="">
You can use the addEventListener() method like this:
document.getElementById('v65-onepage-shipaddr2').addEventListener('keypress', killPObox('v65-onepage-shipaddr2'));
I think your first input is incorrectly passing this.name as the argument to the killPObox() function. Should you be passing this.id instead? Also you may want to replace 'v65-onepage-shipaddr1' in your killPObox() function to just id to use the argument passed into the function.
I'm sure you have solved this already, but since this is still unanswered (and I stumbled on it) I'll add the solution for future visitors.
Use the correct event
First off, the onKeyPress will actually fire before the typed character has been registered in the input element. So if a user types abc and you do onKeyPress="alert(this.value)" it would alert ab. A better alternative would be onKeyUp, since this would get the last typed character too.
Use the event correctly
Next, the events - your options are:
//inline, not considered "best practice"
<input type="text" name="myinput" id="myinput" onKeyUp="killPObox(this)"/>
//same event as above, but in pure js
document.getElementById('myinput').onkeyup = function (e) {
killPObox(e.target);
};
//or attach an eventListener
document.getElementById('myinput').addEventListener('keyup', function (e) {
killPObox(e.target)
});
All of these should work for the majority of browsers. I would suggest alternative 3, or if you need IE8 support, alternative 2.
The JavaScript, simplified
Your function, killPObox(), should look something like this (using one of the above events):
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
Last but not least..
Finally, a very important part when using event binding, you need to use window.onload(). This is to make sure that both the script and elements that are to be bound are loaded before any code is run.
window.onload = function () {
// my binds, events and calls here
};
An actual working example of all three events:
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr0' || el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
window.onload = function () {
document.getElementById('v65-onepage-shipaddr1').onkeyup = function (e) {
killPObox(e.target);
};
document.getElementById('v65-onepage-shipaddr2').addEventListener('keyup', function (e) {
killPObox(e.target)
});
};
"PO B" or "P.O. " will trigger the alert in all boxes:<br><br>
0. <input type="text" class="quantity" name="v65-onepage-shipaddr0" id="v65-onepage-shipaddr0" onKeyUp="killPObox(this)" />
<br/><br/>
1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" />
<br/><br/>
2. <input type="text" class="quantity" name="v65-onepage-shipaddr2" id="v65-onepage-shipaddr2" />
I have 3 input fields which have values prepopulated and a constant value of total hours 200. I am calculating the avghours as totalhours/datediff of date1 and date2.
My Question is if i change the value of date2 then i want the avghours value to change accordingly. I am not sure which event should be used to fire the method which does the calculation
<input type="text" id ="avghours"/>
<input type="text" id ="date1"/>
<input type="text" id ="date2"/>
Javascript code
function getavg()
{
$('#avghours').val()=totalhours/datediff($('#date2').val(),$('#date1').val(),'day');//datediff is userdefined function to get the datedifference
}
change will fire only if the focus is lost so that might not be possible is there anyother event that i can use.
Thanks
Prady
change
$('#avghours').val()=totalhours/datediff($('#date2').val(),
$('#date1').val(),'day');
to
$("#date2").bind("keyup blur change mouseup",function () {
var d = parseInt(datediff($('#date2').val());
var v = (totalhours/d) + ' ' + $('#date1').val() + ' day'; <-- mergestrings
$('#avghours').val(v);
});
assign via the function instead of the right hand.
If you want to update it immediately when the user types you could use the keyup event.
you could try keypress so...
$('#date2').keypress(function() {
//do calculating average logic here
});
then this would pick up when the value of the textbox has been changed
You can use the .change() event for this.
$("#date2").change(function(){
});
[![<html>
<head>
<title></title>
<script>
function multy(val)
{
alert(val.value+"--"+val.id);
}
</script>
</head>
<body>
<input id="txtdemo" type="text" onchange="multy(this);"></br>
<input id="txtdemo" type="text" onchange="multy(this);">
</input>
</body>
</html>][1]][1]