On Change Event - javascript

I wish to populate the alert boxes and then would like to enable Submit Button if all conditions passed, the basic jquery code is here:
$("#expCurrencyState").on("change", function() {
var inputValue = document.getElementById('categoryItem').value;
var expenseStateValue = document.getElementById('expCurrencyState').value;
var expAmountValue = document.getElementById('expAmount').value;
var expDateValue = document.getElementById('expDate').value;
alert(inputValue);
alert(expAmountValue);
alert(expDateValue);
alert(expenseStateValue);
if (inputValue.length && expAmountValue.length && expDateValue.length !== 0) {
alert('passed');
$('#btnSubmit').prop('disabled', false);
$('#btnSubmit').addClass('btnActive');
}
});

The only problem i see is that you only check when the #expCurrencyState changes.
You should run that code on each of the required elements change event, and you should also disable the button and remove the class if not all conditions pass.
$("#expCurrencyState,#categoryItem,#expAmount,#expDate").on("change", function() {
var inputValue = document.getElementById('categoryItem').value;
var expenseStateValue = document.getElementById('expCurrencyState').value;
var expAmountValue = document.getElementById('expAmount').value;
var expDateValue = document.getElementById('expDate').value;
var validData = inputValue.length && expAmountValue.length && expDateValue.length && expenseStateValue.length;
if ( validData ) {
alert('passed');
}
$('#btnSubmit').prop('disabled', !validData);
$('#btnSubmit').toggleClass('btnActive', validData);
});

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!

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

insert a function inside an event jquery

i'm trying to insert a function inside this jquery event. This is the event
$(":checkbox").on('change', function() {
$.fn.myFunction();
})
and this is myFunction
$.fn.myFunction = function() {
alert('ciao');
if ($(this).is(':checked')) {
InputInserireInput = $(this).parent().parent().parent().find('.inserirePrezzoDiv');
$(this).closest('div').parent().parent().find('select').prop('value','0');
$(this).find('button').css('background-color','#c31432')
var checkbox = $(this);
InputInserireInput.removeClass('hidden');
var checkboxSelected = $(this).attr('id');
var nomeServizio = ($(this).next('label').text());
$(this).closest('div').parent().parent().find('.titoloPiega').css('color', 'black')
$(this).closest('div').parent().parent().find('button').css('margin-top', -50)
var titleLabel = $(this).closest('div');
var titleSelect = $(titleLabel).parent().parent().find('.titoloPiega');
var option1 = $(titleLabel).parent().parent().find('.option1');
var option2 = $(titleLabel).parent().parent().find('.option2');
var selectOption = ($(titleLabel).parent().parent().find('select'));
var selectOptionID = ($(titleLabel).parent().parent().find('select').attr('id'));
$(selectOption).on('change', function () {
var selectedOption = $(selectOption).prop('value');
if (selectedOption == 1 && checkbox.is(':checked')) {
InputInserireInput.addClass('hidden');
option2.addClass('hidden');
option1.removeClass('hidden');
}
if (selectedOption == 2 && checkbox.is(':checked')) {
InputInserireInput.addClass('hidden');
option1.removeClass('hidden');
option2.removeClass('hidden');
}
if (selectedOption == 0 && checkbox.is(':checked')) {
InputInserireInput.removeClass('hidden');
option1.addClass('hidden');
option2.addClass('hidden');
}
});
} else {
$('.inserirePrezzoDiv').addClass('hidden');
$(this).closest('div').parent().parent().find('.titoloPiega').css('color', '#a5a6a7');
$(this).closest('div').parent().parent().find('select').prop('value','0');
$(this).closest('div').parent().parent().find('.option1').addClass('hidden');
$(this).closest('div').parent().parent().find('.option2').addClass('hidden');
$('.bottoneCss6').css('margin-bottom', 0)
}
};
The first allert work but then all the if statement i thik doesn' match with the event declared before the function. Can anyone help me?
try by replacing :
$(":checkbox").on('change', function() {
$(this).myFunction()
})
you will pass the this (current checkbox) scope to myFunction

detect when 2 calendar values changed

I am making a financial report where user choose 2 dates search_date1 and search_date2, and then a monthly report is generated.
I created first a daily report with only one calendar and when it is changed I apply some AJAX script to it and it works correctly:
var myApp = {};
myApp.search_date = "";
document.getElementById('search_date').onchange = function (e) {
if (this.value != myApp.search_date) {
var d = $("#search_date").val();
$.ajax({
...
});
}
}
Now I can't know how to detect if both calendars are changed to apply AJAX script according to their values.
EDIT
Is it correct to do the following:
var myApp = {};
myApp.search_date1 = "";
myApp.search_date2 = "";
document.getElementById('search_date1').onchange = function (e) {
if (this.value != myApp.search_date1) {
var d1 = $("#search_date1").val();
document.getElementById('search_date2').onchange = function (e) {
if (this.value != myApp.search_date2) {
var d2 = $("#search_date2").val();
$.ajax({
...
})
}
});
}
});
try this:
var temp = {
from: null,
to: null
}
document.getElementById('from').onchange = function(e){
temp.from = e.target.value;
goAjax();
}
document.getElementById('to').onchange = function(e){
temp.to = e.target.value;
goAjax();
}
function goAjax(){
if(temp.from && temp.to && new Date(temp.from) < new Date(temp.to)){
//do ajax call
console.log('valid')
}
}
<input type="date" id='from'/>
<br>
<input type="date" id='to'/>
I would have captured the change event for both elements :
$("#search_date1, #search_date2").on('change',function(){
var d1 = $("#search_date1").val();
var d2 = $("#search_date2").val();
$.ajax({...});
});
What you do in your edit may work, but it would be better (and easier) do something like this
var myApp = {};
myApp.original_search_date1 = $("#search_date1").val();
myApp.original_search_date2 = $("#search_date2").val();
myApp.search_date1 = $("#search_date1").val();
myApp.search_date2 = $("#search_date2").val();
document.getElementById('search_date1').onchange = function (e) {
if ($("#search_date1").val() != myApp.search_date1) {
myApp.search_date1 = $("#search_date1").val();
sendAjax();
}
});
document.getElementById('search_date2').onchange = function (e) {
if ($("#search_date2").val() != myApp.search_date2) {
myApp.search_date2 = $("#search_date2").val();
sendAjax();
}
});
function sendAjax() {
if (myApp.original_search_date1 !== myApp.search_date1 &&
myApp.original_search_date2 !== myApp.search_date2) {
$.ajax({
...
});
}
}
Cant you just set a variable to check if its been changed with true/false then run the script if both variables are true.
Something like,
var searchOneToggled = false,
searchTwoToggled = false;
$('#search_date_one').on('input', function() {
searchOneToggled = true;
runYourFunction();
});
$('#search_date_two').on('input', function() {
searchTwoToggled = true;
runYourFunction();
});
function runYourFunction() {
if(searchOneToggled === true && searchTwoToggled === true) {
alert('hello world');
}
}

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