Jquery function not being called on Page unload - javascript

<input type="submit" name="Post" value="Post" class="btm-bg" />
<script type="text/javascript" src="../Scripts/jquery-1.9.0.min.js"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/mvcfoolproof.unobtrusive.min.js")" type="text/javascript"></script>
$(function () {
$('.option').hide();
$('input[class="Tproperty"]').click(function () {
$('.option').hide();
if ($(this).val() == '2' || $(this).val() == '8') {
$('#Display').show();
$('#residential').hide();
$('#amen').hide();
}
if ( $(this).val() == '5') {
$('#Display').show();
$('#residential').hide();
$('#amen').hide();
$('#xtrafac').hide();
$('#parkings').hide();
$('#rooms').hide();
$('#bathrooms').hide();
}
else {
$('#Display').show();
$('#residential').show();
$('#amen').show();
$('#xtrafac').show();
$('#parkings').show();
$('#rooms').show();
$('#bathrooms').show();
}
});
});
$('form').on('submit', function () {
alert("hello");
var sr = $("input[name = saleorrent]:checked").val();
alert(sr);
var mr = $("input[name = Monthlyrent]").val();
alert(sr + mr);
if (sr == "Rent" && mr == null ) {
alert("Enter monthly rent");
e.preventDefault();
}
});
$(function () {
$('.showes').hide();
$('input[class="saleorrent"]').click(function () {
$('.showes').hide();
if ($(this).val() == 'Sale') {
$('#optionsale').show();
$('#sale').show();
$('#rent').hide();
}
else {
$('#optionRent').show();
$('#sale').hide();
$('#rent').show();
}
});
});
function CheckNumeric(e) {
if (window.event) // IE
{
if ((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8) {
event.returnValue = false;
return false;
}
}
else { // Fire Fox
if ((e.which < 48 || e.which > 57) & e.which != 8) {
e.preventDefault();
return false;
}
}
}
$(function () {
$("#City").change(function () {
if ($("#City").val() != 0) {
var ddlCityId = $(this).val();
var subItems = "";
$.getJSON("#Url.Action("ddlCities", "Listings")", { id: ddlCityId },
function (data) {
$.each(data, function (index, item) {
subItems += "<option value='" + item.Locality_Id + "'>" + item.Locality + "</option>"
});
$("#Locality").html(subItems)
});
}
else {
alert("false");
}
});
});
I am using MVC 4.0 . I want an alert message if the field is left empty. But the thing is as soon as I click the submit button it reaches out to the server side and not executing the jquery code before unloading the page.

beforeunload fires after a form submission as the form submission can be cancelled. You need to stop the form submission instead. e.g. like:
$('form').on('submit', function () {
alert("hello");
var sr = $("input[name = saleorrent]:checked").val();
alert(sr);
var mr = $("input[name = Monthlyrent]").val();
alert(sr+ mr);
if (sr == 'Rent' && mr == " ")
{
alert("Enter monthly rent");
e.preventDefault(); // <<<<<< Stop the form submission
}
});
Notes:
Always use prop('checked') with checkboxes.
var sr = $("input[name=saleorrent]").prop('checked');

Related

Why can't get script to proceed to next page and stop reload after checkout click?

I am creating a script which takes a minimum of 16 characters in Address field and exactly 10 in the Phone field in Shopify checkout page.
My issue's - The entire page refresh's/load's after click & Even after validating all the fields i cant proceed to next page.
<script>
$(document).ready(function() {
$('#checkout_shipping_address_address1').attr("minlength",16);
$('#checkout_shipping_address_address1').attr("name",'addressOne');
$('#checkout_shipping_address_address1').attr("maxlength",200);
$('#checkout_shipping_address_address1').attr("required",'required');
$("form.edit_checkout.animate-floating-labels").validate(
{
messages: {
checkout_shipping_address_phone: "Please enter 10 digit phone number",
addressOne: "Enter an address of minimum 16 characters",
}
}
);
});
</script>
<script>
(function($) {
window.PhoneNumberInputFormatter=function(){return true;};
$(document).on('page:load page:change', function() {
if (Shopify.Checkout.step === 'contact_information') {
var $phoneField = $('[name="checkout[shipping_address][phone]"]:not([tabindex="-1"])');
phoneFormatValidated = true;
$phoneField.removeAttr('data-phone-formatter data-phone-formatter-country-select');
$phoneField.attr('maxlength', 10);
$phoneField.attr('minlength', 10);
$phoneField.attr('required', 'required');
$phoneField.attr('name', 'checkout_shipping_address_phone');
$phoneField.keypress(function(event){
if (event.which != 48 && (event.which < 47 || event.which > 59))
{
event.preventDefault();
if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
event.preventDefault();
}
}
});
function phoneNumberValidation() {
phoneFormatValidated = true;
var phoneFieldVal = $phoneField.val();
}
if ($phoneField.val() != "") { phoneNumberValidation() };
$phoneField.on('blur', phoneNumberValidation);
$('[data-step] form [type="submit"]').on('click', function(event) {
event.preventDefault();
phoneNumberValidation();
if (phoneFormatValidated) {
$('[data-step] form').trigger('submit');
}
});
$('[data-step] form').on('keypress', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
$('[data-step] form [type="submit"]').trigger('click');
}
});
}
});
})
(Checkout.$);
</script>
P.S - I am new to JS/JQuery.
Thank you.

