Run function only once for particular element [duplicate] - javascript

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

Related

Error with Javascript TypeError code, variable undefined

I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.

Javascript/HTML How to remove element of javascript array dynamically through HTML input/text box [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 5 years ago.
The websites purpose is to store and order book titles, I need to make it so that the user can delete books they have entered into the array. I'm pretty new at Javascript but have a little bit of Java and C# experience.
Little bit stuck on this one. Was doing some reading about removing elements from the array within the code with splice and delete. But when i create a function for it, it removes everything in the array and not just the text box input string.
For the purposes of my assessment it needs to be done without using a third party library.
I'm aware that this is probably not the best way to go about storing data since it clears upon refresh or closing the page.
HTML:
<!DOCTYPE html>
<html>
<body>
<h1> Prototype Book Storage and Display </h1>
<form id = "formWrapper">
Search<br>
<input id="myTextBox" type="text" name="search">
<br>
<input onClick="submitData()" type="button" value="Submit Book">
<input onClick="printBooks()" type="button" value="Find Book">
<input onClick="deleteData()" type="button" value = "Delete Book">
<p id = "booktitle"></p>
</form>
</body>
</html>
Javascript:
var myFormData = []; //declare an array
var value1;
//Prints My Books to a list
function printBooks() {
clearBook();
alert(myFormData);
document.getElementById('booktitle').innerHTML = myFormData;
}
//Submits input to array
function submitData()
{
value1 = document.getElementById("myTextBox").value;
myFormData.push(value1);
alert(myFormData);
clearField();
}
//Deletes data from the array
function deleteData()
{
deleteValue = document.getElementById("myTextBox").value;
myFormData.splice(deleteValue);
alert(deleteValue + " " + "Deleting your book");
}
//clears textbox field
function clearField()
{
var txt2 = document.getElementById("myTextBox");
txt2.value = "";
}
//Refreshes book object model
function clearBook()
{
var txt3 = document.getElementById("booktitle");
txt3.value="";
}
The problem is in
myFormData.splice(deleteValue);
splice() expects a starting index, you are passing a string value. See How do I remove a particular element from an array in JavaScript? on how to use it.
In your case it would be
// get the index of the value in the array or -1 if it does not exist
var index = myFormData.indexOf(deleteValue);
// only try removing it, if it exists in the array
if (index !== -1) {
myFormData.splice(index, 1);
}

First time, password field [duplicate]

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>

How to pass a JavaScript statement to a function? [duplicate]

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>

How to find which all check box is selected [duplicate]

This question already has answers here:
Javascript to check whether a checkbox is being checked or unchecked
(7 answers)
Closed 10 years ago.
I have a list of check box and i need to write a javascript function to find out which all the check boxes are clicked. can any one help?
<input type="checkbox" name="check_group[]" id="name" /> name
<input type="checkbox" name="check_group[]" id="age" /> age
<input type="checkbox" name="check_group[]" id="school" /> school
<input type="checkbox" name="check_group[]" id="company"> company
So if I click on only 2 I need to know which are the 2 I clicked on so that I can send for server side processing.
Given that the checkboxes all have the same name, you can use a function like:
function getChecked(name) {
var els = document.getElementsByName(name);
for (var i=0, iLen=els.length; i<iLen; i++) {
if (els[i].checked) {
// els[i] is checked, do stuff
}
}
}
Have a input type button and call this function on it's click
function callMeOnButtonClick()
{
var selectedBox = document.querySelectorAll('input[name*=check_group]');
// You may also use
// var selectedBox = document.getElementsByName('check_group[]');
// The above two statements will give you the same result. i.e., array of checkboxes having name check_group[]
var count++;
for(var i=0; i<selectedBox.length; i++)
{
if(selectedBox[i].checked)
{
count++;
// Do processing
}
}
alert("Number of selected checkbox: "+count);
}
you can use jQuery to find the checked elements in javascript
alert($("check_group[]:[checked=checked]").length);
and then you can use those values to send server side for processing

Categories