Retrievving eventTarget after addEventListener in javascript - javascript

I have 2 input fields in an html document.
Username : <input type="text" name="username" id="username"><div id='use'></div>
Email : <input type="text" name="email" id="email"><div id='ema'></div>
And a javascript file.
window.onload = initialise;
function initialise() {
username = document.getElementById('username');
username.addEventListener('keyup', respond, false);
email = document.getElementById('email');
email.addEventListener('keyup', respond, false);
}
function respond() {
//code
}
Is there any way in which I can know inside the respond() function whether it was the username field or the email field for which the respond() method is called?
Both procedural code and OOP is welcome thought procedural code is preferred.

Yes, pass in event and use event.target.id
function respond(e) {
//code
var id = e.target.id; //id of called element
}

Or you can use this provided that respond was not bounded to another context. Demo.
function respond() {
console.log(this.id);
}
MDN
It is often desirable to reference the element from which the event
handler was fired, such as when using a generic handler for a series
of similar elements. When attaching a function using
addEventListener() the value of this is changed—note that the value of
this is passed to a function from the caller.

With tymeJV's answer and a correction in your code, I created this fiddle for you.
HTML:
Username : <input type="text" name="username" id="username"><div id='use'></div>
Email : <input type="text" name="email" id="email"><div id='ema'></div>
JS:
window.onload = initialise();
function initialise() {
username = document.getElementById('username');
username.addEventListener('keyup', respond, false);
email = document.getElementById('email');
email.addEventListener('keyup', respond, false);
}
function respond(e) {
//code
alert(e.target.id);
}

Related

How to call variables from different events together?

I am trying to learn how to call variables from different events.
I have 2 inputs, without a submit button. So, the way I get the value is by using the keyup event.
My Code:
function myPhone() {
$("#phone").keyup(function() {
var phone = $(this).val();
});
return phone;
}
function myEmail() {
$("#email").keyup(function() {
var email = $(this).val();
});
return email;
}
function myValidation() {
var myPhone2 = myPhone();
var myEmail2 = myEmail();
alert(myPhone2 + " - " + myEmail2);
}
myValidation();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="phone" id="phone" placeholder="phone">
<input type="text" name="email" id="email" placeholder="email">
Explanation Behind My Code:
First, I create a function called myPhone() where it saves the value of what has been inserted by the user based on keyup. I do the same for email and create a function myEmail().
Now, I created another function named myValidation and tried to call the values I get in myPhone() and myEmail() and then I try to display the values in an alert box.
But, this is not working for me. I can see that it will alert upon page load, and show undefined, which makes sense for me.
But why is it not tracking the keyup event? And why is the 2 variables not getting called in? Have i done it wrongly? Can someone please guide me on this with explanation?
You're trying to alert both values even if the event isn't yet triggered. You should
Create a global access to the email and phone variables, could also be an object
Attach the event first
Run myValidation() after both events are triggered, adding a flag to do so;
Alert the values from the global scope
Following your code, you can:
//Create global variables
var phone, email;
//Create function to attach events
function setEvents(){
//switched to change event
$( "#phone" ).change(function() {
phone = $(this).val();
myValidation(); //call after
});
$( "#email" ).change(function() {
email = $(this).val();
myValidation(); //call after
});
}
//Prepare myValidation() function to call after both events are triggered
function myValidation() {
//Check if phone and email exists before alerting from the global scope
if(phone && email) alert(phone + " - " + email);
}
setEvents(); //initiate function to attach events to element
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="phone" id="phone" placeholder="phone">
<input type="text" name="email" id="email" placeholder="email">
But like others said, you can just directly get $(element).val() without any variables at play; but we are following from your logic which I think is much better for a direct answer to the problem.

Store html form input in array

I am trying to store the inputs of the html form in a simple array.
I found some simple tutorials but my code is still not working, maybe I just can't see the fault.
This is how I made an array:
var person = [];
person[0] = $('#email').val();
person[1] = $('#password').val();
And this is my html, I have the span #demo, where I checked if there's a value in the array:
<input id="email" type="email" name="email" required="required"/><span id="errorfld"></span>
<input id="password" name="password1" type="password" required="required"/><span id="result"></span><span id="demo">text</span>
Then I have a function, which is called on focusout:
function demo(){
$('#demo').text(person[0]);
}
Do I have to search my fault somewhere else?
One way is to use $.serializeArray() to get all the values from the form.
Example
$('#form').on('submit', function(event) {
event.preventDefault();
var data = $(this).serializeArray();
$('#demo').text(data[0].value);
});
DEMO http://jsfiddle.net/7ysbd962/1/
If you just get the value when the page loads document.ready the input fields are still blank. You need to retrieve the values when you want to use them like this...
$(function(){
function updateDemo(){
var person = [];
person[0] = $('#email').val();
person[1] = $('#password').val();
$('#demo').text(JSON.stringify(person));
}
$('#email').on('blur',updateDemo);
$('#password').on('blur',updateDemo);
});
Here is an example
You could also use a different listener like keyup to update the value every time the key is pressed.
Another example

Issue on Referencing $(this) to Multi Inputs on Submit Click

