Clearing the field of a form with a button - javascript

Sounds easy probably, but not for a beginner programmer :)
I have a simple 3 field form with a submit button and a clear button. This is for a homework assignment, and we have been tasked to get the "Clear Fields" button to work properly. Here are more specific instructions:
"Add the JavaScript code for an anonymous function that's stored in a variable named clear. The function should clear the text boxes by using the $ function to get a Textbox object for each text box and then setting the value property of the textbox to an empty string. Then, add a statement in the onload event handler that attaches the clear function to the click event of the Clear Entries button."
I was able to add the statement to the onload event handler:
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
But it is the other part I am having problems with.
Add the JavaScript code for an anonymous function that's stored in a variable named clear:
var clear = function () {
Object.Method
}
Here is my full code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
var clear = function () {
miles.Text = String.Empty
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<label> </label>
<input type="button" id="clear" value="Clear Entries"><br>
</section>
</body>
</html>
And here is the code we were supplied with to work off of:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles) || isNaN(gallons)) {
alert("Both entries must be numeric");
}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
</section>
</body>
</html>

You've got several issues going on:
You're mixing Javascript and jQuery in ways that don't quite work.
jQuery's methods and objects work differently than "pure"
Javascript, so be mindful of that.
The window.onload doesn't work the way you've got it. To be
consistent, do it the jQuery way with a $(document).ready() method
instead.
You're missing the # indicator on your jQuery IDs. This is
imperative or it won't find the ID of the elements you're calling.
It looks like you're mixing VB/C# code in with your javascript, such
as the String.Empty call, etc. Those objects/methods work from the
server and not in Javascript, so that's another issue (it's been a
while since I've worked in C#, so double check me on that).
Here's my solution below. I tweaked a few things to help with what I think you're going for (such as clearing ALL fields with the "Clear" button instead of just the miles field).
I understand you're a student, so don't make it a habit of coming here and trying to find people to do your homework for you. You did provide an attempt at some code, and there were a number of issues in it, so I chose to rectify them for you and explain the reasons since there were so many. Others are not as generous, but I was a struggling student once, too, so I get it when you're banging your head against the wall. :-)
$( document ).ready( function () {
var clear = function () {
miles.value = "";
gallons.value = "";
mpg.value = "";
}
var calculateMpg = function () {
var miles = parseFloat($("#miles").val());
var gallons = parseFloat($("#gallons").val());
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");
}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");
}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");
}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("#mpg").val(mpg.toFixed(1));
}
}
$("#calculate").bind("click", calculateMpg);
$("#miles").focus();
$("#clear").bind("click", clear);
});

Related

How to select and run this function onload?

