js/jquery - event.preventdefault doesn't seem to work in firefox - javascript

I have some code which was written by someone else, which is supposed to open a popup if a zipcode is not in the correct format and stop the page from being submitted. It works correctly in IE and chrome. But in firefox i get the popup, click ok, and then the page submits. Can someone look over the code and let me know what's being done incorrectly? Code pasted at the end of this message.
Thank you
<script type="text/javascript">
$(init);
function init() {
$('form').validate({
error_messages: {
},
failure: function (errors) {
//alert(errors);
$(".errMsg").show();
return false;
},
success: function () {
//alert('passed');
//return true;
}
});
$('#<%= btnAdd.ClientID %>').click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
}
function clearText(mybox, mymsg) {
if (document.forms['form1'].elements[mybox].value == mymsg) {
document.forms['form1'].elements[mybox].value = '';
document.forms['form1'].elements[mybox].style.color = '#000000';
}
}
function resetText(mybox, mymsg) {
if (document.forms['form1'].elements[mybox].value == '') {
document.forms['form1'].elements[mybox].value = mymsg;
document.forms['form1'].elements[mybox].style.color = '#C0C0C0';
}
}
function beginZipValidation() {
//alert('begin validation');
var zip = $('#<%= Zip.ClientID %>').val().replace(/ /g, '').toUpperCase();
var cID = $("#<%= ddlCountry.ClientID %> option:selected").val();
if (!zipCodeValidation(true, cID, zip)) {
return false;
}
//alert('true');
return true;
}
function zipCodeValidation(shouldValidateEmpty, countryID, zc) {
//alert('zipCodeValidation');
if (zc == '' || zc == 'POSTALCODE') {
if (!shouldValidateEmpty) {
return true;
}
}
else {
switch (countryID) {
case '226':
if (/^\d{5}(-\d{4})?$/.test(zc))
return true;
break;
case '38':
if (/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\ ?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/.test(zc))
return true;
break;
case '225':
if (/^(GIR 0AA|[A-PR-UWYZ]([0-9][0-9A-HJKPS-UW]?|[A-HK-Y][0-9][0-9ABEHMNPRV-Y]?)[0-9][ABD-HJLNP-UW-Z]{2})$/.test(zc))
return true;
break;
case '13':
if (/^(((2|8|9)\d{2})|((02|08|09)\d{2})|([1-9]\d{3}))$/.test(zc))
return true;
break;
}
}
alert('The postal code provided does not fit the format for the selected country. Please adjust and try again.');
if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }
event.preventDefault();
return false;
}

It might be as simple as the selector being wrong:
Try changing this:
$('#<%= btnAdd.ClientID %>').click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
Instead be a bit more verbose like:
var myButtonId = "<%= btnAdd.ClientID %>"; // Now you know what this evaluates to client-side
var btnSelector = "#" + myButtonId;
$(btnSelector).click(function (event) {
if (beginZipValidation()) {
//event.preventDefault();
return;
}
});
Are you using the standard tools like Firebug or Chrome Developer tools to debug? If so, throw a few console.log("myButtonId: " + myButtonId); statements in there!

Related

HTML Function Edit

The function I have only responded to a button click but not the image click. Can anyone tell me what would I need to modify in the function so that it responds to both button & image clicks?
function clickMe(a,b) {
$("#q"+b+" input[type='button']").click(function(event) {
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(b !== $(".qc").length) {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250);
});
} else {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250, function() {
loading(0);
});
});
}
});
}
You are probably expecting this $("#q"+b+" input[type='button'], #q"+b+" input[type='image']")
function clickMe(a,b) {
$("#q"+b+" input[type='button'], #q"+b+" input[type='image']").click(function(event) {
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(b !== $(".qc").length) {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250);
});
} else {
$("h1").html(a);
$("#q"+b).hide(250, function() {
$("#q"+b).next().fadeIn(250, function() {
loading(0);
});
});
}
});
}
I hope this solves your problem. If not then no worries :) just update/add your html in the test case bellow:
https://codebrace.com/editor/b02f036fa

DOM not being manipulated from inside a function that is being triggered properly

I have written this function to validate that all form fields and check boxes in a form are filled out. The script automatically disables the submit button and then watches for the moment at which it can be re-enabled. My debugger statements are landing me in all of the proper places, but for some reason, the DOM element is not being updated. I'm sure I am just making a stupid mistake, but can't seem to find a solution. Thank you in advance for any help!
Specifically looking at this section:
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
Here is the whole script below.
$(document).ready(function() {
validateInput();
$('.validate').keyup(function(event){
validateInput();
});
$('[type=checkbox]').click(function(event){
validateInput();
});
function validateInput() {
var valid = 0;
var checkBox = $('[type=checkbox]');
var inputFields = $('input.validate');
var inputLength = inputFields.length + checkBox.length;
inputFields.each(function() {
if($(this).val() !== '') {
valid++ ;
}
});
checkBox.each(function() {
if($(this).prop('checked')) {
valid++ ;
}
});
if(valid === inputLength) {
updateBtnStatus('enable')
} else {
updateBtnStatus('disable')
}
}
function updateBtnStatus(status) {
var btn = $('input[type="submit"]');
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
}
});

