Category: jQuery

Mobile phone validation using javascript or jQuery

For mobile number validation you can use regular expression which give you best output . This is javascript code which check mobile number valid or not.

<html>
<head>
    <title>Mobile number validation using regex</title>
    <script type="text/javascript">
        function validate() {
            var mobile = document.getElementById("mobile").value;
            var pattern = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;
            if (pattern.test(mobile)) {
                alert("Your mobile number : "+mobile);
                return true;
            }
            alert("It is not valid mobile number");
            return false;

        }
    </script>

</head>
<body>
Enter Mobile No. :
<input type="text" name="mobile" id="mobile" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>

and you can also jQuery for mobile number validation , this is simple code

<html>
<head>

    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <title>Mobile number validation using regex</title>
    <script type="text/javascript">
        function validate() {
            var mobile = $("#mobile").val();
            var pattern = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;
            if (pattern.test(mobile)) {
                alert("Your mobile number : " + mobile);
                return true;
            }
            alert("It is not valid mobile number");
            return false;

        }
    </script>

</head>
<body>
Enter Mobile No. :
<input type="text" name="mobile" id="mobile"/>
<input type="submit" value="Check" onclick="validate();"/>
</body>
</html>

If you face any problem then please inform me.

Comment

How to check div is hide or show using jQuery?

If you want to check that div is block(visible) or none then you can do this very easily . Suppose your div id = “test” -> for testing purpose if you use class = “test” then need to update code For checking Block or visible then use this for your select test is ID . This is simple code

1. if ($('#test').is(':visible')) {}

2. if ($('#test').css('display') == 'block'){}

3. if ($('#test').not(':hidden')){}

if you want to check this using class name

1. if ($('.test').is(':visible')) {}
2. if ($(your_element).is(':visible')) {}

This is other option for checking none or hide then use this code if your selector is id

1. if ($('#test').not(':visible')){}

2. if (!$('#test').is(':visible')){}

3. if ($('#test').css('display') == 'none'){}

4. if ($('#test').is(':hidden')){}

if you use class name then code is

1. if ($('.test').not(':visible')){}
2. if ($(your_element).not(':visible')){}

hop e it will help you. if you have face any problem then inform me.

Comment

How to update session variable from dropdown change?

If you want to update your value like when drop down change then this value will set in php session in this case you can use ajax which help you lot. This is simple code which update session value when change drop down change .

This is total html and php code which need to update and browse data

<?php
session_start(); // for show your session value 
print_r($_SESSION); // remove this after check
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="myForm" action="/thanks" method="POST">

    <table>
        <tr>
            <td style="width:272px;">
                <select name="select_amount" id="select_amount" onchange="update_session_value(this.value)">
                    <option value="0">select a listing type</option>
                    <option value="10">Premium Listings</option>
                    <option value="20">Premium Blogs</option>
                    <option value="30">1 week sticky</option>
                </select></td>

            <td style="text-align:left;color:gray;">
                <span style="color:crimson;">*
            </span>Select a listing type
            </td>
        </tr>
    </table>
    <input type="submit" name="submit" class="button_add" onsubmit="return validateForm()">

</form>

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {

            }
        });
    }

</script>

Then create php file which update session value

<?php
session_start();
if( isset($_POST['select_amount']) ) {
    // save values from other page to session
    $_SESSION['amount'] = $_POST['select_amount'];

}
?>

For test you can refresh the page and check output or ajax function update this code

<script>
    function update_session_value(value) {
        $.ajax({
            type: "POST",
            url: 'http://localhost/session.php', // change url as your 
            data: 'select_amount=' + value,
            dataType: 'json',
            success: function (data) {
 window.location.reload;
            }
        });
    }

</script>

if you face any problem then please inform me, I will try to help you

Comment

how to change the style of alert box?

Now we want to change website more style so normal alert box is not good to see so in this case we want to change it.
There are some library which help you a lot. This is some link which you can use

Option 1: You can use

There are lot of option to customize it. hope you will like it