So I have this working codeblock in my script to replace the decimal seperator from comma "," into period "." ,when editing a form. Because in this region the decimal seperator comma is normal I also want the values to be displayed like this 1,99€ so I reverted the working function. The selected fields should change on load. When the form gets submitted I will cange it back again. For this example I show you only one of the fields.
The value="1.5" gets loaded from the Magento-Backend the wrong way, which is another story:
I included onload:"function(event)"
and window.onload = function(); to show two my attempts to adress this function from jQuery: jQuery('form').on('change', '#price', function(event) I also need to know how to remove the .on('change' part. First time using Js und jQuery. I really tried everything.
<html>
<body onload="function(event)">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>
<script>
window.onload = function();
jQuery('form').on('change', '#price', function(event) {
event.preventDefault();
if (jQuery('#price').val().includes('.')) {
var varwithpoint = jQuery('#price').val();
varwithcomma = varwithcomma.replace(",",".");
jQuery('#price').val(varwithpoint);
}
else {
console.log('no dot to replace');
}
});
</script>
There were a few parts of the code which didn't seem to be working as intended, so below is a basic example of code that will convert the "," to a "." if stored in the input "price", and check this after each change of the value;
function convert_price(){
var this_price = $("#price").val();
if (this_price.includes(',')) {
this_price = this_price.replace(",",".");
$('#price').val(this_price);
} else {
console.dir('no dot to replace');
}
}
convert_price();
$("#price").on("change",convert_price);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<body>
<form>
<input id="price" value="1,5">
</form>
</body>
</html>
I have called "init" the function that attaches the change event to the input file, I also changed the parameters passed to the on function
function init(){
var input = jQuery('#price');
input.on('change', function(event) {
event.preventDefault();
var valueInInput = input.val();
if (valueInInput.includes('.')) {
var varwithcomma = valueInInput.replace(",",".");
input.val(varwithcomma);
} else {
console.log('no dot to replace');
}
});
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload="init()">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>

How to take an input that is equal to 10 and perform a function that says awesome to the screen

I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}

Jquery Not working to create new Inputs

Below is my Html Doc and the JQuery does not do anything when the range input changes, any assistance is much appreciated as I am extremely new to web design. Even the alert doesn't work at the top so I am unsure as to what my problem is. My belief is somehow the script is never being called or it's a problem with it being an html doc but either way thank you.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var num=0;
var numOptions = new Array(100);
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
$(document).ready(function(){
$("#numQuestions").on('input',function(){
var numbQuestions = $("#numQuestions".text());
if(num>numbQuestions){
for(i=numbQuestions;i<=num;i++){
try{
$("#qRowNum'+i).remove();
}catch(err){
}
}
}else{
for ( i=num; i < numbQuestions; i++)
{
var row = '<div id="qRowNum'+ i '">
#the below function is not implemented in this version
<input type="text" placeholder="Question '+i'"> <input type="range" name="numOptions'+i'" min="0" max="5" placeholder="Number Of Options" onchange="CreateOptions(this);" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();> </div>';
$("#questionRows").append(row);
//New script test
}
}
num = numbQuestions;
});
});
<div id="questionRows">
</div>
<input type="submit" value="Start">
</form>
</body>
</html>
This is your problem:
var numbQuestions = $("#numQuestions".text());
Firstly I think you mean this:
var numbQuestions = $("#numQuestions").text();
But that is also not true because an input field has not text property. They have value So do this:
var numbQuestions = $("#numQuestions").val();
And this is another problem: $("#qRowNum'+i) When you start selector by double quotation, you need to end this also by double quotation. But it still is not a true jquery selector.
I think you need to more studies about jquery.

Why won't my alert work in one of my functions?

I want the nameVerification() function to throw the alert() message when the user hits submit. For example, if the user enters something like 45 in the name field, I want that alert in nameVerification() function to be called. Right now, when the user does type in a number in the name field, the alert() in the formSubmission() function is being called.
Side note:
formSubmissionfunction works perfectly. In other words, if the user enters a number < 13 in the age field, the functions alert() gets called normally with no problems. If the user enters a number > 13, it works, also, without a problem. Just thought I'd let you guys know that too.
signUp.html
<!DOCTYPE html>
<html>
<head>
<title>Signup Form</title>
<script type="text/javascript" src="signUp.js"></script>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="signUp.css">
<body>
<form class="col-md-4 col-md-offset-4" name="formHandler" id="handle">
<div class="moveUsername">
<label for="usr">Name:</label>
<input type="field" class="form-control" id="nameVerify" placeholder="Username" required="required">
</div>
<div class="ageMovement">
<label for="usr" >Age (Must be 13 years or older to play):</label>
<input type="field" class="form-control" id="ageVerify" name="ageChecker" placeholder="Age" required="required">
</div>
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
</form>
</body>
</html>
signUp.js
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if(typeof name !== 'string') {
alert("That's not a name!");
}
}
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
age is also a string in this function:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
If you want to do a numeric compare, you need to parse first:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if (age) {
var ageInteger = parseInt(age, 10);
if (ageInteger < 13) {
alert("You're too young, you can't play the game");
}
}
}
You have two onclick attributes on the button
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
You can only have one
Your typeof test is failing because the value returned from a text input is always of type string. You can test to see if a provided text value is numeric with the following function:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
The real answer, however, is that you'll need to improve your input validation tests to determine what you want, rather than test for all the things you don't want. For example, testing for a numeric value as above would not work if someone entered "t#^!" in the field, which is likely not a value you would want in a name field. This is where regular expressions, and the built-in validations from HTML5 fields can help.
You can change your nameVerification function as follows:
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if (name) {
var num = parseInt(name) || -1;
if (num >= 0 && num < 13) {
alert("That's not a name!");
}
}
}
and change your onclick values in the html to be:
onclick="formSubmission();nameVerification()"
it's because the javascript is not loaded yet.
Move:
<script type="text/javascript" src="signUp.js"></script>
To just above the </body> tag.
You should use parseInt:
var age = parseInt(document.getElementById("ageVerify").value);

parsley.js - prevent isValid from firing events / just check true or false

Hello I am at my wit's end and I've been stuck creating a more complex version of the form than the example I provide.
I have JS object that is representation of the form. I use parsley's "isValid" on the form itself (checkAll and checkGroup function). These methods are fired on every input that is marked with data-parsley-required attribute. The reason for this is I need to know the state of the whole form and it's parts so I can enable/disable step buttons.
Everything works fine but I also need to call external API when all validations have successed, see line 35. The methods checkAll and checkGroup are basically firing the events again, thus making more AJAX calls (we have limit on calls to the API). Is there a way to force method isValid to just check if the field has been validated and get true/false value out of it?
The whole thing is coded and depends on this structure so the best way would be to have similar functionality. I'm not so experienced so I make lot of mistakes. My example is very simplified version of my actual form but when you open console window you can see what I mean. Uncomment lines 32 and 33 to see the difference and you will know what I mean.
Example code
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="" id="myform">
<div id="section1">
<input type="text" id="field1" data-parsley-required data-parsley-trigger="input" data-parsley-group="group1" data-parsley-lengthvalidator data-parsley-remote="http://pokeapi.co/api/v2/pokemon/1" data-parsley-remote-validator="remotevalidator" /><br />
<button id="next" disabled>Next</button><br />
</div>
<div id="section2">
<input type="text" id="field2" data-parsley-required data-parsley-trigger="input" data-parsley-group="group2" />
</div>
<input type="submit" id="submit-button" disabled />
</form>
</body>
</html>
JS:
function Form(form) {
this.form = form;
this.validations = {};
this.formValid = false;
this.checkAll = function() {
var result = $(form).parsley().isValid();
if (result) {
$('#submit-button').removeAttr('disabled');
console.log('form validated');
} else {
$('#submit-button').attr('disabled', true);
}
this.formValid = result;
};
this.checkGroup = function(e) {
var group = $(e.target).attr('data-parsley-group');
var result = $(form).parsley().isValid({group: group});
if (result) {
$('#next').removeAttr('disabled');
console.log('group validated');
} else {
$('#next').attr('disabled', true);
}
this.validations[group] = result;
};
this.initialize = function() {
var self = this;
$(this.form).parsley();
$('*[data-parsley-required]').on('input', function(e) {
self.checkAll();
self.checkGroup(e);
});
$('#field1').parsley().on('field:success', function() {
console.log('calling another API')
})
Parsley.addValidator('lengthvalidator', {
validateString: function(value) {
console.log('local validator');
return value.length > 0;
}
});
Parsley.addAsyncValidator('remotevalidator', function(response) {
console.log('remote validator');
return response.responseJSON.name === 'bulbasaur';
})
}
}
var form = new Form('#myform');
form.initialize();

Categories

Resources