caiouechi / Studies

5 stars 1 forks source link

jQuery & javascript #205

Open caiouechi opened 2 years ago

caiouechi commented 2 years ago

ajax

           var googleAdsParametersIndex = window.location.href.indexOf("?")
            var originPath = window.location.href.substring(0, googleAdsParametersIndex);

            $.post(originPath + "/Home/RenderDonations",
                $('#annualReportForm').serialize(),
                function (data, status) {
                    $("#DonationsDynamic").html(data);
                });

add validation dynamically

    jQuery.validator.addMethod("datemustbeequalorgreaterthancurrentdate", function (value, element, param) {

        //var someDate = $("#emailSchedule").val();
        var someDate = value;

        var today;
        var currentDate = new Date();
        var year = currentDate.getFullYear();
        var month = currentDate.getMonth() + 1;  // added +1 because javascript counts month from 0
        var day = currentDate.getDay();
        var hours = currentDate.getHours();
        var minutes = currentDate.getMinutes();
        var seconds = currentDate.getSeconds();

        day = ("0" + new Date().getDate()).slice(-2);
        month = ("0" + (new Date().getMonth() + 1)).slice(-2);

        today = year +'-' + month + '-' + day+ 'T' + hours + ':' + minutes

        var someDateParsed = new Date(someDate + ':00')
        var todayParsed = new Date(today + ':00')

        if (someDateParsed < todayParsed) {
            return false;
        }
        return true;
    });

    jQuery.validator.unobtrusive.adapters.addBool("datemustbeequalorgreaterthancurrentdate");

//Must call the validate first
  $('#registerFormId').validate()
  $("input[id*=testInput]").rules("add", { required: true, datemustbeequalorgreaterthancurrentdate : true, messages : { required : 'field is required.', datemustbeequalorgreaterthancurrentdate: 'Select a future date' }});

comment counter

 function commentCounter() {

        var remaininigCharacters = 200 - $("#moreInfo").val().length;

        var characterWord = "characters";

        if (remaininigCharacters == 1) characterWord = "character";

        var counterLabel = "Remaining " + (remaininigCharacters + " " + characterWord);

        $("#spanCounter").text(counterLabel)

        if (remaininigCharacters == 0) $("#spanCounter").text("")
    }

back button disable

    <script type="text/javascript">
            //Disable Back Button In All Browsers.
            function DisableBackButtonAllBrowsers() {
                window.history.forward()
            };
            DisableBackButtonAllBrowsers();
            window.onload = DisableBackButtonAllBrowsers;
            window.onpageshow = function (evts) { if (evts.persisted) DisableBackButtonAllBrowsers(); };
            window.onunload = function () { void (0) };
    </script>

jQuery append option

$("#ddlDonorProvinceState").append($('<option>', {
                value: data.value,
                text: data.text
            }));

anchor without animation

var targetDiv = "#" + $("#hdnIsEditSection").val();

        setTimeout(function () {
            if (targetDiv == "#") return;
            const element = document.querySelector(targetDiv);
            const position = element.getBoundingClientRect();
            const x = position.left;
            const y = position.top;
            console.log(x, y)

            window.scrollTo({
                top: y,
                left: 0,
                behavior: 'instant',
            });
        }, 200);

jQuery validations

    $.validator.addMethod("greaterThan",
        function (value, element, params) {

            if (value == null || value == "" || (value.indexOf('2001') > 0)) return true;

            if (!/Invalid|NaN/.test(new Date(value))) {
                return new Date(value) > new Date($(params).val());
            }

            return isNaN(value) && isNaN($(params).val())
                || (Number(value) > Number($(params).val()));
        }, 'Must be greater than today.');
$(document).ready(function () {
    $('#formDetails').validate({
        errorClass: 'help-block animation-slideDown',
        errorElement: 'div',
        errorPlacement: function (error, e) {
            e.parents('.fed-form-group > div').append(error);
        },
        highlight: function (e) {
            $(e).closest('.fed-form-group').removeClass('has-success has-error').addClass('has-error');
            $(e).closest('.help-block').remove();
        },
        success: function (e) {
            e.closest('.fed-form-group').removeClass('has-success has-error');
            e.closest('.help-block').remove();
        }, rules: {
            //******************************Contact Info 
            'CON_Info.FullName': {
                required: true.
                    postal
            },
        },
        messages: {
            //****************************** Credit card  Info              ////
            'donationForm.creditCard.Number': {
                required: 'Please provide a creditCard',
                minlength: 'Your password must be at least 6 characters long'
            },
        }
    });
});

Add dynamic valid $("#txtSpecificDesignation").rules("add", "required"); Change the validation message $("#registerFormId").validate().settings.messages.SpecificDesignation.required = 'Please insert the Gift Designation'

jQuery curiosity

select[id$=MailProvince] > option

Formats: JSON: double quotations on keys Javascript object: quotations on keys

JSON

var jsonObject = JSON.parse(string)
var jsonString = JSON.stringfy(jsonObject)

jQuery CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

jQuery ready method

$(function() {
    console.log( "ready!" );
});

Loaded elements

          document.addEventListener("DOMContentLoaded", () => {
    alert("DOM ready!");
  });

How to rebind the validations after partial views being loaded

            $('#registerFormId').removeData('validator');
            $('#registerFormId').removeData('unobtrusiveValidation');
            $("#registerFormId").each(function () { $.data($(this)[0], 'validator', false); }); //enable to display the error messages
            $.validator.unobtrusive.parse("#registerFormId");

StreamWriter

If you want to valide on MVC, you need to turn off the HtmlHelper.UnobtrusiveJavaScriptEnabled = false;
It is by default set as true on the webconfig

$(document).ready(function () {

    if (1 == 1) {
        $('#registerFormId').validate({
            errorClass: 'help-block animation-slideDown', // You can change the animation class for a different entrance animation - check animations page
            errorElement: 'div',
            errorPlacement: function (error, e) {
                e.parents('.form-group > div').append(error);
            },
            highlight: function (e) {
                $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
                $(e).closest('.help-block').remove();
            },
            success: function (e) {
                e.closest('.form-group').removeClass('has-success has-error');
                e.closest('.help-block').remove();
            },
            rules: {
                'FirstName': {
                    required: true
                }
            },
            messages: {
                'FirstName': 'Test',
                'Password': {
                    'required': '',
                    'minlength': ''
                },
                'ConfirmPassword': {
                    required: 'Please provide a password',
                    minlength: 'Your password must be at least 6 characters long',
                    equalTo: 'Please enter the same password as above'
                }
            }
        });
    }
});

on submit

` $('form#registerFormId').on('submit', function (e) { validateForm();

var isValid = $('form#registerFormId').valid();

if (!isValid) {
    e.preventDefault(); //prevent the default action
}

}); `

clear validations


    //Reset the validators
    $('#registerFormId').removeData('validator');