How to call variables from different events together? - javascript

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.

Related

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

Send message from input field into database by pressing enter

i've done a web chat which the codes are:
<div id="namebox">Name: <input type="text" id="name" autofocus autocomplete="on" ></div>
<div id="msgbox" >Message: <input type="text" id="message"></div>
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit">Submit</button></div>
So, the message goes into the database fine by clicking the button submit, however i was wondering to ad a code to jut press enter and it will be sent, so there will be 2 options.
I am using onClick and onKeypress which it is not working.
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit" onkeypress="postMessageToDB(this, event); return false;">Submit</button></div>
Where the javascript is:
<script type="text/javascript">
function postMessageToDB(inputElement, event) {
if (event.keyCode == 13) {
inputElement.div.submit();
}
}
</script>
Im not using form because it was asked to be div, not form.
Really appreciate for any help.
Thank you very much
Your code provided will only work when postMessageToDB() is called... it's not listening for a keypress.
Using jQuery:
$(window).keyup(function(e) {
if( e.keyCode==13 ) {
postMessageToDB([...]);
}
}
You need to call the function, you can do this by adding an EventListener to document and then check if it's enter that was pressed.
var keyevent = (/Firefox/i.test(navigator.userAgent)) ? "keypress" : "keydown"; // fit browser
document.addEventListener(keyevent, function(e) {
if (event.keyCode == 13) {
var a = document.getElementById('name').value; //get field values
var b = document.getElementById('message').value; //get field values
postMessageToDB(inputElement, event); // as I said, not sure what this will do, but you need to get the data you want to pass first within this function.
}
});
Then, just remove the keypress checkup from you function and you should check this line, I can't see that this is going to work:
inputElement.div.submit();

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.

Retrievving eventTarget after addEventListener in 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);
}

HTML5 local storage, validating required text box issue

I have a survey. On button click need it to validate certain fields required/store locally/ go to confirmation page(to prevent user from resubmitting). Only 'FirstName''Hostipal' required atm.
Problem is when all required fields are filled, it fails to go to confirmation.html. If i leave 1 required field open, It doesnt validate and goes to confirmation. If all 'required' syntax is taken out, It doesnt go to confirmation
<label>First Name*:</label> <input required title="Name is required" id="FirstName" name="MainName" type="text"/>
In all cases, It still stores to local storage however. Any input on validating required fields would be appreciated. Hopefully can put it in my clicked() function.
<button type="submit" value="Save" id="Save" >Submit Form</button>
function
$( document ).ready(function() {
$('#Save').click(function (e) {
if (confirm('Are you sure you want to submit? You will not be able to go back.')) {
var person = $("#FirstName").val() + "." + $('#LastName').val();
$('input, select, textarea').each(function () {
var value = $(this).val(),
name = $(this).attr('name');
localStorage[person + "." + name] = value;
window.location.href = "Confirmation.html";
console.log('stored key: ' + name + ' stored value: ' + value);
});
}
});
});
If the above doesn't show my problem, here is the whole: http://jsfiddle.net/smZHe/1/
each helper method in jquery executes the function we pass to it once for each item in the initial array. You are trying to execute below statement multiple times (once for each input, select, textarea).
window.location.href = "Confirmation.html";
You can use a variable instead as flag to mark validation failure. In the end, you can check variable and navigate conditionally.

Categories

Resources