Applying HTML5 Validation only if checkbox is checked - html

I have a form that offers a user a choice of whether they would like to receive Email updates. How do I go about making sure that the Email is only 'required' (HTML5 Validation) if the checkbox to receive Email updates is checked.
Here is the form:
<form>
<fieldset>
<legend><b>Details</b></legend>
<label>First Name </label><input id = "fname" type="text" autofocus="" placeholder="Enter first name" name = "fname"><br><br>
<label>Last Name </label><input type="text" placeholder="Enter last name"><br><br>
<label>Email </label><input type="email" placeholder="Enter valid email"> <button onclick="myFunction()">Help</button><br><br>
</fieldset>
<fieldset>
<legend><b>Rating</b></legend>
<label>Website Rating:</label>
<input type="radio" name="Rating" value="1">* (1 Star)
<input type="radio" name="Rating" value="2">* * (2 Star)
<input type="radio" name="Rating" value="3">* * * (3 Star)
<input type="radio" name="Rating" value="4">* * * * (4 Star)
<input type="radio" name="Rating" value="5">* * * * * (5 Star)<br>
</fieldset>
<fieldset>
<legend><b>Comments</b></legend>
<label>Additional Comments:</label>
<textarea id = "feedback1" name="feedback1" rows="2" cols="60"></textarea><br>
</fieldset>
<fieldset>
<legend><b>Updates</b></legend>
Do you want to receive updates via Email?<br>
<input type="checkbox" name="updateYes" value="Yes">Yes
<input type="checkbox" name="update" value="No" checked>No<br>
</fieldset>
<br>
<input type="reset" value="Reset">
<button onclick="myFunction2()" type = "submit">Submit</button>
</form>
<script>
function myFunction() {
alert("Please enter a valid Email adress into the 'Email' field");
}
function myFunction2() {
var checkedRadioButton, inputs, rating;
inputs = document.getElementsByName("Rating");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checkedRadioButton = inputs[i];
break;
}
}
if (checkedRadioButton) {
rating = ("You have rated the website " + checkedRadioButton.value + " Star")
} else {
rating = ("Not Rated")
}
alert("Thank you for your feedback " + document.getElementById('fname').value + "\n" + rating + "\n" + "Your comment was " + document.getElementById('feedback1').value);
}
</script>

Related

get HTML DOM index by Id

Eg. document.form[0].elements[23] will result some input <input id = test2> .
I need to get that 23 index value by id or name = 'test2' like
var n = document.getElementById('test2').getDOMNodeIndex(); // n = 23
This solution may be slightly clunky, but it works as demonstrated below.
I generated 25 input elements and gave them unique IDs.
Then I selected a random index among the Form.elements and printed it to the console.
Then I iterated over the form.elements until I found the matching .outerHTML values (JSON.stringified). When a match is found, return that index.
const theForm = document.forms[0];
const randomIndex = Math.floor(Math.random() * theForm.elements.length);
console.log(randomIndex);
const theInput = theForm.elements[randomIndex];
const formElementsIndexOf = (form, element) => {
let search = JSON.stringify(element.outerHTML);
for (let i = 0; i < form.elements.length; i++) {
if (JSON.stringify(form.elements[i].outerHTML) === search) {
return i;
}
}
};
console.log(formElementsIndexOf(theForm, theInput));
<form>
<input type="text" id="text0">
<input type="text" id="text1">
<input type="text" id="text2">
<input type="text" id="text3">
<input type="text" id="text4">
<input type="text" id="text5">
<input type="text" id="text6">
<input type="text" id="text7">
<input type="text" id="text8">
<input type="text" id="text9">
<input type="text" id="text10">
<input type="text" id="text11">
<input type="text" id="text12">
<input type="text" id="text13">
<input type="text" id="text14">
<input type="text" id="text15">
<input type="text" id="text16">
<input type="text" id="text17">
<input type="text" id="text18">
<input type="text" id="text19">
<input type="text" id="text20">
<input type="text" id="text21">
<input type="text" id="text22">
<input type="text" id="text23">
<input type="text" id="text24">
</form>

How would i create a price calculator with 1 input and 6 different outputs?

