HTML Form Using JavaScript Valildation - javascript

I working on Javascript validation task as i am beginner in Javascript i was stuck in Js validation code codepen.Can, Anyone Please help out of this and point me in right direction.
Thanks in advance.
jQuery(document).ready(function($) {
function formValidation() {
var firstname = document.getElementById('product');
if (firstname.value.length == 0) {
document.getElementById('head').innerText = "* All fields are mandatory *";
firstname.focus();
return false;
}
if (inputAlphabet(firstname, "* For your name please use alphabets only *")) {
return true;
}
return false;
}
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
}
else {
document.getElementByClass('price').innerText = alertMsg;
inputtext.focus();
return false;
}
}
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
}
else {
document.getElementById('product').innerText = alertMsg;
inputtext.focus();
return false;
}
}
});
body {
background: #f5f5f5;
}
.product-container {
display: flex;
justify-content: center;
align-items: center;
padding: 100px;
}
input#product {
max-width: 200px;
padding: 5px 20px;
}
input.price {
max-width: 227px;
padding: 5px 4px;
width: 100%;
}
input.qnty {
max-width: 235px;
width: 100%;
padding: 5px 4px;
}
input[type="submit"] {
font-size: 14px;
font-family: 'Roboto', sans-serif;
font-weight: 500;
color: #000000;
padding: 5px 10px;
letter-spacing: 0.6px;
}
<!DOCTYPE html>
<html>
<head>
<title>Product Order</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="custom.js"></script>
</head>
<body>
<div class="product-container">
<form action="submit" method="POST">
Product Name: <input type="text" name="name" value="" required id="product" ><br><br>
Unit Price: <input type="number" name="Price" value= "" required class="price" pattern="\d+(\.\d{2})?"><br><br>
Quantity: <input type="number" name="Quantity" value="" min="1" max="10" required class="qnty price"><br><br>
<input type = "submit" name = "submit" value = "Get Total Amount">
</form>
</div>
</body>
</html>

You're doing the same thing I was doing when I started using jQuery... mixing JavaScript with jQuery.
You don't need to create a function to validate the form. I'd first change your submit button to this:
<button type="button" id="submitButton">Submit</button>
Then use jQuery to listen for the button click:
$('#submitButton').on('click', function() {
var product = $('#product').val();
var price = $('.price').val();
var name = $('#name').val();
// check if name input has a value, if blank, then display error message
if(name == "") {
alert('You must enter a name');
return false;
}
if(product == '//whatever you want to check here') {
// display message
}
if(price == '// check if the input is blank') {
// return error message
}
else {
// do something
}
});
The if/else inside your button click is your validation.

I see a ton of errors in your very small code. Your Jquery code looks very bad. You are creating functions but never using them, You don't have to create functions for form validation. You can use Jquery event listeners to check if the user has performed some action like (submit, Focus, Blur etc.,) and when you receive the event you have to perform an action and clearly innerText does not work on input boxes. Go through this article on form validation using Jquery.
You should do basic google search before posting a question here.

Related

Set a field to required in html when an option is selected

