Variable is declared but its value is never read JavaScript - javascript

my goal is to get the Close button in this modal to leave the inputs as they are when the Save button has been pressed before. It already Saves the values and resets them when I click the Cancel button but my variable "saved" is declared and even when I use it in the functions it shows me this error and doesnt do what I want.
import {
getInput, setInput
} from '../../service/data'
let close = document.getElementById('advsettings_close');
let cancel = document.getElementById('advsettings_cancel');
let save = document.getElementById('advsettings_save');
const settingsForm = document.getElementById('advsettings_form');
const settingsSliders = settingsForm.querySelectorAll('input');
var saved = false;
cancel.addEventListener('click', function() {
cancelSettings();
});
save.addEventListener('click', function() {
saveSettings();
});
close.addEventListener('click', function() {
closeSettings();
});
settingsForm.addEventListener('submit', function (event){
event.preventDefault();
});
function cancelSettings(){
settingsSliders.forEach(function(input) {
input.value = 5;
console.log('Values canceled and reset');
});
saved = false;
}
function saveSettings(){
settingsSliders.forEach(function(input) {
if (input.type === 'range') {
setInput(input.name, input.value);
console.log('Save Value of ' + input.name + ':', input.value);
}
});
saved = true;
}
function closeSettings(){
settingsSliders.forEach(function(input) {
if (saved = true){
input.value = setInput(input.name, getInput(input.value));
} else if(saved = false) {
input.value = 5;
}
});
}