I have created an initial version, however you have to type the individual inputs for each output. I want to be able to just type into one input box and then it calculates all other outputs. How would i do this?
This is the code i have currently, im very very new to this :)
<form onsubmit="return false" oninput="o.value = (a.valueAsNumber /0.7).toFixed(0)" <br>
NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="RETAIL"></output> Retail
</form>
<form onsubmit="return false" oninput="o.value = (a.valueAsNumber *1).toFixed(0)" <br>
NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Schools & CDC's"></output> Schools & CDC's
</form>
<form onsubmit="return false" oninput="o.value = (a.valueAsNumber / 0.7 -(a.valueAsNumber / 0.7 / 100*40)).toFixed(0)" <br>
NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band A" Math.round></output> Trade - Band A
</form>
<form onsubmit="return false" oninput="o.value = (a.valueAsNumber *1).toFixed(0)" <br>
NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band B"></output> Trade - Band B
</form>
<form onsubmit="return false" oninput="o.value = (a.valueAsNumber / 0.7 -(a.valueAsNumber / 0.7 / 100*20)).toFixed(0)" <br>
NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band C" Math.round></output> Trade - Band C
</form>
<form onsubmit="return false" oninput="o.value = (a.valueAsNumber / 0.7 -(a.valueAsNumber / 0.7 / 100*10)).toFixed(0)" <br>
NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band D" Math.round></output> Trade - Band D
</form>
https://jsfiddle.net/5gpLbj80/2/
You can use the same input to update all your fields, no need to use a form.
const calc = () => {
let nhs = document.getElementById('nhs').value;
document.getElementById('retail').innerHTML = (nhs / 0.7).toFixed(0);
document.getElementById('school').innerHTML = (nhs * 1).toFixed(0);
//If you want an input:
document.getElementById('retailInput').value = (nhs / 0.7).toFixed(0);
document.getElementById('schoolInput').value = (nhs * 1).toFixed(0);
}
NHS<input id='nhs' oninput='calc()'><br>
<span>Retail:</span><span id='retail'></span><br>
<span>School:</span><span id='school'></span><br>
<span>Retail input:</span><input id='retailInput' disabled='true' /><br>
<span>Retail input:</span><input id='schoolInput' disabled='true' />
First piece of advice would be to remove all of those inline event handlers.
Attach a named function, then do all of your grunt-work inside it.
By using addEventListener to connect the two, the function 'knows' which element it's attached to. That is to say, we can simply use this.value to get it's value, rather than having to use document.getElementById('nhs').value
"use strict;"
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt)
{
let outputs = [byId('output1'), byId('output2'), byId('output3')];
let value = parseFloat(this.value);
if (!isNaN(value))
{
outputs[0].textContent = value * 2;
outputs[1].textContent = value * 3;
outputs[2].textContent = parseInt( (value * 3)/4 );
}
else
{
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent = "*invalid input (enter a number)*";
}
}
<label>Enter data: <input id='myInput'/></label><br>
<ul>
<li id='output1'></li>
<li id='output2'></li>
<li id='output3'></li>
</ul>
Alternate snippet
<!doctype html>
<html>
<head>
<script>
"use strict;"
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt)
{
let outputs = [byId('output1'), byId('output2'), byId('output3')];
let value = parseFloat(this.value);
if (!isNaN(value))
{
outputs[0].textContent = value * 2;
outputs[1].textContent = value * 3;
outputs[2].textContent = parseInt( (value * 3)/4 );
}
else
{
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent = "*invalid input (enter a number)*";
}
}
</script>
</head>
<body>
<label>Enter data: <input id='myInput'/></label><br>
<ul>
<li id='output1'></li>
<li id='output2'></li>
<li id='output3'></li>
</ul>
</body>
</html>

html calculated field not accepting an empty field

I am currently trying to get my calculated fields to show a total in a bottom field but in order for that to happen I have to have a value in each field. I am lost on how to get it to work with an empty field being accepted without an error. This is what i have so far:
<script type="text/javascript">
function update()
{
var form = document.forms[0];
var sum = eval(form.x.value)*60 + eval(form.y.value)*110 + eval(form.z.value)*180;
form.sum.value = isNaN(sum) ? "" : sum;
}
</script>
<form name="form1" onsubmit="false">
<fieldset>
<legend>Bloodwood</legend>
<label for="f1">Vault ($60)</label>
<input id="f1" name="x" type="number" onchange="update()">
<label for="f2">Tray ($110)</label>
<input id="f2" name="y" type="number" onchange="update()">
<label for="f3">Tower ($180)</label>
<input id="f3" name="z" type="number" onchange="update()">
<label for="f4">Total</label>
<input id="f4" name="sum" readonly="readonly">
</fieldset>
</form>
I have removed eval from the sum and it works on tab out
function update()
{
var form = document.forms[0];
var sum = form.x.value*60 + form.y.value*110 + form.z.value*180;
form.sum.value = isNaN(sum) ? "" : sum;
}
<form name="form1" onsubmit="false">
<fieldset>
<legend>Bloodwood</legend>
<label for="f1">Vault ($60)</label>
<input id="f1" name="x" type="number" onchange="update()">
<label for="f2">Tray ($110)</label>
<input id="f2" name="y" type="number" onchange="update()">
<label for="f3">Tower ($180)</label>
<input id="f3" name="z" type="number" onchange="update()">
<label for="f4">Total</label>
<input id="f4" name="sum" readonly="readonly">
</fieldset>
</form>

