Javascript form validation submit function is being called only once - javascript

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!

Related

After first click of radio button can not fire change event

My jquery change event of radio button not working after first click and does not give any error please help me. i stuck in this from last week.and also cant count proper value because of this problem.
$('input[name="emailing"]').change(function()
{
checkValue();
});
function checkValue(evt) {
alert('hi');
var package = $("#package_value").val();
var emailing = $('input[name="emailing"]:checked').val();
$('input[name="emailing"]').on("mousedown", function() {
var select = $('input[name="emailing"]:checked').val();
$("#selected").val(select);
}).on("mouseup", function() {
$('input[name="emailing"]').prop('checked', false);
$(this).prop('checked', true).checkboxradio("refresh");
});
var selected = $("#selected").val();
alert(selected);
var update = $("#update").val();
if(update != '')
{
var hiddenPackage = $("#hidden_pricing").val();
var hiddenRadion = $("#hidden_radio").val();
var totalValue = package - hiddenRadion;
if(emailing == 1)
{
$("#package_value").val('');
var value = Number(totalValue) + 38;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 2)
{
$("#package_value").val('');
var value = Number(totalValue) + 55;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 0)
{
$("#package_value").val('');
var value = Number(totalValue) + 0;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
}
}
You should use delegate
$(document).delegate( "input[name='emailing']", "change", function() {
checkValue();
});
Use on() function with any element id instead of (document)
$(document).on('change', 'input[name="emailing"]', function() {
checkValue();
});

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

jquery click send function wont work only update the same field

I am trying to make a click send function for my emoticon function but it is not working correctly.
I have created this demo from jsfiddle. In this demo you can se there are four textarea and smiley. When you click smiley then other alert (comments will be come here) changing to (Plese write your comment). What is the problem on there and what is the solution anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function () {
$('body').on("click", '.emo', function () {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function (event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if (msg == '') {
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
});
HTML
At 43 line $('.sendcomment').trigger(e); you trigger keydown event to all textareas. Change it to theComment.trigger(e)

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;
}
}
});
}

JQuery placeholder HTML5 simulator

I have been using the HTML 5 placeholder and just realised that it does not work outside HTML5 devices. As you can see by the code below the placeholder is always in lowercase and the value is always in upper case.
#maphead input::-webkit-input-placeholder {
text-transform:lowercase;
}
#maphead input:-moz-placeholder {
text-transform:lowercase;
}
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" style="text-transform:uppercase;" class="capital"/>
This is all fine except when dealing with non HTML 5 devices. For this I have employed a bastardised bit of javascript.
function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("type") == "text") {
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0 || value == placeholder) {
inputs[i].value = placeholder;
inputs[i].onclick = function() {
if (this.value == this.getAttribute("placeholder")) {
this.value = "";
}
return false;
}
inputs[i].onblur = function() {
if (this.value.length < 1) {
this.value = this.getAttribute("placeholder");
$('.capital').each(function() {
var current = $(this).val();
var place = $(this).attr('placeholder');
if (current == place) {
$(this).css('text-transform','lowercase')
}
});
}
}
}
}
}
}
window.onload = function() {
activatePlaceholders();
}
Firstly this Javascript is rancid. There must be an easier JQuery way. Now although this above does work (reasonably) it does not respond to keeping the placeholder in lowercase and the value in uppercase since it sets the value with the placeholder.
I've set you all up with a nice Fiddle http://jsfiddle.net/Z9YLZ/1/
Try something like this:
$(function() {
$('input[type="text"]').each(function () {
$(this).focus(function () {
if ($(this).attr('value') === $(this).attr('placeholder')) {
$(this).css('text-transform','lowercase');
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).attr('value') === '') {
$(this).css('text-transform','uppercase');
$(this).attr('value', $(this).attr('placeholder'));
}
}).blur();
});
});
Edit: Explicitly declare the text-transform to cascade properly.
Try this one, I'm using it for a while and it works perfectly:
(function($, undefined) {
var input = document.createElement('input');
if ('placeholder' in input) {
$.fn.hinttext = $.hinttext = $.noop;
$.hinttext.defaults = {};
delete input;
return;
}
delete input;
var boundTo = {},
expando = +new Date + Math.random() * 100000 << 1,
prefix = 'ht_',
dataName = 'hinttext';
$.fn.hinttext = function(options) {
if (options == 'refresh') {
return $(this).each(function() {
if ($(this).data(dataName) != null) {
focusout.call(this);
}
});
}
options = $.extend({}, $.hinttext.defaults, options);
if (!(options.inputClass in boundTo)) {
$('.' + options.inputClass)
.live('focusin click', function() {
$($(this).data(dataName)).hide();
})
.live('focusout', focusout);
boundTo[options.inputClass] = true;
}
return $(this).each(function(){
var input = $(this),
placeholder = input.attr('placeholder');
if (placeholder && input.data(dataName) === undefined) {
var input_id = input.attr('id'),
label_id = prefix + expando++;
if (!input_id) {
input.attr('id', input_id = prefix + expando++);
}
$('<label/>')
.hide()
.css('position', options.labelPosition)
.addClass(options.labelClass)
.text(placeholder)
.attr('for', input_id)
.attr('id', label_id)
.insertAfter(input);
input
.data(dataName, '#' + label_id)
.addClass(options.inputClass)
.change(function() {
focusout.call(this);
});
}
focusout.call(this);
});
};
$.hinttext = function(selector, options) {
if (typeof selector != 'string') {
options = selector;
selector = 'input[placeholder],textarea[placeholder]';
}
$(selector).hinttext(options);
return $;
};
$.hinttext.defaults = {
labelClass: 'placeholder',
inputClass: 'placeholder',
labelPosition: 'absolute'
};
function focusout() {
var input = $(this),
pos = input.position();
$(input.data(dataName)).css({
left: pos.left + 'px',
top: pos.top + 'px',
width: input.width() + 'px',
height: input.height() + 'px'
})
.text(input.attr('placeholder'))
[['show', 'hide'][!!input.val().length * 1]]();
}
$($.hinttext);
})(jQuery);
You just need to make sure to style label.placeholder with CSS to look the same as HTML5 placeholder text (color: #999)
Try this: http://jsfiddle.net/msm595/Z9YLZ/12/
Bit late but here's what I do. Store all the default values on page load and then clear value text ONLY when it's the default value that is clicked on. This prevents the JS clearing user entered text.
jQuery(document).ready(function($){
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
});

Categories

Resources