I have a simple form requesting couple questions from the user. I am attempting to connect my FireBase account so the realtime database can get updated when the user presses the submit button. However, the database is not receiving any information. I have attached the code.
The problem is somewhere in the HTML or JavaScript. I have inserted random alerts to see if they would work, and I get them to come up. I removed some of the "dataLink.push" commands, due to my FireBase only containing 2 values (name, value). I am a beginner with FireBase.
var config = {
apiKey: "AIzaSyCdqgGdZH8bWSMiHEM7ZoeWSNfZ04uA3Y8",
authDomain: "errandboi-f1cf5.firebaseapp.com",
databaseURL: "https://errandboi-f1cf5.firebaseio.com",
storageBucket: "errandboi-f1cf5.appspot.com",
};
firebase.initializeApp(config);
// Creates a variable called databaseLink that links to our database.
var databaseLink = new Firebase('https://errandboi-f1cf5.firebaseio.com/');
// Create javascript variables that link our previous HTML IDs. Remember, we can't use regular HTML inside a script tag, so we need to use JQuery to reference any previous HTML. A $ means we are using JQuery
var messageField = $('#task');
var nameField = $('#name');
var contactField = $('#contact');
var locationField = $('#location');
var miscField = $('#misc');
var messageList = $('#example-messages'); // DELETE MAYBE?????
//alert(messageField);
// If the enter key is pressed, push the values in the text boxes to our database.
function push(){
alert("yo");
messageField.keypress(function (e) {
if (e.keyCode == 13) { //13 is the enter key's keycode
alert("yo");
if (messageField.val() == ""){ //Ensure that an activity was entered.
alert("Please let us know how we can help!");
}else{
//push data to firebase and then clear the text box
databaseLink.push({name:nameField.val(), value:messageField.val()});
messageField.val('');
}
}
}
});//end of keypress function
<DOCTYPE! html>
<html>
<head>
<meta charset="UTF-8">
<!--THIS IS NEEDED TO IMPORT FIREBASE LIBRARIES -->
<script src="https://cdn.firebase.com/js/client/2.2.1/firebase.js"></script>
<!-- THIS IS JUST A NICE LOOKING FONT -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!--THIS IS NEEDED TO IMPORT JQUERY LIBRARIES -->
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
<!-- THIS IS TO IMPORT MY JS FILE -->
<script src="index.js"></script>
<link href="style.css" rel="stylesheet" />
<title>ErrandBoi!</title>
</head>
<body>
<div id="container">
<header>
<h1 class="title">ErrandBoi</h1>
</header>
<div id="banner">
<h2>Your Helping Hand in Every Situation</h2>
</div>
<div id="content">
<p class="content">Ever have an emergency while you are in class? Life has got you all tied up but your tasks won't do themselves? Well, you are at the right place for help. Let ErrandBoi take the stress off your shoulders while you can do what really matters. Simply, fill out the form below with any* task that you may need help with and one of our drivers will help you out as soon as possible!</p>
<br><br><br><br><br><br><br><br><br>
<div class="form-style-5">
<form method="POST">
<fieldset>
<legend><span class="number">1</span> Your Information</legend>
<input type="text" name="field1" id="name" placeholder="Your Name *">
<input type="email" name="field2" id="contact"placeholder="Contact Information (Email, Phone Number, etc.) *">
<input type="location" name="field2" id="location" placeholder="Your Location (i.e. McNutt, Hodge Hall, exact address, etc.)*">
<input type="text" name="field3" id="misc" placeholder="Miscellaneous Information That May Be Important"></textarea>
<label for="job">Urgency:</label>
<select id="job" name="field4">
<optgroup label="Urgency level: just for us to prioritize properly">
<option value="Not Urgent">Low (ETA: Up to an hour)</option>
<option value="reading">Normal (ETA: Up to 45 mins)</option>
<option value="boxing">Critical (ETA: ASAP!)</option>
</optgroup>
</select>
</fieldset>
<fieldset>
<legend><span class="number">2</span>Task that needs completion</legend>
<input type="text" name="field3" id="task" placeholder="Let Us Know How We Can Help!*"></input>
</fieldset>
<input type="submit" value="Apply" onClick = "push()"/>
</form>
</div>
</div>
</div>
</body>
</html>
You are trying to mix Firebase v2 and Firebase v3. In order to make it work you should:
1) Import the right Firebase sdk (and remove the old one from your code)
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase.js"></script>
2) Get a reference to the firebase database
var databaseLink = firebase.database().ref();
NOTE: Firebase has been updated recently, the new documentation is at firebase.google.com (not firebase.com)
Hope it helps ;)
Related
I have a Google Library with HTML form, process form script addNewItemand script to run the form in popup window addItem.
function addItem()
{
var html = HtmlService.createHtmlOutputFromFile('input/form.html');
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add New Recipe');
}
function addNewItem(form_data)
{
var url = "SPREADSHEET_URL_TO_DATA_COLLECTION";
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName('List');
var asiaTime = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd");
var dishName = form_data.dish_name;
var cuisineName = form_data.cuisine_name;
var placeName = form_data.place_name;
var categoryName = form_data.category_name;
var num = sheet.getRange(sheet.getLastRow(), 1).getValue() + 1 || sheet.getLastRow();
sheet.appendRow([num, dishName, cuisineName, placeName, categoryName, asiaTime]);
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myform">
<div class="block form-group">
<label for="dish_name">Dish name</label>
<input type='text' name='dish_name' id="dish_name" required="required"/>
</div>
<div class="block form-group">
<label for="place_name">Place</label>
<select id="place_name" name="place_name" type="text" required>
<option value="LL4H">LL4H</option>
<option value="LL4T">LL4T</option>
</select>
</div>
<div class="block form-group">
<label for="cuisine_name">Cuisine</label>
<select id="cuisine_name" name="cuisine_name" type="text" required>
<option value="Asian">Asian</option>
<option value="Western">Western</option>
</select>
</div>
<div class="block form-group">
<label for="category_name">Category</label>
<input id="category_name" name="category_name" type="text" list="quote-choices" required>
<datalist id="quote-choices">
<option value="Starter">Starter</option>
<option value="Main course">Main course</option>
<option value="Veggi side">Veggi side</option>
<option value="Carbs side">Carbs side</option>
<option value="Dessert">Dessert</option>
<option value="Dough">Dough</option>
<option value="Sauce">Sauce</option>
<option value="Drink">Drink</option>
<option value="Other">Other</option>
</datalist>
</div>
<div class="block">
<button type="submit" class="action">Submit</button>
</div>
</form>
<script>
document.querySelector("#myform").addEventListener("submit",
function(e)
{
e.preventDefault(); //stop form from submitting
console.log(this)
google.script.run.withSuccessHandler(()=> google.script.host.close()).addNewItem(this);
}
);
</script>
</body>
</html>
I connected this Library with the Google Spreadsheet and declared new function to run library script to open the form.
function createRecipe() {
RecipeBuilder.addItem();
}
function addNewItem(form_data) {
RecipeBuilder.addNewItem(form_data);
}
Form appears in popup window well.
I click Submit to submit my data from the form, but serverside process does not start.
How to run this form correct? Where I'm wrong? How to fix it?
UPDATED
It's still does not work with library but works well if I put it in bound-container script of some spreadsheet. Unfortunately, I can't use it in bound-container because full code of addNewItem(form_data) function must replicate current spreadsheet. Finally it will be 1000+ Google Spreadsheets with same numbers of bound-containers. It will be super complicated to update it
I believe your goal and situation as follows.
You want to use addItem(), addNewItem(form_data) and input/form.html as a GAS library.
When you call this library from the client side, when the submit button is clicked, the data is not sent.
You want to remove this issue.
The library name is RecipeBuilder.
For this, how about this modification?
Modification points:
I think that the reason of your issue is google.script.run.addNewItem(this);. In this case, when addNewItem(this) is run, this function is searched from the GAS project. By this, an error occurs like Uncaught TypeError: google.script.run.addNewItem is not a function. I think that this is the reason of your issue.
In order to remove this issue, how about the following modification? In this modification, one more function is added to the client side.
Modified script:
function createRecipe() {
RecipeBuilder.addItem();
}
// Added
function addNewItem(form_data) {
RecipeBuilder.addNewItem(form_data);
}
By this, when google.script.run.addNewItem(this); is run at the library side, addNewItem of client side is run, and then, RecipeBuilder.addNewItem of the library side is run.
Note:
In your Javascript of library side, google.script.run.addNewItem(this); and google.script.host.close(); are run in order. But google.script.run works with the asynchronous process. So if the process of addNewItem(this) is slow, the dialog might be closed before addNewItem(this) is run. So I think that the following modification might be also used.
From
google.script.run.addNewItem(this);
google.script.host.close();//close this dialogbox
To
google.script.run.withSuccessHandler(()=> google.script.host.close()).addNewItem(this);
Reference:
Class google.script.run
I recommend you put your scripts into:
document.addEventListener('DOMContentLoaded', event => {
// your code here
});
I have City and Building fields in my form. Before user submits the form I need to check if building already exist in selected city. Building number can be the same since building with the same number can belong to different city. I want to prevent same building numbers that belong to same city. In order to accomplish this I have to send City+Building concatenated value to the server and check if that value exist in database table. I'm trying to find good solution for this problem. So far I used focus/blur function for this purpose. If user clicks on the Building input field once finished entering value, on blur I will send an ajax request to the server and return true or false. In this case that is a little different, before I send request I have to make sure that City field has entered value. Here is example of my f
$("#frm_building").focus(function() {
var submitBtn = $(this).closest("form").find(":submit").prop("disabled", true), //Disable submit button on field focus.
}).blur(function() {
var fldObj = $(this),
frmMessage = $(this).closest("form").find(".message-submit"),
submitBtn = $(this).closest("form").find(":submit"),
distVal = $("");
if (String(fldObj.val()) && String(fldObj.val()) !== String(fldObj.attr("data-current"))) {
//if (obj.RESULT === true) { // This will be the result returned after ajax call
if(1===1)
fldObj.get(0).setCustomValidity("");
} else {
fldObj.get(0).setCustomValidity("Building already exists for that City.");
}
submitBtn.prop("disabled", false);
} else {
fldObj.get(0).setCustomValidity("");
submitBtn.prop("disabled", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmBuilding" id="frmBuilding">
<div class="form-group">
<label class="control-label" for="City"><span class="label label-primary">City:</span></label>
<select class="form-control" name="frm_city" id="frm_city" required>
<option value="">--Choose City--</option>
<option value="1003">New York</option>
<option value="2341">Chicago</option>
<option value="4343">Miami</option>
<option value="7865">San Francisco</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="Building"><span class="label label-primary">Building:</span></label>
<input type="text" class="form-control check-value" name="frm_building" id="frm_building" data-current="" data-fldname="building" maxlength="4" pattern="[0-9]{4}$" title="Number field requires 4 digits" placeholder="Select City first then enter Building number. Example: 1108"
required>
</div>
</form>
In code above if user first entered Building and City is blank my code won't send request to the server on blur. Then if user tries to submit the form they will get the message City field is required. Let's say they enter City, Building will remain the same as they originally entered. In that case on blur is never triggered and request won't be sent. I'm wondering how I can prevent this to happen, is there a way to prevent user entering Building if City field is empty? Also I have to consider the case when user want to update the record. If they click edit and form gets populated that functionality should work and populate both fields without Building being disabled. I hope this part make sense. Originally I have tried setting Building with attribute disabled and setting on change function on the City field. That worked fine until I discovered the issue with edit situation. If anyone knows a good way to solve this situation please let me know.
is there a way to prevent user entering Building if City field is empty?
When focus is on Buildings you can move focus on City if this field is empty.
$("#frm_building").on('focus', function (e) {
if ($('#frm_city').val().length==0) {
$('#frm_city').focus();
}
});
$("#frm_building").on('focus', function (e) {
if ($('#frm_city').val().length==0) {
$('#frm_city').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmBuilding" id="frmBuilding">
<div class="form-group">
<label class="control-label" for="frm_city"><span class="label label-primary">City:</span></label>
<select class="form-control" name="frm_city" id="frm_city" required>
<option value="">--Choose City--</option>
<option value="1003">New York</option>
<option value="2341">Chicago</option>
<option value="4343">Miami</option>
<option value="7865">San Francisco</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="frm_building"><span class="label label-primary">Building:</span></label>
<input type="text" class="form-control check-value" name="frm_building" id="frm_building" data-current=""
data-fldname="building" maxlength="4" pattern="[0-9]{4}$" title="Number field requires 4 digits"
placeholder="Select City first then enter Building number. Example: 1108"
required>
</div>
<input type="submit" value="submit">
</form>
All right. So I'm coding after A LOOONG TIME, and I just went on to codecademy to get a bit refreshed with javascript. So I learnt something I didn't know before : OOP.
Help. I tried something. Will include the JSfiddle. But I don't know why, it doesn't work.
Nevermind my Idiocy, I will complete the code as soon as I know what the problem in the prev code was. I have alot to do in that. I also want to learn PHP to make a kind of phone directory!
I have also NOT included the CSS, but that hardly matters.
What the code should do, is that everytime a user fills up the form and clicks submit, it should append the values in a '#results' div. Not doing anything. Help?
Also, nevermind the two password fields. I will write the code for validating the form once I am clear with this problem.
THANK YOU IN ADVANCE.
JSFIDDLE : http://jsfiddle.net/Ns66V/1/
HTML -- >
<html>
<head>
<link rel="stylesheet" href='style.css'>
<script type="type/javascript" src='jquery.js'></script>
<script type="type/javascript" src='js.js'></script>
<title>Form JS</title>
</head>
<body>
<div class='container'>
<h1>Create an ID! It's absolutely <strong>FREE!</strong></H1>
<div id='form'><form action='get'>
<input name='fname' type='text' placeholder='First Name'><br>
<input name='lname' type='text' placeholder='Last Name'><br>
<input name='email' type='email' placeholder='Email Address'><br>
<input name='passw' type='password' placeholder='Password'>
<input name='Again' id='last' type='password' placeholder='Again!'><br>
<select name='gender'>
<option value='male'>Male</option>
<option value='female'>Female</option>
<option value='other'>Other</option>
</select>
<div id='submit'><strong>SUBMIT IT!</strong></div>
</form>
</div>
<div class='results'>
<div class='vals' id='intro'>
<div class='srn item'>#</div>
<div class='bigitem item'>FULL NAME</div>
<div class='bigitem item'>EMAIL ADDRESS</div>
<div class='gender item'>Gender</div>
</div>
<div class='vals'>
<div class='srn item'>#</div>
<div class='bigitem item'>FULL NAME</div>
<div class='bigitem item'>EMAIL ADDRESS</div>
<div class='gender item'>Gender</div>
</div>
</div>
</div>
</body>
</html>
JS (JQuery) -->
$(document).ready(function(){
function Person(fname,lname,email,passw,gend){
this.fname = fname;
this.lname = lname;
this.email = email;
this.passw = passw;
this.gend = gend;
};
var numPeople = 0; //Setting the number of people var.
$('#submit').click(function(){
var fname = $('input[name=fname]').val(), //SETS VALUES OF ALL THE INPUTS
lname = $('input[name=lname]').val(), //SETS VALUES OF ALL THE INPUTS
email = $('input[name=email]').val(), //SETS VALUES OF ALL THE INPUTS
passw = $('input[name=passw]').val(), //SETS VALUES OF ALL THE INPUTS
gend = $('select[name=gender]').val(); //SETS VALUES OF ALL THE INPUTS
var People = new Array(); //Definin
numPeople++;
People[numPeople] = new Person(fname,lname,email,passw,gend);
$('.results').append(People[numPeople].fname + People[numPeople].lname + People[numPeople].email + People[numPeople].passw + People[numPeople].gend);
}); //#SUBMIT.CLICK() END
});
OOP isn't entirely needed in this case. The problems is that you need to use #results, and you need to close your button along with other tags.
HTML
<button id='submit' type='button'><strong>SUBMIT IT!</strong></button>
JS
$('#results').append(...);
Here is a Fiddle example, added a <br /> at the end.
Also get and post are for a forms method attribute. action is where the form sends the data. So you probably want:
<form method="get"></form>
Check http://jsfiddle.net/Ns66V/4/
The button tag was not closed and the content was appended to the button and
$('#submit').click(function()
should be replaced with
$('#submit').on('click', function()
Now seems to work.
Of course you should improve how you append the content though - use html tags to separate each information.
I am creating a team registration form. and the required condition is that user must be already registered and can choose only registered members in the team.
for checking user existence in database i am using email.
The form contains multiple email fields triggered by a button that adds a field in the form
I need to check for all user's existence when user types in the respective email field using ajax call and display the result in <span class='form_hint'></span>
The form is contained in a hidden div and is called by colorbox
but it doesn't seem to work somehow
Here's my html code:
Update: Now Working fine
<!DOCTYPE html>
<html dir="ltr" lang="en-US"> <head>
<title>Event Description </title>
<meta charset="UTF-8"/>
<!--Colorbox-->
<link rel="stylesheet" media="screen" href="colorbox/css/styles.css" >
<link rel="stylesheet" media="screen" href="colorbox/css/colorbox.css" >
<script src="colorbox/js/jquery.min.js"></script>
<script src="colorbox/js/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
$(".register").colorbox({inline:true,maxHeight:"95%", maxWidth:"90%"} );
});
</script>
<!--Colorbox ends-->
</head>
<body>
<a class="register" href="#register">Event Registeration</a>
<script type="text/javascript">
function usercheck(){
$(document).ready(function(){
$('input[type="email"]').keyup(function() {
var name = $(this).val();
if(name=="")
{
$(".form_hint").html("");
}
else
{
$.ajax({
type: "POST",
url: "user_check.php",
data: { email: name } ,
success: function(html){
$(".form_hint").html(html);
}
});
return false;
}
});
});
}
</script>
<div style='display:none'>
<div id='register' style='padding:10px; background:#fff;'>
<center>
<form class="contact_form" action="../../register/register.php" method="post" name="contact_form">
<ul>
<li>
<h2>Registration</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" placeholder="mail#example.com" onkeyup="usercheck();" required />
<span class="form_hint">Proper format "mail#example.com"</span>
</li>
<span id="dynamicInput"></span>
<li><input type="button" value="+" onClick="addInput('dynamicInput');"/></li>
<li>
<button class="submit" type="submit">Register</button></h4>
</li>
</ul>
</form></center>
</div>
</div>
<script type="text/javascript">
function addInput(liName){
//var counter=1;
var newfield = document.createElement('li');
newfield.innerHTML = "<label for='email'>Email:</label><input type='email' name='email[]' onkeyup="usercheck();" placeholder='mail#example.com' /><span class='form_hint'></span>";
document.getElementById(liName).appendChild(newfield);
}
</script>
</body>
</html>
PHP code to check users in Database:
<?php
include('connect.php');
if(isset($_POST['email']))
{
$name=$_POST['email'];
$query=mysql_query("select * from user_details where email='$name'");
$row=mysql_num_rows($query);
if($row==1)
{
echo "Okay Pal!";
}
else
{
echo "User doesn't exist";
}
}
?>
I don't know where the error is as i am implementing it using dynamic fields for very first time
Also i want to know a good method to handle multiple email fields like i am using above.
I dont think your IF-Statement in your PHP-Code is executed.
You're checking for an email-parameter, but your ajax-data looks like data: "name="+ name
Try to change it to data: { email: name },
First of all selector $('#email[]') is invalid. Try adding some class to the email input or use this selector $('input[type="email"]') to add event handler to all email fields.
Next thing is keyup handler. Inside handler function you can use $(this) instead trying to select field again.
The last one consider using JSON as the data exchange type. On the server return string like: {registered:true} and on the client parse it as a JSON in the jQuery.ajax function setting dataType to JSON.
The Above code is now fully functional.
Earlier only 1st field was calling the function and checking through php. so as to resolve it, I added a
function usercheck(){}
to handle the user interactions.
And on every key up on <input type='email'> I added onkeyup() function that triggers usercheck() as:
<input type='email' name='email[]' onKeyUp='usercheck();'>
and result of the query is displayed within <span> with every <input type='email'> field
Thank you everyone for your valuable responses :) You made my day!
I'm trying to learn how to use JS in order to create a unit converter for a site I'm working on.
I did have intentions of trying to accomplish it using PHP but someone pointed out how inefficient it would be and so I'm now trying to learn JS to carry out the same tasks.
I've written a very small test function to add two numbers, it worked fine. I then adjusted it slightly to take in a few more params and to check a couple of conditions, again that worked fine - I created a new object and passed the variables in directly.
I now need to pass the values from the form that I have into this function in order to compute the sum and output the result. I keep getting an error of 'undefined'. I've googled and read but can't seem to find a solution.
so far I have:
<script type="text/javascript">
function Convert(from, to, units){
this.from = $("#from").val();
this.to = $("#to").val();
this.units = $("#units").val();
}
Convert.prototype.convertThem = function(){
if(this.from == "degC"){
if(this.to == "degF"){
return this.units * 347956757524;
}
}
}
calcTempTest = new Convert(this.from, this.to, this.units);
alert(calcTempTest.convertThem());
console.log(calcTempTest);
</script>
Could anyone tell me what I'm doing wrong please? The 'to','from' and 'units' are the id's from the form.
The Form:
<div class="form">
<label for="units">Units:</label>
<input type="text" name="units" id="units" class="required digits" />
</div>
<div class="form">
<label for="from">Convert From:</label>
<select name="from" id="from">
<option value="from">-Select an Option-</option>
</select>
</div>
<div class="form">
<label for="to">Convert Into:</label>
<select name="to" id="to">
<option value="to">-Select an Option-</option>
</select>
</div>
<div class="form">
<label> </label>
<input type="submit" name="submit" value="Convert!" />
</div>
many thanks.
Explanation
Your select selected option value onLoad both are "from" and "to". Since these are not equal to "degF" and "degC", your assignments won't go on, the resulting variable will be undefined since no value will be asssigned to it.
Solution
Add several option to your select or change their default value. I also added a default value to the input.
HTML
<input type="text" name="units" id="units" value="12" class="required digits" />
<option value="degC">-Select an Option-</option>
<option value="degF">-Select an Option-</option>
EDIT
I have added a JSFiddle here which executes the script on the button click with the following modifications to JavaScript:
NOTE: I also added the real formula.
JavaScript/jQuery
$('input[name="submit"]').click(function () {
var c = new Convert();
alert(c.convertThem());
});
function Convert() {
this.from = $("#from").val();
this.to = $("#to").val();
this.units = $("#units").val();
}
Convert.prototype.convertThem = function () {
if (this.from == "degC") {
if (this.to == "degF") {
return this.units * 1.8 + 32;
}
}
}
I think when you create the convert object you're trying to pass variables that don't exist:
calcTempTest = new Convert(this.from, this.to, this.units);
I'm pretty sure this stands for window at that point and windw.from is undefined. You don't seem to be doing anything with these values anyway so you could change it to:
calcTempTest = new Convert();
Maybe the following answer could help you out with what this stands for in JS: Prototypical inheritance - writing up
Here is some minimally working code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
</head>
<body>
<div class="form">
<label for="units">Units:</label>
<input type="text" name="units" id="units" class="required digits" />
</div>
<div class="form">
<label for="from">Convert From:</label>
<select name="from" id="from">
<option value="degC">degC</option>
</select>
</div>
<div class="form">
<label for="to">Convert Into:</label>
<select name="to" id="to">
<option value="degF">degG</option>
</select>
</div>
<div class="form">
<label for="output">Output:</label>
<input type="text" id="output" />
</div>
<div class="form">
<label> </label>
<input type="submit" id="subm" name="submit" value="Convert!" />
</div>
<script type="text/javascript">
(function () {
function Convert(from, to, units) {
// when convert is created set a reference to the input elements
this.$from = $("#from");
this.$to = $("#to");
this.$units = $("#units");
this.$output = $("#output");
}
Convert.prototype.convertThem = function () {
// this.$... is a jQuery object containing the input elements
if (this.$from.val() == "degC") {
if (this.$to.val() == "degF") {
this.$output.val( this.$units.val() * 347956757524);
}
}
}
calcTempTest = new Convert();
$("#subm").on("click", null, null, function () {
calcTempTest.convertThem();
});
})();//anonymous funciton, no variables in global scope
</script>
</body>
</html>
There are several issues with your code. Most of them have been resolved in the accepted answer, but I wanted to provide some more insights that would help you create more reusable code in the future.
Since I have already created a jsfiddle with my own example, it will be a shame to let it go to waste so I will post it anyway with some comments.
Using constructor parameters
function Convert(from, to, units, res){
this.from = from;
//etc...
}
Passing parameters to an object's constructor (and using them) makes it more reusable. You did not use the passed parameters and the selected answer used what I assume was your original solution (hard-coding the element values into the object upon construction).
This way you can have multiple instances of the converter on the same page, you can put its code in an external file as it gets more complex and only put the instantiation logic in the page itself (if your page structure changes, there is no need to change the external file, just update the provided constructor parameters).
Storing node references instead of values
The other thing I wanted to point out is the way the calculation is done.
Your implementation requires a new object to be created for each calculation. I find it much better to create a single Converter and obtain the values only when required. That it the reason I stored a reference to the form field DOM nodes and did not store their values.
$("#btnConvert").click(calcTempTest.convertThem.bind(calcTempTest));
I used bind(...) in the click attachment to preserve the object's scope.
Good luck!