Resetting/Clearing Form Upon Button Click w/ Firebase - javascript

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!

Related

Having problems storing and displaying info in google firebase

I am trying to make a chatroom where the messages are stored in google firebase. I have not learned Javascript yet, but my schoolbook contains all the necessary Javascript code that I need for the task. The chatroom will have two inputs, one for username and one for a message, and a button to send the message. My problem is that whenever I try to send the message it won't store itself in the firebase and thus not be displayed. I apologize for the IDs and classes being in Norwegian, but I'm afraid that if I try to change it I will mess up something in the process.
<form id="skjema">
<input type="text" id="inpAvsender" required placeholder="Brukernavn">
<input type="text" id="inpMening" required placeholder="Melding">
<button type="submit" class="button">Send</button>
</form>
<article id="txtMeldinger"></article>
// google firebase snippet here //
<script>
let database = firebase.database();
let meldinger = database.ref("meldinger");
let skjema = document.
getElementById("skjema");
let inpAvsender = document.
getElementById("inpAvsender");
let inpMening = document.
getElementById("inpMening");
let txtMeldinger = document.
getElementById("txtMeldinger");
function visMelding(snapshot) {
let melding = snapshot.val();
let meldingTekst ='<p>
<b>${melding.avsender}:</b>
<i>${melding.tekst}</i>
</p>';
txtMeldinger.innerHTML = txtMeldinger.
innerHTML + meldingTekst;
}
function regNyMelding(evt) {
evt.preventDefault();
var nyMelding = {
avsender: inpAvsender.value,
tekst: inpMening.value
};
meldinger.push(nyMelding);
inpMening.value ="";
}
meldinger.on("child_added", visMelding);
skjema.onsubmit = regNyMelding;
</script>

Display Firebase data previously/currently submitted

So I'm simply trying to make a page where I have an input for a user's name and age, then they submit that, and it sends that to the Firebase database, and that is working perfectly. The other thing I'm trying to do is display the data submitted in a "view" section. So just display the user's name and age below. I'm struggling to understand/get why my code is not working -- I have an h3 in place that should be replaced by the data that is stored in my database.
Here is my code for the retrieval section
'Age' is what one category of children is called (the other is 'Name')
<h2> View</h2>
<h3 id="showData"> Hello</h3>
<script>
showData = document.getElementByID('showData');
var firebaseDataRef = firebase.database().ref().child('Age');
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.value;
});
the rest of my code:
<input type=text" id="userName">
<input type="number" id="userAge">
<button id="btUpdateMessage" margin-bottom="20px" onclick="addFB()"> Update</button>
<script>
var lblCurrentMessage = document.getElementById('lblCurrentMessage'),
userName = document.getElementById('userName'),
btUpdateMessage = document.getElementById('btUpdateMessage'),
userAge = document.getElementById('userAge'),
rootRef = new Firebase('https://addview-c21e6.firebaseio.com'),
currentMessageRef = rootRef.child('Name'),
currentNameRef = rootRef.child('Age');
function addFB()
{
currentMessageRef.push(userName.value);
currentNameRef.push(userAge.value);
userName.value = '';
userAge.value = '';
}
.value is not a property of DataSnapshot. You need to call the .val() method on it.
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.val();
});
docs: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#val

Forcing a change in the value of the hidden field before submitting a form