There is a mistake in the if confition:
function closeSettings(){
settingsSliders.forEach(function(input) {
if (saved == true){
input.value = setInput(input.name, getInput(input.value));
} else if(saved == false) {
input.value = 5;
}
}
Also, it is better to directly evaluate conditions as booleans:
function closeSettings(){
settingsSliders.forEach(function(input) {
if (saved){
input.value = setInput(input.name, getInput(input.value));
} else{
input.value = 5;
}
}

Related

Javascript form validation submit function is being called only once

So I have the JQuery code here:
$(function() {
const $facesSelectorContainer = $('.faces-select');
if ($facesSelectorContainer) {
// store some variables
const $hiddenFacesSelector = $('.selection-wrapper-faces'),
$facesButtons = $facesSelectorContainer.find('.faces-container'),
$facesSelector = $hiddenFacesSelector.find('select'),
$facesUpload = $('.faces-upload'),
$facesUploadFields = $facesUpload.find('.face-upload-container');
// upload the number of faces upload inputs visible
function updateFacesNumber(e) {
const number = parseInt($facesSelector.val());
for(let i = 0, max = $facesUploadFields.length; i < max; i++) {
const $field = $facesUploadFields.eq(i), $input = $field.find('input[type="file"]');
$field.toggle(i < number).removeClass('required');
if (i >= number) {
$input.prop('required', false);
} else {
$input.prop('required', true);
}
$input.trigger('change');
}
$facesButtons.removeClass('selected');
$facesButtons.filter(`[data-faces-number="${number}"]`).addClass('selected');
}
$('.faces-container').on('click', (e) => {
const j = $(e.target).closest('.faces-container').index()-1;
console.log(j);
$('.faces-container').removeClass('selected');
$(e.target).closest('.faces-container').addClass('selected');
$facesUploadFields.removeClass('show');
for ( let g=1;g<=j;g++)
$facesUploadFields.eq(g).addClass('show');
});
updateFacesNumber();
setTimeout(updateFacesNumber, 10); // re-update after 10ms, so that images in cache will be loaded
$facesSelector.on('change', updateFacesNumber);
// update the faces number on click
$facesSelectorContainer.on('click', '.faces-container', function(e) {
e.preventDefault(); e.stopPropagation();
const value = $(this).data('faces-number');
$facesSelector.val( value ).trigger('change');
});
// handle uploads
$facesUploadFields.on('change', 'input[type="file"]', function() {
const file = this.files, $this = $(this), $field = $this.closest('.face-upload-container'), $image = $field.find('.preview-image'), $remove = $field.find('.remove'), $required = $field.find('.required');
if (file.length) {
$field.removeClass('empty required');
const blob = window.URL.createObjectURL(file[0]);
$image.css({ 'background-image': 'url(' + blob + ')' }).addClass('visible');
$image.addClass('show');
$remove.addClass('show');
$required.addClass('hide');
} else {
// $('#AddToCart').attr('disabled','disabled');
//$('#AddToCart').css({ opacity: 0.5 });
$field.addClass('empty');
$image.css({ 'background-image': '' }).removeClass('visible');
$image.removeClass('show');
$remove.removeClass('show');
$required.removeClass('hide');
}
/*if($('.empty.show').length===0 && $('#type-dogs-name').val().length ){
console.log('radi');
$('#AddToCart').removeAttr('disabled');
$('#AddToCart').css({ opacity: 1 });
}*/
}).on('click', '.remove', function(e) {
e.preventDefault(); e.stopPropagation();
const $this = $(this), $field = $this.closest('.face-upload-container'), $input = $field.find('input[type="file"]');
$input.val(null).trigger('change');
});
/*
// display "required" message on form submit
$('#AddToCart').unbind();
$('#AddToCart').off();
$('#AddToCart').prop("onclick", null).off();
$form = $('form[action="/cart/add"]');
$form.off();
$form.find(":submit").prop("onclick", null).off();
*/
$('#AddToCart').on('click submit', function(e) {
const number = parseInt($facesSelector.val());
const button = $(this);
let can_submit = true;
for(let i = 0, max = $facesUploadFields.length; i < max; i++) {
const $field = $facesUploadFields.eq(i), $input = $field.find('input[type="file"]');
if (i < number && !$input[0].files.length) {
$field.addClass('required');
can_submit = false;
}
if($facesUploadFields.eq(i).hasClass("empty") && $facesUploadFields.eq(i).css('display') != 'none')
can_submit=false;
if (i >= number) {
$input.val(null);
}
}
if(!$('#type-dogs-name').val()){
$('#type-dogs-name').before('<span class="error">This field is required</span>');
$('.error').removeClass('hide');
$('#type-dogs-name').addClass('required');
can_submit=false;
}
if(can_submit===false) {
button.off();
e.preventDefault();
e.stopPropagation();
button.addClass('disabled');
//button.css({ opacity: 0.5 });
//button.attr('disabled','disabled');
$('#AddToCartForm').off();
}
else {
button.on();
e.preventDefault();
e.stopPropagation();
button.removeClass('disabled');
button.css({ opacity: 0.5 });
button.removeAttr('disabled');
$('#AddToCartForm').on();
$('#AddToCartForm').submit();
}
});
$("#type-dogs-name").click(function(){
if($('.empty.show').length===0 && $('#type-dogs-name').val().length){
console.log('radi');
$('#AddToCart').removeAttr('disabled');
$('#AddToCart').css({ opacity: 1 });
}
$('.error').addClass('hide');
$("#type-dogs-name").removeClass('required');
});
/*$("#type-dogs-name").change(function(){
if($('.empty.show').length===0 && $('#type-dogs-name').val().length){
console.log('radi');
$('#AddToCart').removeAttr('disabled');
$('#AddToCart').css({ opacity: 1 });
}
});*/
}
});
I've been working on it a bit long so you'll see some things commented which I was trying to implement the best solution.
The website is here: https://pawdie.com/products/custom-dog-doormat
It is run on Shopify. So I'm trying to make some validations to the form. If you try submitting the form (Add To Cart button) and you haven't inserted all the pictures and the name in the text field you will not be able to submit but instead it will show you an error. Which is how it was supposed to work. But when I try and submit the form again without still adding all the needed things(pictures and text in the input field) it will submit and not show the error.
So my guess is: It's somehow passing the validation function which I'm not sure why is happening. If someone could help I would be really grateful. Thanks!

Warn user before leaving web page if changes haven't been saved

When searching for a way to warn a user before leaving web page if changes haven't been saved, I found this solution: https://stackoverflow.com/a/48238659/9512437, but the warning pops up even if the user is hitting the save button. I tried adding an event when the user clicks the submit button to set a variable to keep the warning from appearing, but now the warning never appears.
Here is what I tried:
<script>
"use strict";
var btn_click = false;
(() => {
const modified_inputs = new Set;
const defaultValue = "defaultValue";
// store default values
addEventListener("beforeinput", (evt) => {
const target = evt.target;
if (!(defaultValue in target || defaultValue in target.dataset)) {
target.dataset[defaultValue] = ("" + (target.value || target.textContent)).trim();
}
});
// detect input modifications
addEventListener("input", (evt) => {
const target = evt.target;
let original;
if (defaultValue in target) {
original = target[defaultValue];
} else {
original = target.dataset[defaultValue];
}
if (original !== ("" + (target.value || target.textContent)).trim()) {
if (!modified_inputs.has(target)) {
modified_inputs.add(target);
}
} else if (modified_inputs.has(target)) {
modified_inputs.delete(target);
}
});
addEventListener("beforeunload", (evt) => {
if (modified_inputs.size && !btn_click) {
const unsaved_changes_warning = "Changes you made may not be saved.";
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
}
});
addEventListener("")
})();
document.getElementById("submit").onclick = function save() {
btn_click = true;
}
</script>
Any idea what I did wrong?
Turns out I was doing a couple things wrong. My guess is adding the document.getElementById("submit").onclick under "use strict" either caused an error (https://www.w3schools.com/js/js_strict.asp) or caused a problem with the detection since simply adding the function even without the && !btn_click caused it to not work. I also had to change if (modified_inputs.size && !btn_click) { to if (modified_inputs.size >> 0 && !btn_click) {.
In the end, the solution that ended up working for me is as follows:
<script>
var btn_click = false;
function save() {
btn_click = true;
}
"use strict";
(() => {
const modified_inputs = new Set;
const defaultValue = "defaultValue";
// store default values
addEventListener("beforeinput", (evt) => {
const target = evt.target;
if (!(defaultValue in target || defaultValue in target.dataset)) {
target.dataset[defaultValue] = ("" + (target.value || target.textContent)).trim();
}
});
// detect input modifications
addEventListener("input", (evt) => {
const target = evt.target;
let original;
if (defaultValue in target) {
original = target[defaultValue];
} else {
original = target.dataset[defaultValue];
}
if (original !== ("" + (target.value || target.textContent)).trim()) {
if (!modified_inputs.has(target)) {
modified_inputs.add(target);
}
} else if (modified_inputs.has(target)) {
modified_inputs.delete(target);
}
});
addEventListener("beforeunload", (evt) => {
if (modified_inputs.size >> 0 && !btn_click) {
const unsaved_changes_warning = "Changes you made may not be saved.";
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
}
});
addEventListener("")
})();
</script>
Then add your onclick to the element:
<button type="submit" class="w3-button w3-right w3-theme" id="button" onclick="save()">Save</button>

HTML button that's submitting an empty field even though it shouldn't be

Here's the HTML button I'm working with:
<b>Other: </b><input type="number" id="AmntValue" data-target-element-id="SubmitAmnt" data-target-parameter="Amnt" onchange="setValueOnTarget(this);' +/* ' enableButton(SubmitAmnt);' */+ '">
<button class="button2" id="SubmitAmnt" type="button" data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount=" onclick="disableButton(this); addValueToQueryString(this); redirectPage(this);">Continue To Payment</button>
When someone hits the button but the "Other" text field is blank, it's supposed to not redirect and instead show an error message. Right now the error message displays, but only for a quick moment before it redirects anyway.
Here is my complete JavaScript code:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem)
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
function displaySuccess(message) {
var userMessage = document.getElementById('userMessage1');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'green';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
I'm not sure if something's wrong with the code I put in the button or in the JavaScript.
Disable button by default
The button should be disabled by default, and should only be enabled when the expected input value is detected. It appears you already have a mechanism for this in your example, but you have some impediments to overcome first:
button should be disabled by default. Do this in the HTML:<button disabled …>Continue To Payment</button>
input's onchange handler should just call setValueOnTarget(), because this function already calls EnableButton(). In the HTML:<input onchange="setValueOnTarget(this);" … >
Remove the call to redirectPage() from the button's onclick handler and move it into addValueToQueryString() after you have assigned a value to newSrc.
Add a call to EnableButton() after you call displayError() in cases where you want to allow the user to modify the input and try again.
For example:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
console.log(targetElem);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem);
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
redirectPage(elem);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
EnableButton(elem);
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
<b>Other: </b>
<input
type="number"
id="AmntValue"
data-target-element-id="SubmitAmnt"
data-target-parameter="Amnt"
onchange="setValueOnTarget(this);">
<button
disabled
class="button2"
id="SubmitAmnt"
type="button"
data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount="
onclick="disableButton(this); addValueToQueryString(this);">Continue To Payment</button>
<div id="userMessage"></div>

integrating two javascripts codes into one code to show alerts

In my first javascript i am showing alerts if any text box having class check is left empty before submitting, if all are filled then in second javascript i am showing an alert that confirm submit?. But how to make these two as one javascript code?
<script type="text/javascript">
jQuery('input.test').not('[value]').each(function() {
var blankInput = jQuery(this);
//do what you want with your input
});
function confirmation(domForm) {
var jForm = jQuery(domForm);
var jFields = jForm.find('.check');;
var values = jFields.serializeArray();
var failedFields = [];
for(var i = 0; i < values.length; i++) {
var o = values[i];
if(o.value == null || o.value.length == 0) {
failedFields.push(jFields.filter('[name=' + o.name + ']').attr('title'));
}
}
if(failedFields.length > 0) {
var message = '';
if(failedFields.length == values.length) {
message = 'fill all fields please';
}
else {
message = 'please fill the fields:';
for(var i = 0; i < failedFields.length; i++) {
message += "\n";
message += failedFields[i];
}
}
csscody.alert(message);
return false;
}
var answer = confirm("Confirm save?")
if (answer){
window.location = "confirmsubmit.jsp";
}
else{
return false;
}
return true;
}
</script>
javascript to show confirm submit alert after text boxes having class check are filled
<script type="text/javascript">
$().ready(function() {
$('#btn_submit').click(function(e) {
e.preventDefault();
var that = this;
var text = "Confirm save?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
window.location = "confirmsubmit.jsp";
}
else {
return false;
}
}
})
});
});
</script>
html
<form action="confirmsubmit.jsp" onsubmit="return confirmation(this)" method="POST">
<input type="text" class="check"/>//alert if text box is left empty
<input type="submit" id="btn_submit"/>
</form>
I don't get why you need the second script. You call the validator function onsubmit. Why do change the window.location when you have set the same action? There is not point in binding the same function the the click-event of the button.
You don't need the second script, but have to change the first script.
function confirmation(domForm) {
// Your other code
// ...
if(failedFields.length > 0) {
// Your other code
// ...
csscody.alert(message);
return false;
}
// Your other code
// ...
/* Solution before your comment:
var answer = confirm("Confirm save?")
// This is already the action-target: window.location = "confirmsubmit.jsp";
return answer;
*/
var text = "Confirm save?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
// Probably doesn't work because this seems to be asynchronous?
return true;
}
else {
return false;
}
}
});
}

