jQuery addClass doesnt work in IE 7 or IE 8 - javascript

This is a validation script
This code runs when the user presses the submit button on a form
It loops thru all mandatory fields (entered in an array) and...
1. checks if the element is hidden
2. if not is it empty?
3. if not is it false? (I use false as a value for non selectable options)
And all this sets a variable to true or false.
// when submitting the registration form
function mandatoryCheck() {
jQuery('.tx-powermail-pi1_formwrap_1723 form.tx_powermail_pi1_form').submit(function(event) {
var success = false;
var element;
jQuery.each(mandatoryFields, function(index, value) {
element = jQuery('#powermaildiv_uid'+value+' input, #powermaildiv_uid'+value+' select')
element.each(function() {
// add class required to all fields
jQuery(this).addClass('required');
// is the element hidden, return true
if(jQuery(this).hasClass('fieldHidden') == true || jQuery(this).is(':disabled')) {
success = true;
} else {
// is the input field empty, return false
if(jQuery(this).val().length === 0) {
success = false;
// is the input field not empty, return true
} else {
// is the input field false, return false
if(jQuery(this).val() == 'disabled') {
success = false;
} else {
success = true;
}
}
}
// For each element add/remove validation class
if(success == false) {
jQuery(this).addClass('validation-failed').removeClass('validation-passed');
} else {
jQuery(this).addClass('validation-passed').removeClass('validation-failed');
}
});
});
// if succes is false, show error message and return false
if(success == false) {
jQuery('#c1799').fadeIn().css('display', 'block');
event.preventDefault();
return false;
} else {
jQuery('#c1799').fadeOut();
}
});
}
It works in firefox, chrome ie9 but not ie 7 or 8.
IE7 or 8 adds classes to the elements all random.
It seems like if I validate a select element it passes but an input field fails
What can be wrong?
Edit:
Here is the page: http://asdf.patrikelfstrom.se/index.php?id=267
Enter 1234 if in the little form that shows up
JS: http://asdf.patrikelfstrom.se/typo3conf/ext/gc_fm/res/js/ShowAndHideFields.js
If you press submit (absenden) the field Türnummer should be green (as it is in chrome, firefox etc.) but in ie7/8 it is red.
If you click on Wähle... (The select box) and choose Wohnung the fields under it becomes enabled and if you press submit now Türnummershould be red since the element is visible and empty.
This seems to work but if you click on the select box again and choose einfamilienhaus.
The fields are disabled and should now be green when submitting but this is not the case in IE7/8.

I think you need to loop through element, as it will be a collection of objects, so you would do...
// is the element hidden, return true
element.each(function() {
if($(this).hasClass('fieldHidden') == true) {
...
})
Well, just to show the point, depends on your code what you need to actually change

Remove the (value="false") from your selects.

Related

Jquery - Identify if radio button value has not changed

Is it possible to identify if the value of radio button has not changed?
Currently I am trying to change the confirmation message of submit button on button changed, and do not want any message if the value has not changed. I have something like this now:
$('input[type="radio"]').change(function() {
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$("#submit_button").data("confirm", "foo");
} else if(selected == 'false') {
$('#fee').hide();
$("#submit_button").data("confirm", "bar");
}
This will change confirm message to foo if button selected is true, and bar if button selected is false. However, what if I want to return nothing (no message), if radio button by default is true, and selected is true?
You can start a variable outside the event:
var radioChanged = 0;
And, in your event increase it:
$(':radio').change(function() {
radioChanged += 1;
// your code ...
});
Then, later on:
if (radioChanged > 0) {
alert('Change function occurred ' + radioChanged + ' times.');
} else {
alert('Radio button not changed.');
}
As i understand your expected behaviour, check if any radio has no more its default checked value:
$('form').on('submit', function() {
var anyRadioChanged = !!$(this).find('input[type="radio"]').filter(function() {
return $(this).is(':checked') != this.defaultChecked;
}).length; // '!!' to get boolean but it doesn't really matter here
if(anyRadioChanged) {
// show message(???)
}
})
you can hide message element just adding display: none to it or use jquery hide method
$('#someElementId').hide();
or
$('#someElementId').css("display","none")

Preventing next tab if current tab have empty field

I have a form having few questions set, each displayed at a time (like a slide). I want to prevent next set if current set has an empty field. Below is my script that navigates through each questions set. Any help would be highly appreciated.
$(document).ready(function() {
var $questions = $('#questions .question');
var currentQuestion = $('#questions .question.active').index();
$('#next').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion++;
if (currentQuestion == $questions.length - 1) {
$('#next').css('display', 'none');
$('#submit').css('display', 'inline');
}else{
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
}
$('#back').css('display', 'inline');
$($questions[currentQuestion]).slideDown();
});
});
$('#back').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion--;
if (currentQuestion == 0) {
$('#back').css('display', 'none');
} else {
$('#back').css('display', 'inline');
}
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
$($questions[currentQuestion]).slideDown();
});
});
});
Here is my JSFiddle
I came across your question and decided to fork your fiddle.
You should make a function that checks your conditions before continuing on to the next tab.
In your case, the conditions would be: All fields must be filled
I've added this function that checks the active section and returns true / false, in order to continue.
function validateFormSection() {
var valid = true; //As long as it's true, we may continue
var section = $('.question.active'); //Find the active section
var inputs = section.find('input'); //Get all its inputs
inputs.each(function(index, el) {
if ( $(el).val() == "" ) {
valid = false;
}
});
return valid;
}
JSFiddle here
On the third page, the form would submit whether all fields are empty or not.
You can prevent this by hooking onto the submit function and checking for empty fields.
If they're empty, we use e.preventDefault(); to keep it from submitting.
If they're filled, we simply submit by doing $('form').submit();
$('form').submit( function (e) { //Hook into the submit event
var valid = validateFormSection(); //Check if our fields are filled
if ( valid ) { //They are filled?
$('form').submit(); //Very well, let's submit!
} else {
e.preventDefault(); //If not, prevent the (default) submit behaviour
}
});
The fiddle has been edited to reflect these changes.
You could use if(!$('.question').eq(currentQuestion).find('input').filter(function(){return this.value==""}).length) to check if there are empty fields. Fiddle: http://jsfiddle.net/ilpo/cuqerfxr/1/
$('.question') selects all the questions
.eq(currentQuestion) selects the question you're currently at
.find('input') selects all the input fields inside the current question
.filter(function(){return this.value==""}) selects only empty input fields
.length counts the amount of matches, e.g. amount of empty inputs
if(number) returns true with a positive value, e.g. if there were any empty inputs
! in front of it all inverts it, returning true if there are no empty fields