Contact form Phone Number format Javascript

This piece of code lets me write a phone number to my contact form as (XXX) XXX-XXXX format. (working example is at https://www.fxmerkezi.com/ucretsiz-danismanlik/)
But I need it to be done like 0XXXXXXXXXX first character must be 0 and no letters or any other characters shouldt be allowed.
This is the code in my head tags;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/jquery-input-mask-phone-number#1.0.0/dist/jquery-input-mask-phone-number.js"></script>
<script>
$(document).ready(function () {
$('#yourphone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});
$('#yourphone2').usPhoneFormat();
});
</script>
And this is the file jquery-input-mask-phone-number.js:
(function ($) {
$.fn.usPhoneFormat = function (options) {
var params = $.extend({
format: 'xxx-xxx-xxxx',
international: false,
}, options);
if (params.format === 'xxx-xxx-xxxx') {
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 12);
$(this).val(inputValue);
}
});
$(this).on('keypress', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3) {
$(this).val(curval + "-");
} else if (curchr == 7) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '12');
});
} else if (params.format === '(xxx) xxx-xxxx') {
$(this).on('keypress', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3) {
$(this).val('(' + curval + ')' + " ");
} else if (curchr == 9) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '14');
});
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 14);
$(this).val(inputValue);
}
});
}
}
}(jQuery));
just simply define your textbox as below which will allow only 11 digits with starting 0.
$( document ).ready(function() {
$( "#number" ).keypress(function(e) {
if(this.value.length == 0 && e.which != 48){
return false
}
if(e.which < 48 || e.which > 57 || this.value.length > 10){
return false
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<input type="text" id="number" name="country_code" pattern="[0]{1}[0-9]{10}">
<input type="submit" value="ok">
</form>
You can write regex to match the format you want,
let regex = /[0]\d+/gi;
let match = regex.exec(e);
if(match && match.length == 11){
return true; // match found with 11 digits number starting with 0
}
else{
alert('invalid number'); // no match found
}

Why jQuery keyup is not working while I try to build keyboard shortcut on my website?

I'm trying to build keyboard shortcuts for accessibility in my website. For example, when user presses '1' I want to move him to the home. When user presses '2', to a different page.
I'm trying to use keyup for this but it's not working.
$(function() {
$(document).keyup(function(e) {
if (e.which == 1) {
console.log('1');
window.location.href = '/';
} else if (e.which == 2) {
window.location.href = '/escolas';
} else if (e.which == 3) {
window.location.href = '/noticias';
} else if (e.which == 4) {
window.location.href = '/eventos';
} else if (e.which == 5) {
window.location.href = '/contato';
}
});
});
Can someone help me? It's not logging 1 when I press '1'.
It is because the key code for '1' is not 1 but 49 (or 97 for the one on the numpad).
Check this to see your key code:
$(function() {
$(document).keyup(function(e) {
$('body').text(e.type + ' ' + e.which);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can get the key character by String.fromCharCode(event.which);, and then directly compare with actual character:
$(function() {
$(document).keyup(function(e) {
if (e.key) {
var key = e.key;
} else {
var key = String.fromCharCode(e.which || e.keyCode);
}
if (key == 1) {
console.log('1');
window.location.href = '/';
} else if (key == 2) {
window.location.href = '/escolas';
} else if (key == 3) {
window.location.href = '/noticias';
} else if (key == 4) {
window.location.href = '/eventos';
} else if (key == 5) {
window.location.href = '/contato';
}
});
});
You are using wrong keycodes. Refer this
$(function() {
$(document).keyup(function(e) {
if (e.which == 49) {
console.log('1');
window.location.href = '/';
} else if (e.which == 50) {
window.location.href = '/escolas';
} else if (e.which == 51) {
window.location.href = '/noticias';
} else if (e.which == 52) {
window.location.href = '/eventos';
} else if (e.which == 53) {
window.location.href = '/contato';
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
e.which gives you ASCII value. To convert ASCII into character use String.fromCharCode(e.which).
$(function () {
$(document).keyup(function (e) {
if (String.fromCharCode(e.which) == 1) {
window.location.href = '/';
} else if (String.fromCharCode(e.which) == 2) {
window.location.href = '/escolas';
} else if (String.fromCharCode(e.which) == 3) {
window.location.href = '/noticias';
} else if (String.fromCharCode(e.which) == 4) {
window.location.href = '/eventos';
} else if (String.fromCharCode(e.which) == 5) {
window.location.href = '/contato';
}
});
});
If you wanna go fancy:
$(document).ready(function() {
'use strict';
const addresses = [
{
codes: [49, 97],
path: '/'
},
{
codes: [50, 98],
path: '/escolas'
},
{
codes: [51, 99],
path: '/noticias'
},
{
codes: [52, 100],
path: '/eventos'
},
{
codes: [52, 101],
path: '/contato'
}
]
$(document).on("keyup", evt => {
const key = evt.which;
addresses.map(address => {
if(address.codes.filter(code => code === key).length)
window.location.href = address.path;
})
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Showing multiple validation alert on button click

I have written a Jquery code for validation. But the problem here is that, First the regular expression message fires and after that requiredField error message fires.
Here is my code:-
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTextBoxes();
function FunValidatePan()
if (ErrArr.length > 0)
{
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTextBoxes() {
if ($("#txtPanNo").val() === "") {
ErrArr.push('Pan No is required');
}
}
function FunValidatePan() {
var StrPriError = "";
if (Trim(document.getElementById("txtPanNo").value) != "" && Trim(document.getElementById("txtPanNo").value) != "NULL") {
var fil = /^[a-zA-Z0-9]+$/;
if (fil.test(document.getElementById("txtPanNo").value)) {
var abc = Trim(document.getElementById("txtPanNo").value);
if (abc.length != 10) {
StrPriError += ' Enter valid PAN Card\n';
}
}
else {
StrPriError += ' Enter valid PAN Card\n';
}
}
if (StrPriError != "") {
alert(StrPriError);
return false;
}
else {
return true;
}
}
I want that in single message. How to achieve that. Please suggest. Also I want that in Jquery
UPDATE
ASPX
<asp:TextBox ID="txtPanNo" runat="server" Width="100" MaxLength="10"></asp:TextBox>
Please check changes in the above code.
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTextBoxes();
FunValidatePan();
if (ErrArr.length > 0)
{
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTextBoxes() {
if ($("#txtPanNo").val() === "") {
ErrArr.push('Pan No is required');
}
}
function FunValidatePan() {
if (Trim(document.getElementById("txtPanNo").value) != "" && Trim(document.getElementById("txtPanNo").value) != "NULL") {
var fil = /^[a-zA-Z0-9]+$/;
if (fil.test(document.getElementById("txtPanNo").value)) {
var abc = Trim(document.getElementById("txtPanNo").value);
if (abc.length != 10) {
ErrArr.push('Enter valid PAN Card');
}
}
else {
ErrArr.push('Enter valid PAN Card');
}
}
}

Getting Textbox Cursor Position (Before or After text)

How do I check to see if the cursor position is in the front of the text or the last of the text.
<script type="text/javascript">
$(document).ready(function () {
$('input').keyup(function (e) {
if (e.which == 39 && <CURSOR IS FIRST OR LAST OF TEXT>) {
alert($('input').val);
$(this).closest('td').next().find('input').focus();
$(this).closest('td').next().find('input').select();
}
}
}
<script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input').keyup(function (e) {
if (e.which == 39 && <selected text lenght> > 0) {
$(this).closest('td').next().find('input').focus();
$(this).closest('td').next().find('input').select();
}
else if (e.which == 37) {
$(this).closest('td').prev().find('input').focus();
$(this).closest('td').prev().find('input').select();
}
else if (e.which == 40) {
$(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();
$(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').select();
}
else if (e.which == 38) {
$(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();
$(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').select();
}
});
});
You can use jQuery Caret plugin. Check this thread here and the plugin's homepage. You can then change your code to:
var pos= $(this).caret().start == $(this).caret().end ? $(this).caret().start : -1;
if (e.which === 39 && (pos === 0 || pos === $(this).val().length)) {
...
Hope it helped,
Shakib

Categories

Resources