So for some reason, the JavaScript that I'm using is not working on IE - There are errors which I will point out below. If someone knows anything else that I can try or knows how I can manipulate the code to make it more IE friendly, I'd really appreciate it.
Here are the steps that I've taken:
- Use https://babeljs.io/ to convert the whole page to ES2015.
- Added a polyfill script tag from https://polyfill.io/
Lots of code below (Whole general.js file which I've already converted using Babel (Please let me know if you want me to upload the original general.js file)):
Everything below rtd3Confirmation function is supposed to be:
for (var inputElement of rtd3ChangeClass) {
inputElement.addEventListener('change', rtd3Confirmation);
}
but that was before babel converted it.
"use strict";
// Form wrapper variables
var contactFormID = document.getElementById('contactForm');
var formWrapperSpecific = document.getElementById('form-wrapper-specific');
var formWrapperCertainSelection = document.getElementById('form-wrapper-certain-selection');
var formWrapperCertain = document.getElementById('form-wrapper-certain');
var formWrapperConfirm = document.getElementById('rtd3Confirm'); // Alert variables
var stateAlertID = document.getElementById('stateWarning');
var stateQuery = document.querySelector('#stateWarning b#stateName');
var resident = document.getElementById('resident');
var is_submitted = document.getElementsByClassName('is-submitted'); // Right to Know variables
var rtk5_selection = document.getElementById('rtk5');
var rtk5declaration = document.getElementById('rtk5Declaration'); // Right to Delete variables
var rtdChange = document.getElementById('rtd3');
var rtd3ChangeClass = document.querySelectorAll(".rtd3_change"); // Array for states
var states = []; // Once the DOM has loaded, call functions
document.addEventListener('DOMContentLoaded', function () {
formHandler();
residentAlert();
rtdCheckboxSelection();
rtd3Confirmation();
rtk5Declaration();
get_states();
}); // Show/hide form depending if state is included in array on dropdown selection
function formHandler() {
contactFormID.style.display = 'block';
if (resident == null) return;
if (!states.includes(resident.value)) contactFormID.style.display = 'none';
resident.addEventListener('change', formHandler);
} // Show/hide state alert for non-residents
function residentAlert() {
if (resident !== null) {
resident.addEventListener('change', function () {
// If value in states array is true, show the form
if (!states.includes(resident.value)) {
stateAlertID.style.display = 'block';
stateQuery.textContent = resident.options[resident.selectedIndex].text;
} else {
stateAlertID.style.display = 'none';
}
});
}
} // Show states dropdown depending on PHP variables
function get_states() {
var data_states = contactFormID.getAttribute('data-states').match(/\w{1,}/g);
data_states.forEach(function (state, i) {
return states[i] = state;
});
} // If RTK5 is selected, show declaration field and set required tag
function rtk5Declaration() {
if (!rtk5_selection.checked) {
formWrapperSpecific.style.display = 'none';
rtk5declaration.removeAttribute('required');
} else {
formWrapperSpecific.style.display = '';
rtk5declaration.setAttribute('required', 'required');
}
}
rtk5_selection.addEventListener('change', rtk5Declaration); // If RTD3 is selected, show/hide more checkboxes
function rtdCheckboxSelection() {
formWrapperCertain.style.display = rtdChange.checked ? '' : 'none';
document.querySelectorAll('[name="rtd[checked]"]').forEach(function (r) {
return r.addEventListener('change', rtdCheckboxSelection);
});
} // If at least one checkbox inside rtd3 is checked, show confirmation and make required
function rtd3Confirmation() {
if (document.querySelectorAll('.rtd3_change:checked').length) {
formWrapperCertainSelection.style.display = '';
formWrapperConfirm.required = true;
} else {
formWrapperCertainSelection.style.display = 'none';
formWrapperConfirm.required = false;
}
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = rtd3ChangeClass[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var inputElement = _step.value;
inputElement.addEventListener('change', rtd3Confirmation);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
Related
I have a javascript snippet that doesn't work properly on Safari / iOS and would like some help.
let coverageAtt1 = document.getElementById("att-check1");
let coverageAtt2 = document.getElementById("att-check2");
let coverageAtt3 = document.getElementById("att-check3");
let coverageAtt4 = document.getElementById("att-check4");
let checkboxes = [coverageAtt1, coverageAtt2, coverageAtt3, coverageAtt4];
let attributeCond = [];
let coverageCond = '';
for (let checkbox of checkboxes) {
checkbox.oninput = function() {updateAtt()};
function updateAtt() {
if (checkbox.checked) {
attributeCond.push(checkbox.value);
}
else if (attributeCond.includes(checkbox.value)) {
attributePosition = attributeCond.indexOf(checkbox.value);
attributeCond.splice(attributePosition, 1);
}
else {
null;
}
console.log(attributeCond);
sliders();
}
}
function sliders() {
filteredPlans = plans.filter((item) => {
if (attributeCond.length == 0) {
coverageCond = attributeCond.includes(item.coverage) == false;
}
else {
coverageCond = attributeCond.includes(item.coverage) == true;
}
return (coverageCond);
});
Opening the console in Safari states that the "checkbox" variable have not been declared/cannot be found.
I am making a list where you can edit or delete items. I am listening for 2 events on the same table. One for edit and one for delete, I am listening on the table and not the actual buttons as they are created dinamycally. Edit and Delete both have the same id, the id of the product, which I am using later for the http requests.
,
Now when I press edit the console.logs from the delete functions fire up,but nothing happens, if I am trying to save the item the http request doesnt work, it will not take the id (but it logs it to the console)
If I press the delete button once nothing happnes, if I press it a second time the page refreshes and the item is deleted.
Is there a way to listen for those events separately or for them to not interfere with one another? All I want is if I press the edit button the respective item's values to go to the input field and when I press Add Item update the product in the JSON file as well, and on delete press, to delete the item from the JSON file and remove from the html document.
Update: Managed to resolve edit function
Here is my code:
import { http } from "./http.js";
import { ui } from "./ui.js";
const productsURL = "https://61363d1a8700c50017ef54c1.mockapi.io/product";
// const addProductBtn = document.querySelector('.new-product-btn');
const adminContainer = document.querySelector('.admin-container');
const addItem = document.querySelector('.admin-add-item-btn');
const imgInput = document.getElementById('image');
const nameInput = document.getElementById('name');
const priceInput = document.getElementById('price');
const stockInput = document.getElementById('stock');
const categoryInput = document.getElementById('category');
const typeInput = document.getElementById('type');
const descriptionInput = document.getElementById('description');
const validSvg = document.querySelectorAll('.valid_input_svg');
// const adminForm = document.getElementById('admin-form');
const adminTable = document.getElementById('admin-tbody');
const editBtn = document.querySelectorAll('.edit-btn');
const adminBtn = document.querySelectorAll('.admin-delete-btn');
const cancel = document.getElementById('cancel');
let productToEdit;
let edit = false;
let id;
document.addEventListener('DOMContentLoaded', listAdminProducts);
// adminForm.addEventListener('submit', validateInput);
addItem.addEventListener('click', addOrEditProducts);
// adminTable.addEventListener('click', editOrDeleteItem);
adminTable.addEventListener('click', deleteProduct);
adminTable.addEventListener('click', editProduct);
cancel.addEventListener('click', cancelEdit);
function listAdminProducts() {
http.get(productsURL).then(products => {
ui.showAllAdminProducts(products);
});
};
function addOrEditProducts() {
if (edit === true && validateInput() === true) {
productToEdit = {
image: imgInput.value,
name: nameInput.value,
price: priceInput.value,
stock: stockInput.value,
category: categoryInput.value,
type: typeInput.value,
description: descriptionInput.value,
};
http
.put(`${productsURL}/${id}`, productToEdit)
.then(() => listAdminProducts());
console.log(`${productsURL}/${id}`)
ui.clearFields();
id = '';
edit = false;
return;
} else if (edit === false && validateInput() === true) {
const product = {
image: imgInput.value,
name: nameInput.value,
price: priceInput.value,
stock: stockInput.value,
category: categoryInput.value,
type: typeInput.value,
description: descriptionInput.value
};
http.post(productsURL, product).then(() => listAdminProducts());
ui.clearFields();
};
};
function editProduct(e) {
console.log('works');
if (e.target.classList.contains('edit-btn')) {
edit = true;
id = e.target.getAttribute('id');
console.log(id);
console.log(e.target)
http.get(`${productsURL}/${id}`).then((data) => {
imgInput.value = data.image;
nameInput.value = data.name;
priceInput.value = data.price;
stockInput.value = data.stock;
categoryInput.value = data.category;
typeInput.value = data.type;
descriptionInput.value = data.description;
});
console.log(`${productsURL}/${id}`)
};
// id = '';
}
function deleteProduct(e) {
console.log(e.target);
if (e.target.className === 'admin-delete-btn') {
console.log(e.target);
id = e.target.getAttribute('id');
console.log(id);
http
.delete(`${productsURL}/${id}`)
.then(() => listAdminProducts())
.catch("Error on delete");
id = '';
}
ui.showSuccessMessage('Product deleted', adminContainer);
}
function cancelEdit() {
ui.clearFields;
imgInput.className = '';
nameInput.className = '';
priceInput.className = '';
stockInput.className = '';
categoryInput.className = '';
edit = false;
}
function validateInput() {
let valid = true;
if (imgInput.value == '') {
if (imgInput.classList.contains('input-invalid')) {
imgInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Must contain a link to an image', 0);
imgInput.classList.add('input-invalid');
valid = false;
} else {
imgInput.classList.add('input-valid');
validSvg[0].style.display = "block";
removeClass(imgInput, 0);
};
if (nameInput.value === '') {
if (nameInput.classList.contains('input-invalid')) {
nameInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Name is requierd', 1);
nameInput.classList.add('input-invalid');
valid = false;
} else {
// stockInput.classList.remove('input-invalid');
nameInput.classList.add('input-valid');
validSvg[1].style.display = "block";
removeClass(nameInput, 1);
};
if (priceInput.value == "" || isNaN(priceInput.value) || priceInput.value < 0) {
if (priceInput.classList.contains('input-invalid')) {
priceInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Price must be a number greater then 0', 2);
priceInput.classList.add('input-invalid');
valid = false;
} else {
// stockInput.classList.remove('input-invalid');
priceInput.classList.add('input-valid');
validSvg[2].style.display = "block";
removeClass(priceInput, 2);
};
if (stockInput.value == "" || isNaN(stockInput.value) || stockInput.value < 0) {
if (stockInput.classList.contains('input-invalid')) {
stockInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Stock must be a number greater then 0', 3);
stockInput.classList.add('input-invalid');
valid = false;
} else {
// stockInput.classList.remove('input-invalid');
stockInput.classList.add('input-valid');
validSvg[3].style.display = "block";
removeClass(stockInput, 3);
};
if (categoryInput.value === 'barware' || categoryInput.value === 'spirits') {
// categoryInput.classList.remove('input-invalid');
categoryInput.classList.add('input-valid');
validSvg[4].style.display = "block";
removeClass(categoryInput, 4);
} else {
ui.showAdminMessage('Category must be barware or spirits', 4);
categoryInput.classList.add('input-invalid');
valid = false;
};
return valid;
};
function removeClass(element, index) {
// console.log(element, index);
setTimeout(() => {
element.className = '';
validSvg[index].style.display = "none";
}, 3000)
}
Finally managed to resolve it, I had to put e.preventDefault() in both functions, so the page will not reload first
I have made a list application using JavaScript. I want to be able to put in items and when I click the button grab the items or tasks randomly. I got it to grab the tasks randomly, but want it to end once its gone through the items added. Right now it just keeps randomly cycling through the list endlessly. What am I missing?
Here's the code:
var taskList = [];
var $ = function(id) {
return document.getElementById(id);
}
var listTasks = function() {
textList = "";
for (var i in taskList) {
textList += taskList[i] + "\n";
}
$("task_list").value = textList;
}
var addTask = function() {
taskList[taskList.length] = $("new_task").value;
$("new_task").value = "";
$("new_task").focus();
listTasks();
}
var showNextTask = function() {
if (taskList.length == 0) {
alert("No tasks in the list");
$("next_task").value = "";
} else {
$("next_task").value = taskList[Math.floor(Math.random() * taskList.length)];
taskList.shift(Math.value());
}
if (taskList.length == 0) {
alert("No tasks in the list");
$("next_task").value = "";
}
};
window.onload = function() {
$("add_task").onclick = addTask;
$("show_next_task").onclick = showNextTask;
$("new_task").focus();
}
I have JavaScript calculator wherein I have defined two arrays as follows:
var degInc, degArr = [];
var radInc, radArr = [];
var PI = Math.PI;
var radStart = (-91*PI/2), radEnd = (91*PI/2);
for (degInc = -8190; degInc <= 8190; degInc+=180) {
degArr.push(degInc);
}
for (radInc = radStart; radInc <= radEnd; radInc+=PI) {
var radIncFixed = radInc.toFixed(8);
radArr.push(radIncFixed);
}
to be used in conjunction with the tangent function (below) so as to display a value of Undefined in an input (HTML below) should the user attempt to take the tangent of these values (I have included other relavent function as well):
Input -
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>
Functions -
function tan(form) {
form.display.value = trigPrecision(Math.tan(form.display.value));
}
function tanDeg(form) {
form.display.value = trigPrecision(Math.tan(radians(form)));
}
function radians(form) {
return form.display.value * Math.PI / 180;
}
with jQuery -
$("#button-tan").click(function(){
if (checkNum(this.form.display.value)) {
if($("#button-mode").val() === 'DEG'){
tan(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR RAD ARRAY
}
else{
tanDeg(this.form); // INSERT OTHER 'if' STATEMENT HERE FOR DEG ARRAY
}
}
});
I would like to incorporate an array check within the .click function such that if the user input is contained in the array (degArr or radArr depending on the mode), the calculator returns Undefined. Now, I know how to display Undefined in the input display ($('#disp').val('Undefined')), but I cannot figure out how to configure an if statement that checks the relevant array. Is there a way to do so within the #button-tan function where I have commented?
Loop through the arrays on click and set a variable if you find a matched value.
You can do something like this:
$("#button-tan").click(function(e) {
e.preventDefault();
var userInput = $('#disp').val();
var buttonMode = $('#button-mode').val();
var displayVal = '';
if (buttonMode === 'DEG') {
var radFound = false;
radArr.forEach(function(item) { // changed from degArr
if (item === userInput) {
radFound = true;
}
if (radFound) {
displayVal = 'undefined';
} else {
tan(this.form);
}
});
} else {
var degFound = false;
degArr.forEach(function(item) {
if (item === userInput) {
degFound = true;
}
if (degFound) {
displayVal = 'undefined';
} else {
tanDeg(this.form);
}
});
}
});
You could create a simple object of a Calculator class, which keeps a reference to these arrays, and use like this. I changed some methods to receive the input as parameter rather than form.
$(function () {
function Calculator()
{
var degInc;
this.degArr = [];
var radInc;
this.radArr = [];
var PI = Math.PI;
var radStart = (-91*PI/2);
var radEnd = (91*PI/2);
for (degInc = -8190; degInc <= 8190; degInc+=180) {
this.degArr.push(degInc);
}
for (radInc = radStart; radInc <= radEnd; radInc+=PI) {
var radIncFixed = radInc.toFixed(8);
this.radArr.push(radIncFixed);
}
}
var calc = new Calculator();
function tan(input) {
alert("tan called");
var value = Math.tan(input.value);
alert("tan called. value: " + value);
input.value = value;
}
function tanDeg(input) {
alert("tanDeg called");
var value = Math.tan(radians(input));
alert("tanDeg called. value: " + value);
input.value = value;
}
function radians(input) {
alert("radians called");
var value = input.value * Math.PI / 180;
alert("radians called. value: " + value);
return value;
}
$("#button-tan").click(function(){
alert (calc.degArr);
alert (calc.radArr);
var displayInput = $("#disp");
alert("user input: " + displayInput.val());
if (!isNaN(displayInput.val()))
{
if($("#button-mode").val() === 'DEG')
{
if (calc.radArr.indexOf(displayInput.val()) > -1)
{
alert("user input is in radArr");
}
else
{
alert("user input IS NOT in radArr");
tan(displayInput);
}
}
else
{
if (calc.degArr.indexOf(displayInput.val()) > -1)
{
alert("user input is in degArr");
}
else {
alert("user input IS NOT in degArr");
tan(displayInput);
}
}
}
else
alert("Not a number in input");
});
});
If you wanna do some tests, I created a JSFiddle demo here. Type -8190 in the first input, then click the button. It's gonna be inside the array. Then try typing "DEG" in the second input and clicking again, you'll notice code will check against another array (due to IFs). I couldn't make your auxiliar functions to calculate a value, but I think this helps you with your initial problem.
indexOf should work...
$("#button-tan").click(function(){
if (checkNum(this.form.display.value)) {
if($("#button-mode").val() === 'DEG'){
if (radArr.indexOf(Number(this.form)) > -1) {
$('#disp').val('Undefined');
} else {
tan(this.form);
}
}
else{
if (degArr.indexOf(Number(this.form)) > -1) {
$('#disp').val('Undefined');
} else {
tanDeg(this.form);
}
}
}
});
I'm working on a form that will have a "Validate" button. The purpose of this button is to check and make sure all the fields are completed (this is what the project demands). Below is the code that checks to see if the field is null and then changes the border color and displays a text box.
if (form1.Main.sfRequestor.requestNameFirst.rawValue == null){
form1.Main.sfRequest.txtValidate.presence = "visible";
form1.Main.sfRequestor.requestNameFirst.border.edge.color.value = "255,0,0"
} else {
form1.Main.sfRequest.txtValidate.presence = "hidden";
form1.Main.sfRequestor.requestNameFirst.border.edge.color.value = "255,255,255"
};
if (form1.Main.sfRequestor.requestNameLast.rawValue == null){
form1.Main.sfRequest.txtValidate.presence = "visible";
form1.Main.sfRequestor.requestNameLast.border.edge.color.value = "255,0,0"
} else {
form1.Main.sfRequest.txtValidate.presence = "hidden";
form1.Main.sfRequestor.requestNameLast.border.edge.color.value = "255,255,255"
};
There are 20+ fields in several subforms that need to be checked. I'm trying to consolidate the code but am at a loss on how to do so. Can variables handle field names in Javascript?
You can make this into a loop pretty easily, and could write it as an IIFE to keep your namespace clean
(function (arr) {
var txtValidate = form1.Main.sfRequest.txtValidate,
i, e;
for (i = 0; i < arr.length; ++i) {
e = form1.Main.sfRequestor[arr[i]]; // cache me
if (e.rawValue == null){
txtValidate.presence = "visible";
e.border.edge.color.value = "255,0,0"
} else {
txtValidate.presence = "hidden";
e.border.edge.color.value = "255,255,255"
}
}
}(['requestNameFirst', 'requestNameLast']));
However, it looks like txtValidate.presence only ever gets set to whatever the last item's conditions were, are you sure you don't want to use a flag and set this last instead? e.g.
(function (arr) {
var txtValidateState = 'hidden',
i, e;
for (i = 0; i < arr.length; ++i) {
e = form1.Main.sfRequestor[arr[i]];
if (e.rawValue == null){
txtValidateState = "visible"; // any null makes txtValidate visible
e.border.edge.color.value = "255,0,0"
} else {
e.border.edge.color.value = "255,255,255"
}
}
form1.Main.sfRequest.txtValidate.presence = txtValidateState; // set last
}(['requestNameFirst', 'requestNameLast']));
Update for generic forms, assuming sfRequestor and sfRequest
(function (form, arr) {
var txtValidateState = 'hidden',
i, e;
for (i = 0; i < arr.length; ++i) {
e = form.sfRequestor[arr[i]];
if (e.rawValue == null){
txtValidateState = "visible";
e.border.edge.color.value = "255,0,0";
} else {
e.border.edge.color.value = "255,255,255";
}
}
form.sfRequest.txtValidate.presence = txtValidateState;
}(form1.Main, ['requestNameFirst', 'requestNameLast']));
Update Assuming sfRequest is a constant but sfRequestor could be something different
(function () { // moved IIFE to protect namespace
function validate(form, subform, arr) { // now named, new param subform
var txtValidateState = 'hidden',
i, e;
for (i = 0; i < arr.length; ++i) {
e = form[subform][arr[i]]; // select from subform
if (e.rawValue == null){
txtValidateState = "visible";
e.border.edge.color.value = "255,0,0";
} else {
e.border.edge.color.value = "255,255,255";
}
}
form.sfRequest.txtValidate.presence = txtValidateState; // assuming stays same
}
validate(form1.Main, 'sfRequestor', ['requestNameFirst', 'requestNameLast']);
validate(form1.Main, 'sfClientInfo', ['firstname']);
// if you have many here you can re-write as a loop again
}());
You could easily make this into a simple function:
function validateField(element) {
if (element.rawValue == null) {
form1.Main.sfRequest.txtValidate.presence = "visible";
element.border.edge.color.calue = "255,0,0";
}
else {
form1.Main.sfRequest.txtValidate.presence = "hidden";
element.border.edge.color.calue = "255,255,255";
}
}
And then just call it like so:
validateField(form1.Main.sfRequestor.requestNameFirst);
validateField(form1.Main.sfRequestor.requestNameLast);
To simplify even further, put all 20 elements in an array and loop
var elements = [form1.Main.sfRequestor.requestNameFirst, form1.Main.sfRequestor.requestNameLast, ...];
elements.forEach(function(element) {
validateField(element);
});