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

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>

Related

Multi-Part HTML Form Validating Only Some Inputs

I have this multi-part HTML form... I know it is a bit messy! I am working on it!
I want the validation to work but only work on the inputs that are not disabled. I want to make it so on the dropdowns when the text inputs are not disabled, it checks them but when they are disabled, they don't be checked!
How?
<?php
$conn = mysqli_connect("localhost", 'admin', 'myphpadmin', 'tests');
$qm = "Select Name From options Where `Type` = 'Merchant'";
$merchant = mysqli_query($conn, $qm);
$qt = "Select Name From options Where `Type` = 'Type'";
$type = mysqli_query($conn, $qt);
$qs = "Select Name From options Where `Type` = 'Source'";
$source = mysqli_query($conn, $qs);
$qsub = "Select Name From options Where `Type` = 'Sub'";
$sub = mysqli_query($conn, $qsub);
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='stylesheet' href='../Bootstrap/css/bootstrap.css'
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
</style>
<body>
<form id="regForm" action="multi.php">
<h1>Add Transaction</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Details
<p><input placeholder="Description" oninput="this.classList.remove('invalid')" class='form-control' name="description"></p>
<p><input oninput="this.classList.remove('invalid')" name="date" type='date' class='form-control'></p>
<p><input placeholder='Amount' oninput="this.classList.remove('invalid')" name="amount" type='number' step='0.01' class='form-control'></p>
</div>
<div class="tab">Merchant
<p>
<select oninput="this.classList.remove('invalid')" onchange='merch(this.value)' name="merchant" class='form-control'>
<option value='' disable selected hidden>Select Merchant</option>
<?php
while($row = mysqli_fetch_assoc($merchant)){
foreach($row as $val){
echo "\t\t\t\t\t\t<option value='$val'>$val</option>\n";
}
}
?>
<option value='other'>Other</option>
</select>
</p>
<p><input type='text' name='om' class='form-control omerch' placeholder='Other Merchant' disabled></p>
<p><input type='checkbox' name='am' class='form-check-input omerch' id='om' disabled><label for='om' >&nbspAdd To Merchants List?</label></p>
</div>
<div class="tab">Type
<p>
<select oninput="this.classList.remove('invalid')" onchange='checktype(this.value)' name="type" class='form-control'>
<option value='' disable selected hidden>Select Type</option>
<?php
while($row = mysqli_fetch_assoc($type)){
foreach($row as $val){
echo "\t\t\t\t\t\t<option value='$val'>$val</option>\n";
}
}
?>
<option value='other'>Other</option>
</select>
</p>
<p><input type='text' name='ot' class='form-control otype' placeholder='Other Type' disabled></p>
<p><input type='checkbox' name='at' class='form-check-input otype' id='ot' disabled><label for='ot' >&nbspAdd To Types List?</label></p>
</div>
<div class="tab">Sub:
<p>
<select oninput="this.classList.remove('invalid')" onchange='checksub(this.value)' name="sub" class='form-control'>
<option value='' disable selected hidden>Select Sub-Type</option>
<?php
while($row = mysqli_fetch_assoc($sub)){
foreach($row as $val){
echo "\t\t\t\t\t\t<option value='$val'>$val</option>\n";
}
}
?>
<option value='other'>Other</option>
</select>
</p>
<p><input type='text' name='os' disabled class='form-control otype' placeholder='Other Sob' ></p>
<p><input type='checkbox' name='as' class='form-check-input osub' id='ot' disabled><label for='ot' >&nbspAdd To Subs List?</label></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
<script>
function merch(value){
console.log(value);
if(value == 'other'){
$('.omerch').removeAttr('disabled');
console.log('enabled')
}
else{
$('.omerch').attr('disabled','disabled');
console.log('disabled')
$('input[type="checkbox"].omerch').attr('checked', false);
$('input[type="text"].omerch').val('');
}
}
</script>
</body>
</html>
Does anyone know how to do this? I used input:enabled, input:not(:disabled)... Nothing worked!
Thanks!
You need to just change one line and you can do this with JS itself rather than with your selector:
if (y[i].value == "")
to
if (y[i].value == "" && !y[i].disabled) {
Basically we say, is it blank and not (!) disabled.
Or if you do want to do it with CSS selectors it is
input:not([disabled]) as disabled is an attribute and you need to use the attribute selector ([]).
Also you are using getElementByTagName - use querySelectorAll instead as otherwise you are limited in the CSS you can use (Tag Name is for the element type such as input, button etc. so you can't use CSS selectors there).
Full Validator Code JS way
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
///////////////////////////////////CHANGED HERE////////////////////////////
// If a field is empty and NOT disabled...
if (y[i].value == "" && !y[i].disabled) {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Full Validator code CSS way
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
///////////////////////////////////CHANGED HERE////////////////////////////
y = x[currentTab].querySelectorAll("input:not([disabled])");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
A quick note
You may want to look into the :valid psuedo selector. It has the added benefit that you get some native checks for validation if you give the input a type attribute. It will also be invalid if you have an empty field provided you use the required attribute.
I have stolen the example from the MSDN page and added it below to show you how easy it can make life, not a single line of JS there.
You could then query your inputs with input:valid and input:invalid within your JavaScript so it makes life easier there too.
That gives you a good grounding and a nice fallback incase your JS fails for any reason, but JavaScript is still useful to improve the accessibility.
Finally if you do decide to use the :valid and :invalid pseudo selectors and still want to perform some custom validation on top you can use the setCustomValidity function so you can rely on them solely (not a lot of people seem to know about this!)
input + span {
position: relative;
}
input + span::before {
position: absolute;
right: -20px;
top: 5px;
}
input:invalid {
border: 2px solid red;
}
input:invalid + span::before {
content: '✖';
color: red;
}
input:valid + span::before {
content: '✓';
color: green;
}
<form>
<fieldset>
<legend>Feedback form</legend>
<p>Required fields are labelled with "required".</p>
<div>
<label for="fname">First name: </label>
<input id="fname" name="fname" type="text" required>
<span></span>
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" name="lname" type="text" required disabled>
<span></span>
</div>
<div>
<label for="email">Email address (): </label>
<input id="email" name="email" type="email" required>
<span></span>
</div>
<div><button>Submit</button></div>
</fieldset>
</form>

HTML Form Using JavaScript Valildation

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.

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 />

Calculate difference of multiple inputs and write on page

I'm having an issue calculating the difference of two variables that should change depending on input values and number of inputs.
The jQuery works fine adding/subtracting buttons it's the peoplePaid() function that I've been dealing with.
I'm trying to write the difference (.difference) of paidTotal minus each input of pCheck.
So the first question is how do I get the value for difference (paidTotal - pCheck) to write to .difference for each input on the page.
And if I have to loop iy what may need to be done.
Thank you!
$(document).ready(function () {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function (e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i = myNode.childNodes.length - 1;
if (i >= 0) {
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = parseFloat(document.getElementById('check').value);
var personsCheck = document.getElementsByClassName('persons');
var paidTotal = document.getElementById('paidTotal');
var serviceQuality = document.getElementById('serviceQuality').value;
var difference = document.getElementsByClassName('difference');
var pCheck = 0;
for (var i = 0; i < personsCheck.length; i += 1) {
pCheck += parseFloat(personsCheck[i].value);
}
paidTotal.innerHTML = (checkTotal * serviceQuality) - pCheck;
for (var i = 0; i < personsCheck.length; i += 1) {
checkDifference = parseFloat(paidTotal - pCheck).value;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Check Total</h3>
$ <input type="text" id="check" value="" />
<h3>Tip%</h3>
<select name="tip" id="serviceQuality">
<option disabled selected value="1">-- Choose an Option --</option>
<option value="1">0%</option>
<option value="1.06">6%</option>
<option value="1.15">15%</option>
<option value="1.2">20%</option>
<option value="1.3">30%</option>
</select>
<h3>Number of People: <span id="numberOfPeople"></span></h3>
<button type="button" onclick="plusOne()" id="plusOne">+</button>
<button type="button" onclick="minusOne()" id="minusOne">-</button>
<div>
<div id="userNumbers">
<input type="text" class="persons" name="person" />
<p class="difference">$</p>
</div>
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
Disscrepancies
There were some discrepancies that should be addressed:
(Major) There are two functions called by onclick event handlers:
<button type="button" onclick="plusOne()" id="plusOne">+</button>
<button type="button" onclick="minusOne()" id="minusOne">-</button>
First of all, a quick run of this Snippet logs errors about these functions not existing. Secondly, you should never use on-event handlers when using jQuery, it's like using paddle (on-event handlers) on a speed boat (event delegation using .on()).
(Minor) If you store jQuery Objects in variables, do not wrap those variables in $(...) because they already wrapped in $(...) when you declared them:
var addButton = $('#plusOne');
$(addButton).on('click',... // That is like doing this: $($('#plusOne'))
addButton.on('click',...... // This is the cleaner way or...
var $addButton = $('#plusOne');
$addButton.on('click'...... /* This is a common practice which serves as an obvious
reminder that the variable is a jQuery Object */
Plain JavaScript Array Methods
(Core) The solution is to collect all of the input.customer' by gathering the <input>s into a NodeList with .querySelctorAll() and then converting it into an array with Array.from():
var customers = Array.from(document.querySelectorAll('.customer'));
Next, use .map() to extract each of the <input>'s values, and then return them as an array:
var payments = customers.map(function(customer) {
return parseFloat(customer.value);
});
Finally, use .reduce() to add all of the values in the payments array into one number:
paidTotal = payments.reduce(function(total, number) {
return total + number;
});
Demo
var max = 20;
var count = 1;
var paidTotal = 0;
var customerQty = $('#totalCustomers');
var add = $('#add');
var group = $('.group');
var paid = `
<li>
<input type="number" class="customer" step='0.01'/>
<button type="button" class="remove">-</button>
</li>`;
add.on('click', function(e) {
if (count < max) {
count++;
group.append(paid);
} else {
return false;
}
customerQty.val(count);
});
group.on('click', '.remove', function() {
if (count > 0) {
count--;
var subtract = parseFloat($(this).prev('.customer').val()).toFixed(2);
var total = parseFloat($('#paidTotal').val()).toFixed(2);
var newTotal = parseFloat(total - subtract).toFixed(2);
$('#paidTotal').val(newTotal);
var due = parseFloat($('#balanceDue').val());
$('#balanceDue').val((due + parseFloat(subtract)).toFixed(2));
$(this).parent().remove();
} else {
return false;
}
customerQty.val(count);
});
$('#bill').on('input', totalPaid);
function totalPaid(e) {
var check = $('#check').val();
var tip = $('#tip').val();
var total = $('#paidTotal');
var due = $('#balanceDue');
var customers = Array.from(document.querySelectorAll('.customer'));
var payments = customers.map(function(customer) {
return parseFloat(customer.value);
});
//console.log('payments: '+payments);
paidTotal = payments.reduce(function(total, number) {
return total + number;
});
$('#amountDue').val(parseFloat(check * tip).toFixed(2));
//console.log('paidTotal: '+paidTotal);
total.val(parseFloat(paidTotal).toFixed(2));
due.val(parseFloat((check * tip) - total.val()).toFixed(2));
}
html {
font: 400 16px/1.5 Consolas;
}
body {
font-size: 1rem;
}
fieldset {
width: 490px;
}
button,
label,
select,
input,
output {
display: inline-block;
font: inherit;
line-height: 1.5;
}
label {
margin: 5px;
}
input {
width: 12ex;
text-align: center
}
button {
cursor: pointer;
}
output {
margin-left: -5px;
}
#totalCustomers {
font-size: 1.2rem;
color: blue;
}
#tip {
padding: 5px 0;
margin-left: -5px;
}
.tip {
margin-left: -2px;
}
.customers {
height: fit-content;
min-height: 60px;
}
.group {
margin: -8% 10px auto -25px;
padding-left: 1.5em;
width: 40%;
list-style-position: inside;
}
.group li {
padding-left: 0.1em;
}
.add {
transform: translate(105%, -15%);
}
/*
For debugging purposes only (Optional)
*/
.as-console-wrapper {
width: 250px;
min-height: 100%;
margin-left: 50%;
background: #000;
color: lime;
}
.as-console-row.as-console-row {
background: #000;
}
.as-console-row.as-console-row::after {
content: '';
padding: 0;
margin: 0;
border: 0;
width: 0;
}
<form id='bill'>
<fieldset class='total'>
<legend>Total Amount Due</legend>
$ <input type="number" id="check" value="" step='0.01' min='0.00'>
<label class='tip'>Tip%</label>
<select id="tip">
<option disabled selected value="">Pick</option>
<option value="1">0%</option>
<option value="1.06">6%</option>
<option value="1.15">15%</option>
<option value="1.2">20%</option>
<option value="1.3">30%</option>
</select>
<label>Amount Due: $
<output id="amountDue">0.00</output>
</label>
</fieldset>
<fieldset class='customers'>
<legend>Total Customers:
<output id="totalCustomers">1</output>
</legend>
<label class='add'> Add a Customer
<button type="button" id="add">+</button>
</label>
<ol class='group'>
<li>
<input type="number" class="customer" step='0.01' min='0.00' />
<button type="button" class="remove">-</button>
</li>
</ol>
</fieldset>
<fieldset class='grandTotal'>
<legend>Total Balance</legend>
<label>Paid Amount: $
<output id="paidTotal">0.00</output>
</label>
<br>
<label>Balance Due: $
<output id="balanceDue">0.00</output>
</label>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Add Dynamic Textbox if Radio Button is selected + Alert bug

I have 2 problems that i am not able to solve:
The code should show me a Alert if everything is correctly saved. I made that alert message, but if i add 10 elements and click save, i get 10 alerts.
Unable to add dynamical textfield after i press the Radio Button in the drop down. I did a lot of things, but whenever i implant it, indexedDB stops working.
Bonus question if somebody knows the answer to:
3. How can i save the Forms i made in the Forms tab, so i can search them later and put new info in?
var db;
function indexedDBOk() {
return "indexedDB" in window;
}
document.addEventListener("DOMContentLoaded", function() {
//No support? Go in the corner and pout.
if(!indexedDBOk) return;
var openRequest = indexedDB.open("idarticle_people4",1);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("people")) {
thisDB.createObjectStore("people", {autoIncrement:true});
}
};
openRequest.onsuccess = function(e) {
db = e.target.result;
//Listen for add clicks
document.querySelector("#addButton").addEventListener("click", addPerson, false);
openRequest.onsuccess = function(e) {
alert('success: version 1 opened');
};
//Listen for get clicks
document.querySelector("#getButton").addEventListener("click", getPerson, false);
};
openRequest.onerror = function(e) {
}
},false);
function addPerson(e) {
//console.log(i);
var person= new Array(polje2);
for (n=0; n<i; n++) {
person.length=i;
var element='#element';
element+=n;
var unos='#unos';
unos+=n;
var provjera = document.querySelector(element).type;
var polje1 = document.querySelector(unos).innerHTML;
if (provjera=='checkbox') {
var polje2 = document.querySelector(element).checked
}
else {
polje2 = document.querySelector(element).value
}
if (polje2==='') {
alert ('Uspješno snimljeno');
}
//default for OS list is all, default for type is read
var transaction = db.transaction(["people"],"readwrite");
//Ask for the objectStore
var store = transaction.objectStore("people");
person[n]=
{pitanje: polje1, odgovor:polje2 };
}
//Perform the add
var request = store.add(person);
request.onerror = function(e) {
console.log("Error",e.target.error.
name);
//some type of error handler
};
request.onsuccess = function(e) {
console.log("Jej, uspjelo je");
}
}
function getPerson(e) {
var key = document.querySelector("#key").value;
if(key === "") return;
var transaction = db.transaction(["people"],"readonly");
var store = transaction.objectStore("people");
var request = store.get(Number(key));
request.onsuccess = function(e) {
var result = e.target.result;
if(result) {
var s = "<h2>Forma broj: "+key+"</h2><p>";
for(var j=0; j<result.length; j++) {
s+= (result[j].pitanje + ': ' + result[j].odgovor + "<br/>");
}
document.querySelector("#status").innerHTML = s;
}
else {
document.getElementById('element').style.visibility='visible'
}
}
}
// get allPeople
// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
var type1 = document.getElementById('type1').value;
var type2 = document.getElementById('type2').value;
var question = document.getElementById('question').value;
var counter = 'Element';
counter+= a;
var prviElement=document.createElement('span');
prviElement.textContent= counter + ':' +' ';
document.body.appendChild(prviElement);
var pitanje= document.createElement('span');
var unos='unos';
unos += i;
pitanje.id=unos;
pitanje.textContent=question + ' ';
document.body.appendChild(pitanje);
var tip1 = document.createElement("input");
var element='element';
element += i;
tip1.id=element;
if (type1=='textbox') {
tip1.type=type2
} else {
tip1.type=type1
}
document.body.appendChild(tip1);
var linija1= document.createElement("br");
document.body.appendChild(linija1);
var linija2= document.createElement("br");
document.body.appendChild(linija2);
i++;
a++;
}
function AddTextBox(elm) {
var v = elm.value;
var iCounter = elm.id.replace('type1', '');
if (v == 'radio') {
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.id = 'txtSecond' + iCounter;
elm.parentNode.insertBefore(textbox, elm.nextSibling);
} else {
//Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
var rmv = document.getElementById('txtSecond' + iCounter);
if (rmv != undefined) {
rmv.remove();
}
}
}
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'testvalue';
}
/* Dropdown Button */
.dropbtn {
background-color: #A9A9A9;
color: white;
padding: 10px;
font-size: 16px;
text-align:center;
border: none;
cursor: pointer;
}
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #696969;}
input{
text-align:left;
}
.hide {
visibility: hidden
}
.h1 {
font-size: 4em;
}
.h2 {
font-size: 2.5em;
}
/* Dropdown Button */
.dropbtn2 {
background-color: #A9A9A9;
color: white;
padding: 10px;
font-size: 16px;
text-align:center;
border: none;
cursor: pointer;
margin-left:580px;
}
/* Dropdown button on hover & focus */
.dropbtn2:hover, .dropbtn2:focus {
background-color: #696969;}
input{
text-align:left;
}
.kocka {
max-width: 291px;
max-height: 94px;
background-color: #91ceff;
border: 20px;
border-style:solid;
border-color:#91ceff;
}
.kocka2 {
max-width: 291px;
max-height: 94px;
background-color: #91ceff;
border: 20px;
border-style:solid;
border-color:#91ceff;
}
/* Dropdown button on hover & focus */
.kocka2:hover, .kocka2:focus {
background-color: #696969;}
input{
text-align:left;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="pepo.css">
<meta charset="UTF-8">
<script src="basa.js"></script>
<title>OnlineForms</title>
</head>
<body>
<!--Ovaj kod je za Main Page-->
<Main class="kocka">
<div align="left">
<input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>
      
<button class="dropbtn" id="getAllButton">Forms</button>
</div>
<br>
<div align="left">
<input type="number" id="key" class="dropbtn" Placeholder="Type the key value"/>
<button class="dropbtn" id="getButton"> Search </button>
<br>
<br>
</div>
</Main>
<!--Ovaj kod je za Elemente-->
<div id="element" class="hide">
<h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
<select title="ddmenu" class="dropbtn" id="type1">
<option selected disabled hidden value="Please select">Please select</option>
<option value="textbox">textbox</option>
<option value="checkbox">checkbox</option>
<option value="radio">radio button</option>
</select>
<select title="ddmenu" class="dropbtn" id="type2">
<option selected disabled hidden value="Please select">Please select</option>
<option value="none">none</option>
<option value="mandatory">mandatory</option>
<option value="number">numeric</option>
</select>
</h1>
<input type="button" id="adddugme" class="dropbtn2" value="Add" onclick="mojaFunkcija()"/>
<br>
<br>
<button id="addButton" class='dropbtn'>Save</button>
</div>
<br>
<br>
<div id="status"></div>
<br>
<div id="status2"></div>
</body>
</html>

Categories

Resources