Store html form input in array - javascript

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

Related

Why isn't my localStorage.setItem() and localStorage.getItem() storing a value?

I want to store a user input value using localStorage then use that value in my countdown timer.
Here is the HTML where the user inputs their data:
<form action='/' method= 'GET' id='settings'>
<label> Work Time </label>
<input class='settingInput' type='number' id='workInput'>
<label id='short-break'> Short Break </label>
<input class='settingInput' id='shortBreak'>
<label id='long-break'> Long Break </label>
<input class='settingInput' id='longBreak'>
<button id = 'set-values'>Submit</button>
</form>
this is the javascript to store and retrieve the data:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
Here is the codepen for the whole project: https://codepen.io/Games247/pen/XWJqebG
This is my first time using setItem and getItem so I may be overlooking something obvious.
Currently it looks like a pair of brackets is stored in the localStorage where workTimeKey should be.
Your linked code on codepen has a problem, in fact the code posted here corrects said problem.
var workTimeSerialized = JSON.stringify(document.getElementById('workInput'));
The above is your codepen, the problem is you are trying to serialize the HTML element to JSON rather than it's value hence the '{}' you see in your session storage.
You need to ensure it's the value of the input element and not the element itself you serialize. Like i mentioned, your code posted here resolves the issue ;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
Note: Whenever you see '[]' or '{}' in session storage rather than your intended value, you are either passing an object directly or an element in your case.
Edit:
'you are most likely not either'
Your input values should be read in the submit click handler otherwise, you get the value of the input before sumbit and not after
So your code:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
becomes:
submitButton.addEventListener('click', (e) => {
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})

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.

Resetting/Clearing Form Upon Button Click w/ Firebase

I'm having trouble actually clearing the content of a form upon button click with Firebase. I'm able to use type="reset"on another form I have that just has one text field, however, the second form has two text fields and when I try the following:
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
or I try this (something just using reset()):
function clearFields() {
document.getElementById(userCityEmail).reset();
document.getElementById(cityTextField).reset();
}
The page will reload but nothing is sent to the Firebase. If I don't use the above functions and leave the text within the text field, it sends the content to Firebase. Where am I going wrong? Thanks in advance!
Here's my HTML form:
<form id="myform" method="post">
<input type="email" class="contactUsEmail" id="userCityEmail" placeholder="Enter email" name="contactUsEmail">
<input type="text" class="contactUsEmail" id="cityTextField" placeholder="City" name="contactUsCity">
<button type="submit" id="citySubmitButton" onclick="submitCityClick(); clearFields(); return false;" class="btn btn-primary contactUsButton">Submit</button>
</form>
Javascript:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
var citySubmitButton = document.getElementById('citySubmitButton');
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push().set(userEmail);
}
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
Figured out what happened now.
The problem you had was that you were calling
firebaseRef.child("potentialCities").push().set(userEmail);
This doesnt make sense. Either use just push(userEmail) or set(userEmail).
The difference between these two things is that push will create a random ID under the potentialCities tree node, and set will put user email data right under the same object. It probably will be overwritten. Push is recomended for this case.
To explain the field clearing, still have the clearfields method in the submit click method. Code beneath
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push(userEmail);
clearFields()
}
This also expects that you have the right firebase ref, have you checked the url you are using?
Another thing you are doing wrong is that you are declaring these variables:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
Then trying to get the elementById, with that variable, in clearFields:
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
This doesnt work, you have to either get it by string in clearFields or just use the variable you declared:
userCityEmail.value = "";
or
document.getElementById('userCityEmail').value = "";
I would not recommend to just pull in jQuery just for that reason. It's a big library, and if you can suffice with vanilla javascript, do that!

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

copy form to Backbone.js model

I have a form:
<form>
<input type="text" name="email" >
<input type="text" name="phone" >
<input type="button" value="ok" />
</form>
When clicking the button, I'd like to copy the form values to a corresponding model.
I've found Backbone.ModelBinder which will automatically copy values to model whenever the values are changed, but that's not what I want, I just want to copy the values when the button is clicked.
write a custom function into the view where the form is located and bind it to the ok click event:
events: {
...
'click input[name="ok"]': 'copyFormToModel'
...
},
...
copyFormToModel: function() {
var email = $('input[name="email"]').val();
var phone = $('input[name="phone"]').val();
// Perform some sort of validation
this.model.email = email;
this.model.phone = phone;
}
This isn't the prettiest answer, but if you have just one small form in your page, then using some library or plugin might be a bit overkill. If you want to use a plugin or library, then for your case I think backbone-forms could do the trick. It features updating the model bound to the form with a method call rather than every time fields are updated.
This code may be you need:
events: {
...
'click input[value="ok"]': 'collectData2Model'
...
},
...
//suppose employee is your model
collectData2Model: function(e) {
var employee = new Employee();
var attr = {};
$('input').each(function(){
var input = $(this);
attr[input.attr('name')] = input.val();
});
employee.bind('error',function(model,error){
alert(error);
});
// set method will automatically call the model's validate method
employee.set(attr);
}

Categories

Resources