From element to element script - javascript

how to pass from a function to another function? (script>script) <= element
how do I pass the value of the field validator into the second function?
<script>
$('#card_number').validateCreditCard(function(result) {
if (result.valid) {
const infosuccess = result.card_type == null ? '-' : result.card_type.name
const valid = result.valid
const validlunn = result.luhn_valid
const validlenght = result.length_valid
console.log(infosuccess);
} else {
// $(this)
// const inforeject = result.valid
// console.log(result);
}
});
</script>
<script>
$('#nextaction').click(function(e) {
e.preventDefault();
// my code...
})
</script>

You cannot pass arguments directly in to event handlers. However, there are other approaches you can use.
In this case you can set the 'Next' button to be disabled when the page loads. You can then enable/disable it depending on the result of the credit card validation.
To retrieve the entered card number you can simply read the value from the input when the button is clicked, like this:
const $cardInput = $('#card_number');
const $validateBtn = $('#validate_card');
const $nextBtn = $('#next-action');
$cardInput.validateCreditCard(function(result) {
$nextBtn.prop('disabled', !result.valid); // enable/disable 'next' button
if (result.valid) {
// update the UI to show card details if necessary here...
} else {
console.log('enter a valid credit card number...');
}
});
$nextBtn.on('click', function(e) {
e.preventDefault();
const cardNumber = $cardInput.val();
console.log(cardNumber);
console.log('move to next action here...');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-creditcardvalidator/1.0.0/jquery.creditCardValidator.min.js" integrity="sha512-7omJBgl5QF4QuC3Ge745IO3rDZVMrZWIGK8lSs5lQIFxbWt4d2c7YQg3ZcnonFyRuQslrJ1Ai33Zj/rnXC15+Q==" crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<p>
Test Card number: 5404000000000084
</p>
<label>
Credit card number:
<input type="text" id="card_number" />
<button type="button" id="validate_card">Validate</button>
</label>
<button type="button" id="next-action" disabled>Next...</button>

Related

Why is the JavaScript function checking value before submit

I have been working on a website that randomly generates math equations, I have the javascript algorithm and the HTML but the problem is the function runs before the value is submitted. This is the code:
const duration = 60000
const end = Date.now() + duration
let correct = 0
let error = 0
let result = -1
function ask() {
const op1 = Math.floor(Math.random() * 100)
const op2 = Math.floor(Math.random() * 100)
result = op1 + op2
document.getElementById('eq').innerHTML = (`${op1} + ${op2} = ?`);
}
function handler(evt) {
document.getElementById("btn01").submit();
if ("btn01" == result) {
correct++
document.getElementById('f').innerHTML = ("correct!")
if (Date.now() < end) ask()
} else {
error++
document.getElementById('f').innerHTML = ("wrong :(")
}
}
document.addEventListener("keyup", handler)
ask()
setTimeout(() => {
document.getElementById('q').innerHTML = (`${correct} correct and ${error} error`)
document.removeEventListener("keyup", handler)
}, duration)
<body>
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<h1><span id="eq"></span></h1>
<form id="btn01">
<input type="number">
<input type="button" id="z" value="Submit" onclick="handler(evt)">
</form>
<h1><span id="f"></span></h1>
<h1><span id="q"></span></h1>
</body>
I have tried using onclick in both HTML and javascript but I either did them wrong or they did not work. Note that this is not a repost of other questions asked for different circumstances. Thanks
There are a couple of issues in your code. I have made a couple of changes and show below. The first is that you need to read the value from the input field. Not sure what you were trying to do reading the button. The second is the keyup event handler was annoying because it checked after every key press.
<!DOCTYPE html>
<html>
<body>
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<h1><span id="eq"></span></h1>
<form id="btn01">
<input type="number" id="answer">
<input type="button" id = "z" value="Submit" onclick="handler(event)">
</form>
<h1><span id="f"></span></h1>
<h1><span id="q"></span></h1>
<script>
const duration = 60000
const end = Date.now()+duration
let correct = 0
let error = 0
let result=-1
function ask() {
const op1 = Math.floor(Math.random()*100)
const op2 = Math.floor(Math.random()*100)
result = op1 + op2
document.getElementById('eq').innerHTML = (`${op1} + ${op2} = ?`);
}
function handler(evt) {
//document.getElementById("btn01").submit();
if (document.getElementById("answer").value == result) {
correct++
document.getElementById('f').innerHTML =("correct!")
if (Date.now()<end) ask()
}
else {
error++
document.getElementById('f').innerHTML =("wrong :(")
}
}
//document.addEventListener("keyup", handler)
ask()
setTimeout(()=>{
document.getElementById('q').innerHTML =(`${correct} correct and ${error} error`)
document.removeEventListener("keyup", handler)
}, duration)
</script>
</body>
</html>
several issues.
you should have added a click event listener to submit button, not 'keyup', because it listens to every button pushed and submits the form even though the user might have not submitted willingly.
The main error is caused by -> document.getElementById("btn01").submit(); in the handle function. when you add click event, button click will automatically submit form.
You can handle event listeners in this manner document.getElemetById('buttonIdExample').addEventListener("click", handler).
and remove the listener this way.
You can also define variable -> const Button = document.getElemetById('buttonIdExample') and then -> Button.addEventListener("click", handler).
finally, for the best practice, define more easy-to-understand variable names.

JS Validation Function with 3 arguments(//selector,message,validation function for specific input)

I need to implement code which should add eventlistener and on change event check if the form is valid and add the message
let validate = function(element, info, functionValidate) {
let htmlTag = document.querySelector('fieldElem');//?
htmlTag.addEventListener('change',ev=>{
let notif = document.createElement('span');
document.htmlTag.appendChild(notif);//should add span element next to input
if(fieldElem.value == '')
{
notif.style.visibility = "hidden"; //hide span if nothing happens
}
//I need to implement code which should add eventlistener and on change event check if the form is valid and add the message...
Try the following. You could also use form validation (see Form Validation Set Custom Validity for an example)
function validator(val) {
return (val != '');
}
function validateField(element, validator, message) {
var helper = document.createElement("span");
var parent = element.parentElement;
parent.appendChild(helper);
element.addEventListener('change', function() {
var val = element.value;
if (!validator(val)) {
helper.innerText = message;
} else {
helper.innerText = "";
}
});
}
validateField(document.getElementById('test'), validator, 'Wrong input');
<html>
<body>
<form>
<input id="test" type="text" placeholder="Type here"/>
</form>
</body>
</html>

Tried to get data from a form and append it to a global array, but for some reason the data isn't being added

I am trying to get data from a form and append it to a global array but for some reason, the data isn't being added to the array. The code should basically accept the input from the form and store it into the global array. I updated the HTML so you can see the entire syntax. The value should basically be taken from the form and placed into the global array using the "addnew" function.
function addnew()
{
//calculateAge();
//Accept values entered in form
const fname = document.getElementById('fname').value;
const mname = document.getElementById('mname').value;
const lname= document.getElementById('lname').value;
const dob= document.getElementById('dob').value;
const genderM = document.getElementsByName('male').checked;
const genderF = document.getElementsByName('female').checked;
const age = calculateAge.bYear;
const bodyType = document.getElementById('Body Type').value;
const occu= document.getElementById('occu').value;
const height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert();
}
if(mname==null || mname=="")
{
alert();
}
if (lname==null || lname=="")
{
alert();
}
if(dob==null || dob=="")
{
alert();
}
if (genderM.checked == false || genderF.checked == false){
alert();
}
if (age <=18 || age >=75)
{
alert();
}
if(height>=170 || height<=200)
{
alert();
}
if(bodyType==null || bodyType==""){
alert();
}
if(oocu==null || oocu=="")
{
alert();
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(dob);
records.push(genderM);
records.push(genderF);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
//showAll();
//<h1 class="logo"><img src="New folder/logo.jpg" /></h1>
Information.addEventListener('submit', addnew);
}
</script>
```
first of all. name attribute has nothing to do with form element.
second. Information.addEventListener('submit', addnew); has no meaning because Information is not defined.
and to the core. when submiing a form, the page refreshes defaultly, so the addNew function is aborted like all the other variables. in order to prevent it you have to do as follows.
on submit button ad an id attribute:
<button id="submit" type="submit"> Submit </button>
then on top of your JS, get the button element and add an event listener to it:
let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );
and here is the final step. on the addNew function, add an event argument. and on the begining of the function's code, fire the preventDefault method:
function addnew(event) {
event.preventDefault();
// the rest of the code here
}
by the way. you have a typo here. it should be occu.
if (oocu == null || oocu == "") {
alert();
}
good luck!

Global array remains empty

I am trying to update my global array, but it remains null after I submit a text value(.name) through a submit button.
Please tell me how I can keep track of text values in my global array. Thank you.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#form1").onsubmit = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});
When the form is submitted, a new page is loaded. It loads the URL in the action property of the form. So, your variable goes away.
If you don't want that to happen, prevent the form from being submitted with preventDefault.
For example ...
const name_list = [];
window.addEventListener('DOMContentLoaded', (e) => {
const names = document.querySelector(`.names`);
const add_button = document.querySelector(`.names--add_button`);
names.addEventListener('submit', e => e.preventDefault());
add_button.addEventListener('click', (e) => {
const name = document.querySelector(`.names--name`);
const collected = document.querySelector(`.names--collected`);
name_list.push(name.value);
collected.innerHTML += `<li>${name.value}</li>`;
name.value = ``;
name.focus();
});
});
body { background: snow; }
<form class="names" action="#" method="post">
<label>Name: <input type="text" name="name" class="names--name"></label>
<button class="names--add_button">Add To List</button>
<div>Names Collected:</div>
<ul class="names--collected">
</ul>
</form>
I am see at the moment it's working perfect. but you want add value every time when you click the button. so just changed the type of your
<button type="submit"> to <button type="button">
because when you click on submit page automatically reload in html, an the 2nd thing you need to change your event from onsubmit to onclick and your button to it instead of your form.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#button1").onclick = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});

Displaying Counter on The Actual HTML Button

I have a 'like' button; and underneath the button, I can display the 'like count'.
However, I want the 'like count' value to be displayed on the actual button itself. For example, I want the button to say: "Like 5"
How can I display both text and a variable value on a button?
Maybe you can improving with this code that i did.
HTML
<form id = "form" method = "POST">
<input type = "submit" value = "Like" />
</form>
<br />
<div id = "clicks">
counter = <label id = "count">0</label> clicks !
</div>
JS
function CountOnFormSubmitEvent(form_id, _callback_)
{
var that = this, count = 0, callback = _callback_;
var form = document.getElementById(form_id);
if(form === null) { return null; }
var reset = function(){
count = 0;
};
form.addEventListener("submit", function(evt){
callback(evt, ++count, reset);
}, false);
}
//Reseting Process You can delete if you dont want it.
var counter = new CountOnFormSubmitEvent("form", function(event, count, reset_callback){
event.preventDefault();
if(count >= 10)
{
alert("Reseting the process");
reset_callback();
}
document.getElementById("count").innerHTML = count;
});
Here is the link Jsfiddle.
DEMO JSFIDDLE

Categories