How to put a checkout date and prevent the user from changing it?

I would like to produce something similar to the checkin and checkout for a hotel reservation system. So far, I'm allowing the user to enter the booking date (which is the check in). However, I would like to implement an unedited input with the value of checkin plus number of nights.
So, after the user has selected the booking date and the number of nights, it would add them together and display the checkout date on the side (but the user can't change it). After the duration has finished, the user can book the same hotel again, without telling the user that they have already booked that hotel.
<body>
<form action="" method="POST">
<fieldset>
<legend>Personal Details: </legend>
<label for="phone">Phone:</label><input type="tel" name="phone" id="phone" required placeholder="Please enter in your phone number" pattern="[0-9]{4}[0-9]{3}[0-9]{3}" title="Please enter in a phone number in this format:#### ### ###">
<select name="country" required >
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
<option value="AUS">AUS</option>
</select>
</fieldset>
<br>
<fieldset>
<legend>Booking Details: </legend>
<label for="date">Booking date: </label><input id="date" type="date" name="date" min="2017-01-04">
<label for="numberOfRooms">Number of Rooms:</label><input id="NumberOfRooms" type="number" name="numberOfRooms" min="1" max="4">
<label for="numberOfNights">Number of Nights:</label><input id="NumberOfNights" type="number" name="numberOfNights" min="1" max="60">
<p>Do you require breakfast?</p>
<label for="yesBreakfast">Yes:</label><input id="yesBreakfast" type="radio" name="meals" value="yesBreakfast">
<label for="noBreakfast">No:</label><input id="noBreakfast" type="radio" name="meals" value="noBreakfast">
<br>
<!--<label for="balcony">Do you require a balcony?</label><input id="balcony" type="checkbox" name="balcony" value="yes" checked>-->
<br>
<button name="submit" type="submit">Submit</button>
</fieldset>
</form>
</body>
</html>
database tables for the book and the hotel
Book table:
id(int 11)
username(varchar 30)
hotel_id(int11)
phone(varchar 50)
date(datetime)
num_rooms(int 60)
num_nights(int 4)
Table for hotel
id(int 11)
Hotel_name(text)
Hotel_location(text)
Hotel_price(int 11)
image(varchar 500)
description(text)
I suggest you use momentjs to handle date related stuff.
I added change event on both date and NumberOfNights to call updateCheckout(), in that function will handle the checkout date
hope it helps
$(document).ready(function() {
$('#date, #NumberOfNights').on("change", updateCheckout);
$('#price, #NumberOfNights, #NumberOfRooms').on("change", updateTotalPrice);
function updateCheckout() {
var bookingDate = $('#date').val();
var numOfNights = $('#NumberOfNights').val();
if (bookingDate != '' && numOfNights != '') {
var new_date = moment(bookingDate, "YYYY-MM-DD").add(numOfNights, 'days').format("YYYY-MM-DD");
$('#checkout_date').text(new_date);
} else {
$('#checkout_date').text('N/A');
}
}
function updateTotalPrice() {
var price = $('#price').val();
var numOfNights = $('#NumberOfNights').val();
var NumberOfRooms = $('#NumberOfRooms').val();
if (price != '' && numOfNights != '' && NumberOfRooms != '') {
var total_price = +price * +numOfNights * +NumberOfRooms;
$('#total_price').text('$' + total_price);
} else {
$('#total_price').text('N/A');
}
}
});
#checkout_date,
#total_price {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<form action="" method="POST">
<fieldset>
<legend>Personal Details: </legend>
<label for="phone">Phone:</label>
<input type="tel" name="phone" id="phone" required placeholder="Please enter in your phone number" pattern="[0-9]{4}[0-9]{3}[0-9]{3}" title="Please enter in a phone number in this format:#### ### ###">
<select name="country" required>
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
<option value="AUS">AUS</option>
</select>
</fieldset>
<br>
<fieldset>
<legend>Booking Details: </legend>
<label for="date">Booking date: </label>
<input id="date" type="date" name="date" min="2017-01-04">
<label for="numberOfRooms">Number of Rooms:</label>
<input id="NumberOfRooms" type="number" name="numberOfRooms" min="1" max="4">
<label for="numberOfNights">Number of Nights:</label>
<input id="NumberOfNights" type="number" name="numberOfNights" min="1" max="60">
<label for="price">Single Room Price: </label>
<input id="price" type="number" min="0">
<br>
<br>
<label>Checkout Date:</label>
<span id="checkout_date"> N/A</span>
<p>Do you require breakfast?</p>
<label for="yesBreakfast">Yes:</label>
<input id="yesBreakfast" type="radio" name="meals" value="yesBreakfast">
<label for="noBreakfast">No:</label>
<input id="noBreakfast" type="radio" name="meals" value="noBreakfast">
<br>
<!--<label for="balcony">Do you require a balcony?</label><input id="balcony" type="checkbox" name="balcony" value="yes" checked>-->
<br>
<label>Total Price:</label>
<span id="total_price"> N/A</span>
<br><br>
<button name="submit" type="submit">Submit</button>
</fieldset>
</form>
</body>
</html>

clear html form with angularjs

I want to clear my input values in html form when you press submit.
the function is in the controller.
i tried to do: $scope.name = "" or null (for every input) but its don't work.
This is the html file:
<label for="messageName">Message Name:</label>
<input type="text" ng-model="message.name" name="message.name" required/>
<label for="text">Text:</label>
<input type="textarea" ng-model="message.text" name="message.text" required/>
<label for="images">Images:</label>
<input type="text" ng-model="message.images" name="message.images" required/>
<label for="template">Template:</label>
<input list="template" ng-model="message.template" name="message.template" required/>
<datalist id="template">
<option value="template1">
<option value="template2">
<option value="template3">
</datalist>
<label for="millisecToShow">Millisec To Show:</label>
<input type="number" min="1000" max="10000" ng-model="message.millisecToShow" name="message.millisecToShow" required/>
<label for="timeFrame">Time Frame:</label>
<label for="TimeStart">Start Time:</label>
<input type="datetime-local" ng-model="message.startDateTime" name="message.startDateTime" required/>
<label for="DateStart">End Time:</label>
<input type="datetime-local" ng-model="message.endDateTime" name="message.endDateTime" required/>
<label for="days">Days:</label><br>
<form>
<input type="checkbox" ng-model="message.sunday" name="message.days" value="Sunday">Sunday<br>
<input type="checkbox" ng-model="message.monday" name="message.days" value="Monday">Monday<br>
<input type="checkbox" ng-model="message.tuesday" name="message.days" value="Tuesday">Tuesday<br>
<input type="checkbox" ng-model="message.wednesday" name="message.days" value="Wednesday">Wednesday<br>
<input type="checkbox" ng-model="message.thursday" name="message.days" value="Thursday">Thursday<br>
<input type="checkbox" ng-model="message.friday" name="message.days" value="Friday">Friday<br>
<input type="checkbox" ng-model="message.saturday" name="message.days" value="Saturday">Saturday<br>
</form>
<label for="screenId">Screen ID:</label>
<input list="screenId" ng-model="message.screenId" name="message.screenId" required/>
<datalist id="screenId">
<option value="screen1">
<option value="screen2">
<option value="screen3">
</datalist>
<button ng-click="createButton()">Create</button>
And this is the controller:
angular.module('CreateCtrl', []).controller('CreateController', function($scope, superService) {
$scope.createButton = function() {
superService.insert($scope.message).then(function (result)
if (result == "true") {
alert('Create successful');
$scope.tagline = 'Create successful';
return result.data;
}
else {
$scope.tagline = 'Cannot create message';
}
});
};
});
I want to remove the input after sending the file.
thanks (:
Considering that all of the fields refer to $scope.message.*, wouldn't it be easier to just clean up the whole message object like this?
if (result === "true") {
alert('Create successful');
$scope.tagline = 'Create successful';
// cleaning up
$scope.message = {
name: null,
text: null,
images: null,
template: null
};
return result.data;
}
In fact, if you want to wipe the whole object clean, if it were me I would just go for $scope.message = {}; and be done with it.