Why is on form submit default value deleted?

I am using jQuery validation plugin, and after I added focus() and blur()event handlers to delete and set pre populated value,if I try to submit form without changing default value, value is replaced with empty string, where desired is to leave value untouched and run validate().
JS code is as follows:
$.validator.addMethod("mobileHR", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^\+[0-9]{1,3}\.[0-9]{1,14}$/);
}, "Unesite broj u fromatu: +385.111234567");
$(document).ready(function () {
// append help block below input
$('.controls').append('<span id="helpBlock" class="help-block">Format broja: +385.11123456789</span>');
// clear pre populated value on focus
var value = $("input[name='contactdetails[Registrant][Phone]']").val();
$("input[name='contactdetails[Registrant][Phone]']").focus(function() {
if ($(this).val() == value)
{
$(this).val("");
}
}).blur(function(event) {
if($(this).val() == "")
{
$(this).val(value);
}
});
// initialize validation
$('.form-horizontal').validate({
// set immediate validation, on event code 9
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
},
rules: {
"contactdetails[Registrant][Phone]": {
required: true,
mobileHR: true
}
},
messages: {
"contactdetails[Registrant][Phone]": {
required: "Molimo unesite broj telefona"
}
}
});
// check if form is valid then enable submit button
$('.form-horizontal input').on('keyup blur', function () {
if ($('.form-horizontal').valid()) {
$('.btn-primary').removeClass('btn-disabled');
} else {
$('.btn-primary').addClass('btn-disabled');
}
});
//do we valid form on document.ready?
//$('.form-horizontal').valid();
});
Fiddle is here.
After little research, I've found why is value changing on form submit:
$("input[name='contactdetails[Registrant][Phone]']").focus(function() {...});
After form is submitted, validate() is run, and as field is empty, input field is focused, so focus() is triggered again, and value of input field is "".
Changing event to click input field get focused, but value is untouched, as now function is fired on click event.

On click check if there are elements in a form which are with display none

I have a form in which I have hidden some inputs when a button is clicked. I have a validation code, which runs through every input and prints an error message if there are empty inputs. But in order to submit the form I have to fill every element, including the invisible ones, because the code is printing the message although I have filled all visible elements.
Here is the code for the validation
$('button.submit-first').click(function() {
var emptyElements = $('form.registration-form div.first-part :input').filter( function() {
return this.value === '';
});
if (emptyElements.length === 0)
{
$('p.red').css('display', 'none');
}
else
{
$('p.red').css('display', 'block');
$('html, body').animate({scrollTop: $('div.row').offset().top}, 800);
}
});
I can't seem to figure out how should I go through the inputs and if there are invisible ones just skip them and check the visible ones.
You can just add ":visible" to the input to only validate those.
$('button.submit-first').click(function() {
var emptyElements = $('form.registration-form div.first-part :input:visible').filter( function() {
return this.value === '';
});

JQuery Validation Problem

I doing a field validation using jquery to check if it is empty. If it is I want to display a message and then refocus on the field so the user can enter some data. Code:
$('#fieldId').blur(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
$(this).focus();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
It sort of works but it moves the cursor to the next field and not the one I refocused on.
You can try this:
$('#fieldId').blur(function(evt) {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
this.focus();
evt.preventDefault();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
However that may not completely solve the problem, as some browsers might be confused. As an alternative, wrap your "focus" call up as a timeout and run it after the current event finishes:
var self = this;
setTimeout(function() { self.focus(); }, 1);
It's kind-of a hack but it should also work.
edit — #Gus is right about which "focus()" to call
The blur event is triggered during a focus change (as the control you are validating loses focus). This could cause weird behaviour if you try to alter the focus while it is already changing. Instead of blur, try attaching the validation to the change event.
Also, there's no need to call the jQuery version of focus: $(this).focus(), you can just call this.focus().
$('#fieldId').change(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId').text('You must enter a value in this field').show();
this.focus();
} else {
if ($(this).is('.error')) {
$(this).removeClass('error');
$('#errorDivId').hide()
}
}
});

Categories

Resources