I am trying to create a simple Validation Function for validating User inputs at This Demo.
now my problem is using the $(this). to reference for each of the inputs which has same type. For example at this example I tried the
$('#email1').parent().after('<div class="err" role="alert">Can Not be Empty</div>');
which works but when I use the
$(this).parent().after('<div class="err" role="alert">Can Not be Empty</div>');
I am not getting any thing for validation
Here is the code which I have
<div class="form-group">
E-Mail 1: <input type="email" name="email1" id="email1"/>
</div>
<div class="form-group">
E-Mail 2: <input type="email" name="email2" id="email2" />
</div>
<button type="button" id="exe">Validate</button>
<script>
$(function() {
function emailInput(inputData) {
inputData = $.trim($(inputData).val());
if (inputData == "") {
$(this).parent().after('<div class="err" role="alert">Can Not be Empty</div>');
} else {
return inputData;
}
}
$("#exe").on("click",function(){
$(".err").hide();
if (emailInput($('#email1').val())){
alert($('#email1').val());
}
});
});
</script>
jQuery provides context to it's methods (i.e. what the value of this is), your function does not have this provided so this refers to window or the global scope. If you want to use this and have it refer to the current DOM node, you have to call your function using the call,apply or bind methods and provide the value of this as jQuery does.
// first argument is the context, i.e. what this refers to, subsequent arguments are your function arguments
emailInput.call($('#email1').get(0), $('#email1').val())
Here are some links to explain call, apply and bind:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
this is what I explained in the comments: DEMO
$(function() {
function emailInput(elem) {
inputData = $.trim(elem.val());
if (inputData == "") {
elem.parent().after('<div class="err" role="alert">Can Not be Empty</div>');
} else {
return inputData;
}
}
$("#exe").on("click",function(){
$(".err").hide();
if (emailInput($('#email1'))){
alert($('#email1').val());
}
});
});
The only problem with your code is that in your emailInput function there is no reference for this that is why your code is breaking at this point.
this works when an element is hit with an event and you bind it to the event handler. Only this element can be used with the this reference., for rest elements like parents children you need to use ids or any other selector. I hope this make it clear what you are doing wrong.

Stop form submission with submit eventlistener

I'm trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the function. There are no JS errors being thrown.
Am I making some stupid mistake?
<form id="highlight">
Row: <input type="text" name="rows" value="1" id="rows">
Column: <input type="text" name="cells" value="1" id="cells">
<input type="submit" name="Submit" value="Highlight" id="Submit">
</form>
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function() {
alert('hi');
return false;
}, false);
</script>
I always call event.preventDefault() on event listeners that I want to cancel the event for, as well as return false. This always works for me.
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function(event)
{
event.preventDefault();
alert('hi');
return false;
}, false);
</script>
To prevent form submission, I've always used the "onclick" event to call a javascript method which will do something and then submit from there. You can also setup the form as follows:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Once submitted, the validateForm() method can prevent submission if necessary:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
Well this is the way I would do it :
function validate (form)
{
// return false if some fields are not right
}
function setup_form_validation (form)
{
form.addEventListener (
'submit',
function (f) { // closure to pass the form to event handler
return function (evt) {
if (!validate (f)) evt.preventDefault();
// Return status doesn't work consistently across browsers,
// and since the default submit event will not be called in case
// of validation failure, what we return does not matter anyway.
// Better return true or nothing in case you want to chain other
// handlers to the submit event (why you would want do that is
// another question)
};
} (form),
false);
}
I would rather have a boolean holding the form validation status, though. Better update the status each time a field changes than do the check only when the user tries to submit the whole form.
And of course this will fail in IE8- and other older browsers. You would need yet another bloody event abstraction layer to make it work everywhere.

Javascript form validation: how to force focus to remain on 'incorrect' field?

I can't believe that I can't find the answer to this question but I really have searched and can't find it! honest!
anyway - here is the question: I am trying to create a validation function for a form that will not permit the user to proceed to the next form field if the field doesn't validate.
I just want the 'incorrect' field to have focus until it is 'correct'.
because this is for a JS class I cannot use jQuery or any other framework.
here is one of the HTML fields:
<li>Number 1:<input class="field2" type="text" id="star1" onchange="validateAndDraw(this.value);"></li>
and here is a truncated version of the JS function:
function validateAndDraw(theValue) {
if (isNaN(theValue)) {
alert("no good");
} else {
[do stuff here]
}
}
I have tried using 'this.focus();' and 'this.parentNode.focus();' but no joy.
I am sure the answer is ridiculously simple, but I can't seem to find it.
thanks,
bennett
Try sending the object reference to the function instead of the value.
So in your input event:
validateAndDraw(this);
And change your function to:
function validateAndDraw(input) {
if (isNaN(input.value)) {
alert("no good");
input.focus();
} else {
[do stuff here]
}
}
As a side, I would suggest looking into Progressive Enhancement.
document.getElementById('star1').focus();
Using this inside your function will refer back to the function.
Alternatively, you could pass the object in the onclick event:
<input class="field2" type="text" id="star1" onchange="validateAndDraw(this);">
so the function could look like
function validateAndDraw(obj) {
alert(obj.value);
}
Try calling focus() in the blur event.
Also, this in your function refers to the global context, not the element.
(It only refers to the element inside the inline handler; you are making an ordinary function call from there)
You should change your function to accept the element as a parameter (which you can pass as this insidethe inline handler)
Why not pass in the element?
function validateAndDraw(theElement) {
var theValue = theElement.value;
if (isNaN(theValue)) {
alert("no good");
theElement.focus()
} else {
[do stuff here]
}
}
Send as trigger
There are for each loop function for check input in form.
If there are input[x].value = "", so alert and focus in it, next input and next alert
<html>
<body>
<form onsubmit="return validateForm(this)">
Name: <input type="text" name="name"><br />
E-mail: <input type="text" name="email"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Send">
</form>
<script >
function validateForm(input) {
for (x in input) {
if (input[x].value == "") {
alert(input[x].name + " must be filled out");
input[x].focus();
return false;
}
}
}
</script>
</body>
</html>

Categories

Resources