Add Prefix in text field

When you have to prefix any hard coded value in a text field, like for example in telephone field you have to prefix the country code and dont want the user to remove it, then in that case assign the prefix code in the text field and add the below javascript code code

jQuery("input[name='job-code']").keydown(function(e) {
    var oldvalue = jQuery(this).val();
    var field = this;
    setTimeout(function() {
        if (field.value.indexOf('JPC-') !== 0) {
            jQuery(field).val(oldvalue);
        }
    }, 1);
});

Demo: https://codepen.io/phpweblamp/pen/yLwPqjJ

Detect Change in form fields

<script type=”text/javascript”>
var formChanged = false;
jQuery(window).load(function() { // This is triggered when the entiire page is loaded fully
// form id and all the possible filed type in that form, You can also target by field type, name, class or id
jQuery(‘#FrmIdToTarget input[type=text], #FrmIdToTarget select.form-control’).each(function (i)
{
// console.log(‘a’);
jQuery(this).data(‘initial_value’, jQuery(this).val());
});

jQuery(‘#FrmIdToTarget input[type=text], #FrmIdToTarget select.form-control’).keyup(function()
{
if (jQuery(this).val() != jQuery(this).data(‘initial_value’)) {
// console.log(‘1’);
handleFormChanged(‘saveDriverInfoBtn’);
}
});
jQuery(‘#FrmIdToTarget input[type=text], #FrmIdToTarget select.form-control’).bind(‘change paste’, function()
{
// console.log(‘b’);
handleFormChanged(‘saveDriverInfoBtn’);
});

jQuery(document.body).on(“click”, “#submitFormButtonId, button.cancelBtnDrvbtn”, function () {
if(formChanged === true){
return confirmNavigation();
}

});

});

function handleFormChanged(formSaveBtnId) {
// alert(‘formSaveBtnId=’+formSaveBtnId);
jQuery(‘#’+formSaveBtnId).removeAttr(‘disabled’);
formChanged = true;
}

function confirmNavigation() {
if (formChanged) {
return confirm(‘You have changes to save, Please save before moving to next tab? Otherwise your changes will be lost!’);
} else {
return true;
}
}
</script>

Jquery set input value and trigger on blur event

I want to trigger an event every time i click on select on any element by id

First i will try to set the input value by the following code

pickedvalue = jQuery(‘#someElementId’).val();

jQuery(‘#anotherInputElement’).val(parseInt(pickedvalue)); // use parseInt if the input type is “number” else not required.

After setting the new value to the other element i wanted to fire “on blur” event so to achieve the same use the below code.

jQuery(‘#anotherInputElement’).val(parseInt(pickedvalue)).trigger(“change”).blur();

 

–Happy Coding

Ajax call using jquery

function makeAjaxRequest(data1,data2,.....,datax){
    $.ajax({
        'type':'POST',
        async: false,
        url: 'http://www.example.com/some_request_url',
        data:{param1:data1,param2:data2,....,paramx:datax},
        success : function(response) {
            console.log(response); // Using this you can check the posted data in browser console window
            return true;// you can process and return the response as required
            //location.reload(); // or you may reload the current page also
        },
        error: function (jqXHR, exception) {
            // If some error is returned, you can check the details below
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'Not connect.\n Verify Network.';
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
            $('#post').html(msg); // return the error response in your html page or process it further as required
        }
    });
}

 

issue with submit form in ajax success response

Usually when we try to submit the form after ajax call on success response, the form does not’t get submitted.

Like for example in below code:-

$.ajax({
type : “POST”,
url : “to/some/url”,
data : {
userName:userName,
mobileNumber:mobileNumber,
otp:otp
},
dataType : “json”,
success : function(data)
{
if(data.result == true) {
jQuery(“#form_id”).submit();
}else {
return false;
}
}
});

Now why this occur. Since you are calling the submit function from the ajax response, you need to remove the “submit” handler before submitting the form again. I.E. You need to submit the form without doing the ajax call again. Refer below:-

$.ajax({
type : “POST”,
url : “to/some/url”,
data : {
userName:userName,
mobileNumber:mobileNumber,
otp:otp
},
dataType : “json”,
success : function(data)
{
if(data.result == true) {
// Submit this form without doing the ajax call again
jQuery(“#form_id”).unbind().submit();
}else {
return false;
}
}
});

 

Validate date format mm/dd/yyyy by using jquery validation library

First add the custom method to the validation library as below. Can you put this code in your jquery validation file or in your page where you want to validate the date, just before setting your validation rule for your form.

$.validator.addMethod(“dateFormat”,
 function (value, element) {
 return value.match(/^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/);
 },“Please enter a date in the format mm/dd/yyyy.”);

Now suppose you are using a datepicker or input field to accept the date in mm/dd/yyyy format like 02/21/2018 as example. You can validate it as below;

 

<form id="your-form-id">
<input id="submission_date" name="submission_date" type="text" />
<input type="submit" value="submitForm" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js">
 <script type="text/javascript">

$("#your-form-id").validate({
 rules: {
 submission_date: {
 required: true,
 dateFormat: true,
 },
 },
 messages: {
 submission_date: {
 required: "Please select or enter the submission date!!.",
 dateFormat: "Submission date should in the format mm/dd/yyyy.",
 },
 },
 errorPlacement: function(error, element) {
 error.insertAfter(element);
 },
 submitHandler: function (formName) {
 formName.submit();
 }
 });
 </script>

Validate date format mm/dd/yyyy in jquery or javascript

<script type="text/javascript">

function isValideDate(datavalue){
 var regexValidDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
 return regexValidDate.test(datavalue);
 }

var dateToCheck = '06/01/2011',

if(isValideDate(dateToCheck)){

alert("Given date is valid as per the format of MM/dd/YYYY");

}else{

alert("Given date is not valid as per the format of MM/dd/YYYY");

}

</script>

 

Redirect to another page after a specific time interval

<html>
<body>
<h1>Welcome to my Website</h1>
<h4 id=”msg”>You will be redirected to another page in 5 seconds!</h4>
<script type=”text/javascript”>
function countDown(i, callback) {
callback = callback || function(){};
var int = setInterval(function() {
//document.getElementById(“displayDiv”).innerHTML = “Number: ” + i;
document.getElementById(“msg”).innerHTML = “You will be redirected to backend page in “+i+” seconds!”;
i– || (clearInterval(int), callback());
}, 1000);
}
setTimeout(function(){
countDown(5, function(){
window.location=”[Give your absolute or relative url to redirect]”;
});
}, 3000);
</script>
</body>
</html>