Hi I am trying to make a field required when option is selected like if option 1 is selected so field one will be required and if option 2 then field 2 and make field 1 not required so on. So far I have tried setAttribute, removeAttribute, getelemenybyid(..).required=true or false (proper camel cases are used in code). nothing seem to work.to better explain I have entered the code below. I am using this form as Camunda embedded form and scripts are java scripts. smaple below
<div class="form-group" >
<label for="AmendmentType" >Amendment Type: </label>
<select class="form-control" onchange="Optionselection(this);" cam-variable-name="AmendmentType" cam-variable-type="String" id = "AmendmentType" required>
<option onClick="Optionselection()" id="update" name="AmendmentType" value="Update a field">Update a field</option>
<option onClick="Optionselection()" id="DuplicateId" name="AmendmentType" value="Duplicate Tax Files (to be mande inactive)">Duplicate Tax Files (to be made inactive)</option>
</select>
</div>
function Optionselection(that) {
if (that.value == "Update a field") {
document.getElementById('ValueinSystem').required=true;
document.getElementById('duplicateID').required=false;
}
else if(that.value == "Duplicate Tax Files (to be mande inactive)") {
document.getElementById('ValueinSystem').required=flase;
document.getElementById('duplicateID').required=true;
}
as i said i tried the following nothing seems to work
function Optionselection(that) {
if (that.value == "Update a field") {
document.getElementById('ValueinSystem').setAttribute('required','');
document.getElementById('duplicateID').removeAttribute('required');
}
else if(that.value == "Duplicate Tax Files (to be mande inactive)") {
document.getElementById('duplicateID').setAttribute('required','');
document.getElementById('ValueinSystem').removeAttribute('required');
}
Selects and makes the respective input field required, to distinguish added some style
More on client side validation here .......
const carsNode = document.querySelector("#cars");
const merc = document.querySelector("#merc");
const audi = document.querySelector("#audi");
const form = document.querySelector("form");
const mercError = document.querySelector('#merc + span.error');
const audiError = document.querySelector('#audi + span.error');
const carError = document.querySelector('#cars + span.error');
let selectedCar;
cars.addEventListener('change', (e) => {
// we listen to change event for select
selectedCar = e.target.value;
switch (selectedCar) {
case "mercedes":
merc.required = true;
audi.required = false;
break;
case "audi":
merc.required = false;
audi.required = true;
break;
default:
merc.required = false;
audi.required = false;
break;
}
})
form.addEventListener('submit', function(event) {
// if the field's is valid, we let the form submit
if ((!merc.validity.valid && selectedCar === "mercedes") || (!audi.validity.valid && selectedCar === "audi") || !selectedCar) {
// If it isn't, we display an appropriate error message
showError();
// Then we prevent the form from being sent by canceling the event
event.preventDefault();
}
});
function showError() {
if (merc.validity.valueMissing && selectedCar === "mercedes") {
// If the field is empty,
// display the following error message.
mercError.textContent = 'You need to enter a Mercedes value';
carError.textContent = '';
audiError.textContent = '';
// Set the styling appropriately
mercError.className = 'error active';
audiError.classList.remove('error', 'active');
carError.classList.remove('error', 'active');
} else if (audi.validity.valueMissing && selectedCar === "audi") {
audiError.textContent = 'You need to enter an Audi value';
mercError.textContent = '';
carError.textContent = '';
// Set the styling appropriately
audiError.className = 'error active';
mercError.classList.remove('error', 'active');
carError.classList.remove('error', 'active');
} else {
mercError.classList.remove('error', 'active');
audiError.classList.remove('error', 'active');
carError.textContent = 'You need to select a car';
mercError.textContent = '';
audiError.textContent = '';
carError.className = 'error active';
}
}
input:required {
border: 1px dashed red;
}
body {
font: 1em sans-serif;
width: 200px;
padding: 0;
margin: 10px auto;
}
p * {
display: block;
}
/* This is our style for the invalid fields */
input:invalid {
border-color: #900;
background-color: #FDD;
}
input:focus:invalid {
outline: none;
}
/* This is the style of our error messages */
.error {
width: 100%;
padding: 0;
font-size: 80%;
color: white;
background-color: #900;
border-radius: 0 0 5px 5px;
box-sizing: border-box;
}
.error.active {
padding: 0.3em;
margin-top: 5px;
}
input {
-webkit-appearance: none;
appearance: none;
width: 100%;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
<div>
<form novalidate>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<option value="" selected>Select Car</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<span class="error" aria-live="polite"></span>
<br>
<br>
<label for="merc">Mercedes:</label>
<input type="text" id="merc" name="merc">
<span class="error" aria-live="polite"></span>
<br><br>
<label for="audi">Audi:</label>
<input type="text" id="audi" name="audi">
<span class="error" aria-live="polite"></span>
<br><br>
<button>Submit</button>
</form>
</div>

Serverless Contact form issue html css ajax js

So, I have this contact form sending me a mail and updating my google sheet. I found this on GitHub. When I don't add the JS file I get a mail and an update. When I add the JS I get neither. I have tried with and without this script link when using JS but it does not work.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
For security purpose I have removed my google sheet link and kept it as action="#" from form and because I have added my e-mail in my google sheet I can leave my data-email="" as it is.
I also don't get the thankyou message at the submission of the form when I have added my JS file, but without it I get confirmation displaying the details submitted.
There is a honeypot input label that is hidden by CSS and needs to be left blank for the form to be submitted successfully, avoiding spam.
It seems that there is some issue with the JS(duh!).
Please help!!!
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="contact form example">
<title>Contact Form Example</title>
</head>
<body>
<h2 class="content-head is-center">Contact Us!</h2>
<aside>
<p>
We would <em>love</em> to hear from you! </p>
<p>Please use the <b><em>Contact Form</em></b>
to send us a message.
</p>
</aside>
<!-- START HERE -->
<link rel="stylesheet" href="https://unpkg.com/purecss#1.0.0/build/pure-min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Style The Contact Form How Ever You Prefer -->
<link rel="stylesheet" href="style.css">
<form class="gform pure-form pure-form-stacked" method="POST" data-email=""
action="#">
<!-- change the form action to your script url -->
<div class="form-elements">
<fieldset class="pure-group">
<label for="name">Name: </label>
<input id="name" name="name" placeholder="What your Mom calls you" />
</fieldset>
<fieldset class="pure-group">
<label for="message">Message: </label>
<textarea id="message" name="message" rows="10"
placeholder="Tell us what's on your mind..."></textarea>
</fieldset>
<fieldset class="pure-group">
<label for="email"><em>Your</em> Email Address:</label>
<input id="email" name="email" type="email" value=""
required placeholder="your.name#email.com"/>
</fieldset>
<fieldset class="pure-group">
<label for="color">Favourite Color: </label>
<input id="color" name="color" placeholder="green" />
</fieldset>
<fieldset class="pure-group honeypot-field">
<label for="honeypot">To help avoid spam, utilize a Honeypot technique with a hidden text field; must be empty to submit the form! Otherwise, we assume the user is a spam bot.</label>
<input id="honeypot" type="text" name="honeypot" value="" />
</fieldset>
<button class="button-success pure-button button-xlarge">
<i class="fa fa-paper-plane"></i> Send</button>
</div>
<!-- Customise the Thankyou Message People See when they submit the form: -->
<div class="thankyou_message" style="display:none;">
<h2><em>Thanks</em> for contacting us!
We will get back to you soon!</h2>
</div>
</form>
<!-- Submit the Form to Google Using "AJAX" -->
<script data-cfasync="false" type="text/javascript" src="form-submission-handler.js"></script>
<!-- END -->
</body>
</html>
JS
(function() {
// get all data in form and return object
function getFormData(form) {
var elements = form.elements;
var honeypot;
var fields = Object.keys(elements).filter(function(k) {
if (elements[k].name === "honeypot") {
honeypot = elements[k].value;
return false;
}
return true;
}).map(function(k) {
if(elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
}else if(elements[k].length > 0){
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name){
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
formData.formGoogleSendEmail
= form.dataset.email || ""; // no email by default
return {data: formData, honeypot: honeypot};
}
function handleFormSubmit(event) { // handles form submit without any jquery
event.preventDefault(); // we are submitting via xhr below
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
// If a honeypot field is filled, assume it was done so by a spam bot.
if (formData.honeypot) {
return false;
}
disableAllButtons(form);
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
}
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
function loaded() {
// bind to the submit event of our form
var forms = document.querySelectorAll("form.gform");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", handleFormSubmit, false);
}
};
document.addEventListener("DOMContentLoaded", loaded, false);
function disableAllButtons(form) {
var buttons = form.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
})();
CSS
body {
margin: 2em;
}
aside {
background: #1f8dd6; /* same color as selected state on site menu */
padding: 0.3em 1em;
border-radius: 3px;
color: #fff;
margin-bottom: 2em;
}
textarea {
width: 100%;
}
.content-head {
font-weight: 400;
text-transform: uppercase;
letter-spacing: 0.1em;
margin: 2em 0 1em;
}
.is-center {
text-align: center;
}
.button-success {
color: white;
border-radius: 4px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
background: rgb(28, 184, 65); /* this is a green */
}
.button-xlarge {
font-size: 125%;
}
button {
float: right;
}
#name, #email {
width: 50%;
}
.honeypot-field {
display: none;
}

How to call a function when textfield value change in Javascript?

I want to change width of a textfield when user enters more than 17 characters in that textfield using Javascript (if possible) otherwise by any other means.
I wrote a code to do the same, but it only changes width when user click outside the textfield after entering more than 17 characters. I want it to change width automatically when user enters more than 17 characters :
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onchange="widen()" value="" required>
</form>
onchange gets activated when the input looses focus, that's why it works when you click outside. On the other hand oninput will be triggered immediately when the value changes:
const nametf = document.getElementById('nametf');
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<html>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" oninput="widen()" value="" required>
</form>
</html>
You need to pass a self-reference to the function using this. I would also change on-change to on-key-up, because on-change waits for you to move focus away from the field.
onkeyup="widen(this)"
Then you need to parameterize the function with your variable "nametf"
function widen(nametf) {
// ...
}
Example
function widen(nametf) {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onkeyup="widen(this)" value="" required>
</form>
A better approach would be to use em units to expand the text are based on the current value.
initExpandingFields();
function initExpandingFields() {
Array.from(document.querySelectorAll('.expanding-field')).forEach(field => {
field.addEventListener('keyup', onFieldChange);
});
}
function onFieldChange(e) {
let field = e.target,
len = field.value.length;
field.style.width = (len * 0.667) + 'em';
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" class="expanding-field" name="name1" id="nametf" value="" required>
</form>
Try this:
var nametf = document.getElementById("nametf");
nametf.addEventListener("input", function(){
if(nametf.value.length > 17) {
nametf.size = "30";
} else {
nametf.size = "20";
}
});
#nametf {
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" size="20" value="" required>
</form>

How to change the text of a label when a radio button is selected

What I don't understand is why does my code not change the text of the label when the radio is selected?
This is what is suppose to happen:
Which when 'Fahrenheit to Celsius' is selected the first image should be true (the text of the first and second label should change)
When 'Celsius to Fahrenheit' is selected the second image should be true (the text of the first and second label should change)
What I'm guessing is my problem is with the if ($("input:to_celsius").val() == "true") statement but I don't quite know why it's wrong.
***Current error message:
{
"message": "Uncaught TypeError: Cannot set property 'onclick' of null",
"filename": "https://stacksnippets.net/js",
"lineno": 69,
"colno": 30
}
"use strict";
var $ = function(id) { return document.getElementById(id); };
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "true") {
$("#degree_labl_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
}
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "true") {
$("#degree_labl_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
<script src="jquery-3.4.1.min.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
There are multiple issues in your code.
Looks like you are trying to use jQuery here, but in your case you are overriding the jQuery $ function with a custom function. So in effect you are not using jQuery here by calling the $ function but using pure javascript selectors
var $ = function(id) {
return document.getElementById(id);
};
With a function declaration as above, you can select elements only by Id and the Id should not be prefixed with #
$("#degree_label_1") won't work here
$("degree_label_1") will work.
So I suggest changing the $ function declaration to something like below.
var $ = function(selector) {
return document.querySelector(selector);
};
Here I changed document.getElementById -> document.querySelector so that selectors are more flexible (You can use any css selectors like "#id", ".classname" etc)
As we are not using jQuery here, the below code will not work. In jQuery, its correct but there are syntax differences in accessing the dom in plain javascript
$("#to_fahrenheit").val() == "true"
One way to implement the same is..
Assign values to the radio button inputs
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br />
and check the value
$("#to_fahrenheit").value == "c_to_f"
Same applies to the below line. There's a typo as well (Missed an e in degree_label_1)
$("#degree_labl_1").text("Enter F degrees")
should be changed to
$("#degree_label_1").textContent = "Enter F degrees"
Complete code would look like below.
"use strict";
var $ = function(id) {
return document.querySelector(id);
};
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#convert").onclick = convert;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").value == "c_to_f") {
$("#degree_label_1").textContent = "Enter C degrees";
$("#degree_label_2").textContent = "Degrees Fahrenheit";
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").value == "f_to_c") {
$("#degree_label_1").textContent = "Enter F degrees";
$("#degree_label_2").textContent = "Degrees Celsius";
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).value;
var enteredValue = Number($("#degrees_entered").value);
if (conversiontype === "f_to_c") {
$("#degrees_computed").value = ((enteredValue - 32) * 5) / 9;
} else {
$("#degrees_computed").value = (enteredValue * 9) / 5 + 32;
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<h1>Convert temperatures</h1>
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />
If you want to use jQuery, you should remove below function declaration
var $ = function(id) {
return document.getElementById(id);
};
And modify your code as follows.
"use strict";
var clearTextBoxes = function() {
$("#degrees_entered").val("");
$("#degrees_computed").val("");
};
window.onload = function() {
$("#to_celsius").on("click", toCelsius);
$("#to_fahrenheit").on("click", toFahrenheit);
$("#convert").on("click", convert);
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "c_to_f") {
$("#degree_label_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "f_to_c") {
$("#degree_label_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).val();
var enteredValue = Number($("#degrees_entered").val());
if (conversiontype === "f_to_c") {
$("#degrees_computed").val(((enteredValue - 32) * 5) / 9);
} else {
$("#degrees_computed").val((enteredValue * 9) / 5 + 32);
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" value="f_to_c" checked />Fahrenheit to Celsius<br />
<input type="radio" name="conversion_type" id="to_fahrenheit" value="c_to_f" />Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />

Check the contents of the edit field

I have on my website input type="text" and i trying to write code, that can check when field is empty.
if (number>0)document.getElementById("score").innerHTML="+";
else if (number<0)document.getElementById("score").innerHTML="-";
else if (number==0)document.getElementById("score").innerHTML="0";
else document.getElementById("score").innerHTML="this is not a number";
And when the field is null, it still shows that "0" is entered.
____edit
var number = document.getElementById("field").value;
<input type="text" id="field">
Here is a working solution that shows nothing in the score div when then input field is empty. (You can change it to show a message if you want.)
var score = document.getElementById('score');
document.getElementById('field').addEventListener('keyup', checkNum);
function checkNum() {
var number = parseInt(document.getElementById('field').value);
if (number>0) score.innerHTML="+";
else if (number<0) score.innerHTML="-";
else if (number==0) score.innerHTML="0";
else if (document.getElementById('field').value=="") score.innerHTML="";
else score.innerHTML="this is not a number";
}
#score {
display: inline-block;
border: 2px solid red;
border-radius: 4px;
font-weight: 700;
padding: 4px;
}
<input type="text" id="field">
<br><br>
<div id="score"></div>

Categories

Resources