Replace/Recreate Input Element and Update PrototypeJS Focus/Blur Functions

I have functions on blur and on focus that change a password text field to change from text to password type. What happens is that we deleted and recreate it, but the prototype functions don't work afterwards. The code is as follows:
function focusPass(inputel,inputval) {
if(inputel.value == inputval) {
var newInput = document.createElement('input');
newInput.setAttribute('type','password');
newInput.setAttribute('name',inputel.getAttribute('name'));
newInput.setAttribute('id',inputel.getAttribute('id'));
inputel.parentNode.replaceChild(newInput,inputel);
setTimeout(function() { newInput.focus(); }, 10);
}
}
function blurPass(inputel,inputval) {
if(inputel.value == '') {
var newInput = document.createElement('input');
newInput.setAttribute('type','text');
newInput.setAttribute('name',inputel.getAttribute('name'));
newInput.setAttribute('id',inputel.getAttribute('id'));
newInput.value = inputval;
inputel.parentNode.replaceChild(newInput,inputel);
}
}
if ($('j_password') != undefined) {
blurPass($('j_password'),'password');
$('j_password').observe('blur', function(e) {
blurPass(this,'password');
});
$('j_password').observe('focus', function(e) {
focusPass(this,'password');
});
}
I tried doing something like:
document.observe('blur', function(e, el) {
if (el = e.findElement('#j_password')) {
blurPass(this,'password');
}
});
document.observe('focus', function(e, el) {
if (el = e.findElement('#j_password')) {
focusPass(this,'password');
}
});
but that doesn't seem to do anything. Can someone tell me how I would keep this function working? I would prefer not to have to set an attribute for onblur and onfocus, but if it's not possible, will revert to that.
Thanks.
What I ended up doing was:
function focusPass(inputel,inputval) {
if(inputel.value == inputval) {
var ie = getIEVersion();
if (ie > -1 && ie < 9) {
var newInput = document.createElement('input');
newInput.setAttribute('type','password');
newInput.setAttribute('name',inputel.getAttribute('name'));
newInput.setAttribute('id',inputel.getAttribute('id'));
new Insertion.After(inputel, newInput);
inputel.remove();
setTimeout(function() { newInput.focus(); }, 10);
} else {
inputel.setAttribute('type','password');
inputel.value = "";
inputel.focus();
}
}
}
function blurPass(inputel,inputval) {
if(inputel.value == '') {
var ie = getIEVersion();
if (ie > -1 && ie < 9) {
var newInput = document.createElement('input');
newInput.setAttribute('type','text');
newInput.setAttribute('name',inputel.getAttribute('name'));
newInput.setAttribute('id',inputel.getAttribute('id'));
newInput.value = inputval;
new Insertion.After(inputel, newInput);
inputel.remove();
} else {
inputel.setAttribute('type','text');
inputel.value = inputval;
}
}
}
It doesn't fix the IE7 and IE8 issues, but at least it works on all other major browsers as they support changing the input type.

Categories

Resources