I am trying to change the value of a hidden field on submission by JavaScript. In my page there are two buttons, one for going back to homepage (index.php) and another for returning to the first page for data entry (addData.php). I am trying to use a hidden field with id "goHome" to control the routeing. My codes are like this:
HTML (Form only)
<form name = "addDataReal" id = "addDataReal" method = "POST" action = "addDataProc.php" onsubmit="return checkNSub()">
<!-- Other items -->
<input type = "submit" name = "submitBtnF" id = "submitBtnF" class="shortText" style = "width: 120px;" value = "Submit + Home" onclick = "return getGoValue(true)"/>
<input type = "submit" name = "submitBtnR" id = "submitBtnT" class="shortText" style = "width: 120px;" value = "Submit + Next" onclick = "return getGoValue(false)"/>
<input type = "hidden" name = "goHome" id = "goHome" value = "" />
</div>
</form>
Javascript
function checkNSub() {
//form validation functions
//OK then return true
//Not then return false
}
function getGoValue(goHome) {
if (goHome) {
document.getElementById("goHome").value = "true";
} else {
document.getElementById("goHome").value = "false";
}
return true;
}
Before this I have tried many other versions and I refered to these few questions:
Set form hidden value on submit
Setting a form variable value before submitting
How to change the value of hidden input field before submitting
But none of the methods were working for me.
For practical purposes there is a workaround for this, but I want to know if I would like to keep these two buttons, how should my code be modified so that the value of "goHome" can be changed before the form is submitted? After many attempts I am still getting $_POST["goHome"] = "".
Also, why is the form submitted before the value is actually changed when the code is placed before that?
Thanks!
It's old question But I thought If any one still looking for the answer , here it is
You can try jquery $('input[name="goHome"]').val('true');
or JS - document.getElementByName("goHome").value = "true";
This will work for sure.
While updating any value at the time of submitting for use name selector instead of ID, that will save you some time :)
When we try to change value of Hidden field at the time of submitting form it didn't update value because DOM has already detached the ID from the input parameter but name is still there because name is going to be passed in form.
If anyone find this useful and they do not have to work for lot hours for a simple solution :)
Happy Coding :)
Various ways to achieve this. Firstly though keep in mind that you are using type="submit" <input> inside a <form> , and that means that they will automatically submit the form regardless of an onclick event or not.
One as much as less intrusive (to your code) way is the following:
Take out the submit inputs from your form like this:
Example :
<form name = "addDataReal" id = "addDataReal" method = "POST" action = "whatever.php">
<!-- Other items -->
<input type = "hidden" name = "goHome" id = "goHome" value = "" />
</div>
</form>
<input type = "submit" name = "submitBtnF" id = "submitBtnF" class="shortText" style = "width: 120px;" value = "Submit + Home" onclick = "return getGoValue(true)"/>
<input type = "submit" name = "submitBtnR" id = "submitBtnT" class="shortText" style = "width: 120px;" value = "Submit + Next" onclick = "return getGoValue(false)"/>
Change your getGoValue() and checkNSub() functions like this :
function checkNSub() {
//form validation functions
//OK then return true
//Not then return false
var myForm = document.getElementById('addDataReal');
myForm.submit();
}
function getGoValue(goHome) {
if (goHome) {
document.getElementById("goHome").value = "true";
console.log(document.getElementById("goHome").value);
checkNSub();
} else {
document.getElementById("goHome").value = "false";
console.log(document.getElementById("goHome").value);
checkNSub();
}
return true;
}
Try it out.
P.S : A couple of console.logs so you can check out the value changing. Comment out checkNSub(); to see them in your console. Nevertheless keep in mind that you are posting a Form which means you are going to load a new page from the server , this new page will be agnostic regarding your "goHome" value. The "goHome" value exists only while you are on the same page. The moment your DOM is "recreated" you will lose it.
P.S.2 :
Your return true; inside the getGoValue(); is not needed in my
example. You can remove it.
the return in your onclick = "return getGoValue(true)" is also
not needed and you can remove it
P.S.3 :
This reply is focused on keeping most of your code intact. In reality now that you have your inputs outside the form there is no need for them to be of type="submit" you should change them to <button> with onClick events (or Listeners).

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

JavaScript - How to assign user input value to variable inside script

Using widget script--http://socialmention.com/tools/-- from Social Mention. Tried to modify by adding input box to allow user to change social media topic (var smSearchPhrase). I created a function [smSearch()] to retrieve user data (smTopic), assign it to a new variable (var newTopic) and then assign that value to var smSearchPhrase. The assignment does not work.
The function appears to work based on values observed via alerts, however, I cannot figure out how to assign the value from var newTopic to var smSearchPhrase inside the script. I experimented by placing script inside the function, but that didn't work either. Any assistance is appreciated.
If I failed to include all necessary information, please advise. Thanks for any assistance.
HTML:
<form>
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button onclick="smSearch()">Submit</button>
<input type="reset">
</form>
Function: (includes alerts to check values)
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
Script: var smSearchPhrase in original has value assigned, e.g. var smSearchPhrase = 'social mention';
<script type="text/javascript">
// search phrase (replace this)
var smSearchPhrase;
// title (optional)
var smTitle = 'Realtime Buzz';
// items per page
var smItemsPerPage = 7;
// show or hide user profile images
var smShowUserImages = true;
// widget font size in pixels
var smFontSize = 11;
// height of the widget
var smWidgetHeight = 800;
// sources (optional, comment out for "all")
//var smSources = ['twitter', 'facebook', 'googleblog', 'identica'];
</script>
<script type="text/javascript" language="javascript" src="http://socialmention.s3.amazonaws.com/buzz_widget/buzz.js"></script>
I think your form is submitting back to the backend, you need to stop the form from doing that by returning false from onsubmit or canceling the event.
So this should work:
<form onsubmit="return smSearch();">
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button>Submit</button>
<input type="reset">
</form>
And return false in your JavaScript:
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
return false;
}
Personally I'd use preventDefault() on the event argument (not shown here), but that only works across all browsers when you also include a JavaScript library like jQuery as some versions of IE use a bubble property on the event or something.

Categories

Resources