Category: JAVASCRIPT

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

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 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 add and remove attribute with jquery?

If you want to add and remove attribute using jquery then you can check this code. It will remove id and then when click remove then this id will remove. I also add css for understanding it.

This is html and css code


<div id="page_navigation1" style="border: 2px solid #ccc;height: 70px;width: 300px">Main Content</div>
<button id="add">Add</button>
<button id="remove">Remove</button>

This is css code

<style>
    #page_navigation1 {
        color: red;
    }
</style>

This is jQuery code which add and remove attribute

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#page_navigation1").addClass("page_navigation");

        $("#add").click(function(){
            $(".page_navigation").attr("id","page_navigation1");
        });
        $("#remove").click(function(){
            $(".page_navigation").removeAttr("id");
        });
    });
</script>

When run this code you will see this effect, If you find any problem then please inform me.

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

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

How to auto reload and clear cache using Javascript?

If you want to reload page automatically and at a time you want to clear cache then you can do this using javascript. This is simple code which reload after 3 seconds

 

<pre class="brush: xml; title: ; notranslate" title=""><!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
setInterval(function(){cache_clear()},3000);
});
function cache_clear()
{
window.location.reload(true); // if you do not want to clear cache then use window.location.reload();
}
</script>
</head>

<body>
<p>Auto reload and clear cache</p>
</body>
</html></pre>

Hope it will help you. If you face any problem then please inform me.

Comment

how to set class to selected “li” dynamically using jQuery?

If you want to add class in click li and remove all other class from all li then you can use simple jQuery code. Sometime we need to set active class for menu or other in this case this code is very helpful. This is simple code which set new class and remove all class from li.

$(document).ready(function(){
        $('.list li').click(function() {
             $( '.list li' ).removeClass( "active" ); // remove active class from all li 
            $(this).addClass('active'); // add active class for click li
        });
    });

then this is html code

active {
color:red;
}
   li {
   cursor: pointer;
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
            <li>Test 1</li>
            <li>Test 2</li>
            <li>Test 3</li>
            <li>Test 4</li>
            <li>Test 5</li>
            <li>Test 6 </li>
            <li>Test 7</li>
        </ul>

When you click any li then remove all class and add active class , i also add a css which color is red then easily can understand it.
If you face any problem then please inform me. I will try to help you.

Comment