Option 2 : you can also use

This is very cool and more option to customize

If you need any help then please inform me, i will try to help you

Comment

How to check if all inputs are not empty with jQuery?

If you want to check that all input fields not empty or any field empty then give error and show error message. You can do this easily using jQuery . This is simple code you can test it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
    textarea{height:auto;}
    select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
    select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
    select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
    .uneditable-textarea{width:auto;height:auto;}
    #country{height: 30px;}
	.highlight
	{
		border: 1px solid red !important;
	}
</style>
<script>
function test()
{
 var isFormValid = true;

    $(".bs-example input").each(function(){
        if ($.trim($(this).val()).length == 0){
		    $(this).addClass("highlight");
            isFormValid = false;
			$(this).focus();
        }
        else{
            $(this).removeClass("highlight");
        }
    });

    if (!isFormValid) { 
		alert("Please fill in all the required fields (indicated by *)");
	}

    return isFormValid;
}	
</script>
</head>
<body>
<div class="bs-example">
    <form onsubmit="return test()">
        <div class="form-group">
            <label for="inputEmail">Email</label>
            <input type="text" class="form-control" id="inputEmail" placeholder="Email">
        </div>
        <div class="form-group">
            <label for="inputPassword">Password</label>
            <input type="password" class="form-control" id="inputPassword" placeholder="Password">
        </div>
        <button type="submit" class="btn btn-primary">Login</button>
    </form>
</div>
</body>
</html>   

If you face any problem then please inform me.

Comment

how to remove http:// or https:// from url using JavaScript?

In some case we need to remove https or http from url. We can do it using javascript. Here is simple code

   var url = "https://techparkbd.com/";
   url = url.replace(/^https?:\/\//,'');
   console.log(url);

This output :


techparkbd.com/

If you face any problem then please inform me, I will try to help you.

Comment

How to change css for mobile ?

If you want to change css for specific device then you can use this code. This is simple code.

Option 1:

var window_weight = $(window).width();
    // change weight as your wish
    if (window_weight <= 600) {
        //$('.text-class').removeClass('mobile');
        $('.text-class').css('weight','100px');
    }

Option 2:


if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
            || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) {

        //$('.text-class').removeClass('mobile');
        $('.text-class').css('weight','100px');
    }

if you face any problem then please inform me, i will try to help you.

Comment

Get the max height from a set of elements using jQuery.

In various design section we need to match height for list for look better. In this case need to determine max height of some element and then set this height for all other element .In this case you can do it easily using normal jquery map function. Here is simple code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <div class="testdiv">
        Line 1<br>
        Line 2
    </div>
    <div class="testdiv">
        Line 1<br>
        Line 2<br>
        Line 3<br>
        Line 4
    </div>
    <div class="testdiv">
        Line 1
    </div>
    <div class="testdiv">
        Line 1<br>
        Line 2
    </div>
</div>

From this element we need to determine max height then add some style . This is simle jQuery code

<script>
    var highest = null;
    var hi = 0;
    $(".testdiv").each(function () {
        var h = $(this).height();
        if (h > hi) {
            hi = h;

            highest = $(this);
        }
    });
    alert(hi)
    highest.css("background-color", "red");

</script>

In this case this code get max height then you can set other element same height and also some style

If you need any help or face any problem then please inform me, i will try to help you.

Comment

How do I determine browser name using JavaScript?

If you want to know which browser access your page or other case then you can do this using javascript. This is simple code which you can use.

<script>
    function get_browser() {
        var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if (/trident/i.test(M[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE';
        }
        if (M[1] === 'Chrome') {
            tem = ua.match(/\bOPR\/(\d+)/)
            if (tem != null) {
                return 'Opera'
            }
        }
        M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
        if ((tem = ua.match(/version\/(\d+)/i)) != null) {
            M.splice(1, 1, tem[1]);
        }
        return M[0];
    }

    var browser = get_browser();

    alert(browser)

</script>

this code give alert browser name. If you face any problem then please inform me.

Comment