How to add favourite during on click jQUERY

I have a word as a custom "Add to Favorites" button. Clicking on the word link should add the website's URL to the user browser's favorites (bookmarks). This should work for all browsers, IE7+, FF, Opera, Chrome. As my code is working but i think i lack of something, it doesn't when clicked it will auto bookmarks instead of clicking the dialog alert. Kindly advise
Here my code :
$(function(){
function AddFavorite(sURL, sTitle)
{
try
{
window.external.addFavorite(sURL, sTitle);
}
catch (e)
{
try
{
window.sidebar.addPanel(sTitle, sURL, "");
}
catch (e)
{
alert("请使用Ctrl+D进行添加");
}
}
}
$('div.link_r').find('a').on('click',function(){
AddFavorite(location.herf,'新蔡');
return false;
});
HTML :
<div class="link_r">
收藏此页面,开奖即时查看
</div>
$(function() {
function AddFavorite(sURL, sTitle) {
if (/firefox/i.test(navigator.userAgent)) {
return false; //firefox work with attr "rel=sidebar"
} else if (window.external && window.external.addFavorite) {
window.external.addFavorite(sURL, sTitle);
return true;
} else if (window.sidebar && window.sidebar.addPanel) {
window.sidebar.addPanel(sTitle, sURL, "");
return true;
} else {
var touch = (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL');
alert('Press ' + touch + ' + D to bookmark this page.');
return false;
}
}
$("div.link_r a").attr("rel", "sidebar").click(function() {
return !AddFavorite(window.location.href, $(this).attr("title"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link_r">
收藏此页面,开奖即时查看
</div>
See : How do I add an "Add to Favorites" button or link on my website?
This works on some browsers :
$('#bookmark_me').click(function(e){
e.preventDefault();
var bookmarkURL = this.href;
var bookmarkTitle = this.title;
try {
if (window.sidebar) { // moz
window.sidebar.addPanel(bookmarkTitle, bookmarkURL, "");
} else if (window.external || document.all) { // ie
window.external.AddFavorite(bookmarkURL, bookmarkTitle);
} else if (window.opera) { // duh
$('a#bookmark').attr('href',bookmarkURL);
$('a#bookmark').attr('title',bookmarkTitle);
$('a#bookmark').attr('rel','sidebar');
}
} catch (err) { // catch all incl webkit
alert('Sorry. Your browser does not support this bookmark action. Please bookmark this page manually.');
}
});
DEMO

jquery checking select input if changed with condition

i have this code below when the select changes it works great and check for the correct condition but then for the second time if i change the select both conditions run after each other
$('#x_Statususer').on('change', function () {
var chng = !this.options[this.selectedIndex].defaultSelected;
if (chng) {
alert("has changed");
var celm=$( this ).val();
if (celm== "Revision") {
$("#btnAction").click(function() {
var r = confirm("Are you sure you want to set to Revision! ");
if (r == false) {
return false;
}
});
}
else if (celm == "Canceled") {
$("#btnAction").click(function() {
var r = confirm("Are you sure you want to set to Cancel! ");
if (r == false) {
return false;
}
});
}
} else {}
});
The problem is that you rebind the click event to #btnAction at each change. Try to change:
$("#btnAction").click(function() {...});
To:
$("#btnAction").one(function() {...});

How can I combine two functions properly on submit

I am new to jQuery and I have the following lines of jQuery. My intention is 'on submit' to check if the input text values are filled and check to see if the radio buttons are checked or selected and make the text red if they aren't but i am not sure on how to combine the two.
Right now it is kind of buggy because it submits IF the text is filled and it ignores the radio buttons BUT it makes the text red before it submits. so it is working just not how I would like it to.
jQuery
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
}
});
Call e.preventDefault() to prevent the normal form submission.
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
e.preventDefault();
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
e.preventDefault();
}
});
I like to separate my validations into single units and combine them at the end. It makes it easier to read, maintain and test.
$('#form3096').submit(function (e) {
var isFieldPopulated, isRadioChecked;
isFieldPopulated = $('#check-sm input:text').filter(function () {
return $.trim(this.value) !== "";
}).length > 0;
if (!isFieldPopulated) {
$('.social-heading').css('color','red');
}
isRadioChecked = $('input:radio', this).is(':checked');
if (!isRadioChecked) {
$('.radio-options').css('color','red');
}
return isFieldPopulated && isRadioChecked;
});
you can try this
$('#form3096').submit(function (e) {
var len = $('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length;
if (!len) {
$('.social-heading').css('color','red');
e.preventDefault();
}
if(!$('input:radio', this).is(':checked')){
$('.radio-options').css('color','red');
e.preventDefault();
}
});
$('#form3096').submit(function (e) {
if (!$.trim($('#check-sm input:text').val()) {
$('.social-heading').css('color','red');
return false;
}
if ($('input:radio', this).is(':checked')) {
// everything's fine...
return true;
} else {
$('.radio-options').css('color','red');
return false;
}
});

Categories