Category: jQuery

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

Input tab index auto jump using jQuery.

In html form or other some time need tab auto jump when max length is covered. We can do it easily javascript code.

First create simple html code

<input size="2" tabindex="1" id="one"
maxlength="2" onkeyup="toUnicode(this)" />

<input size="2" tabindex="2" id="two"
maxlength="2" onkeyup="toUnicode(this)" />

<input size="2" tabindex="3" id="three"
maxlength="2" onkeyup="toUnicode(this)" />

then create javascript code. this is javascript code.

function toUnicode(elmnt)
{
  var next;
  if (elmnt.value.length==elmnt.maxLength)
  {
    next=elmnt.tabIndex + 1;
    //look for the fields with the next tabIndex
    var f = elmnt.form;
    for (var i = 0; i < f.elements.length; i++)
    {
      if (next<=f.elements[i].tabIndex)
      {
        f.elements[i].focus();
        break;
      }
    }
  }
}

then browse it and press onkeyup then automatic go to next input field.

Comment

How can I load jQuery if it is not loaded?

If you need to check that a specific jQuery load or not load if not loaded then load it or not load . You can do this using jquery . This is simple code.

<script type="text/javascript">
 var baseurl="shafiqul.wordpress.com";
 var doc=document.getElementsByTagName("head").item(0);
 var jQueryScriptOutputted = false;
 var jQueryScriptOutputtedplaceholder = false;
 window.onload=function()
 {
 initJQuery();
 }
 function initJQuery() {
 if (typeof(jQuery) == "undefined") {
 if (! jQueryScriptOutputted) {
 jQueryScriptOutputted = true;
 includeJs("/js/jquery-1.4.4.min.js", true);
| }
 }
 if (! jQueryScriptOutputtedplaceholder) {
 jQueryScriptOutputtedplaceholder = true;
 includeJs("/scripts/html5_placeholder.js", true);
 }
 setTimeout("initJQuery()", 100);
 }
 function includeJs(fileName, jQ, head){
 var js=document.createElement("script");
 js.setAttribute("language", "javascript");
 js.setAttribute("type", "text/javascript");
 js.setAttribute("src", baseurl+fileName);
 if(jQ===true){
 doc.insertBefore(js, doc.firstChild);
 return false;
 }
 if(head===true){
 doc.appendChild(js);
 return false;
 }
 document.getElementsByTagName("body").item(0).appendChild(js);
 return false;
 }
 </script>

This code first check jquery already or not, if not loaded then load it. If you face any problem then please inform me.

Comment

Show Content if class attribute exists in page.

If you want to show content when class exit in this page then you can use this code .It will give alert ok when class attribute exit in this page , you can change also class to id if you want.

<body>
<div class="home-container">
    <div class="home">

        Content

    </div>
    <span style="cursor: pointer; background: #0f192a;color: #00BD9B" onclick="test()">Click</span>
</div>
</body>

then this is javascript code which give alert if class attribute exit in this page

function test() {
        if (document.querySelector('.home') !== null) {
            alert('ok');
        } else {
            alert('not');
        }
    }

In this code home attribute exit so it will give alert ok.
If you find any problem then please inform me.

Comment

how to remove id and add new id using jQuery?

For remove exiting id from attribute and add new id , in this case you can use jQuery code which very simple to do this. this is demo code

<script>
$(document).ready(function(){
$('.test').removeAttr('id');
$('.test').attr('id','test1');
});
</script>

and this is html code section.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<p id="test" class="test">Add new id</p>
</body>

this is code i add ID test and add class also test so i want to remove id and add new ID test1 . so please check this code which help you.
If you face any problem then please inform me.

Comment

how to count textarea characters using jquery?

If you want to count that which characters left in your textarea then you can use this code, in this code i need to count 99 and check which left when enter text in textarea. check this simple demo code.

<script>
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');

$('#textarea').keyup(function() {
    var text_length = $('#textarea').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback').html(text_remaining + ' characters remaining');
});

});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>

this code check left characters ,if you need any help then please inform me.

Comment

make two dropdown values from an array using JavaScript and jQuery.

If you want to make two select dropdown using javascript array then you can use this code which help you.

This is html code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectNumber">
	<option>Choose a number1</option>
</select>
<select id="selectNumber2">
	<option>Choose a number2</option>
</select>

this is jQuery code

<script> 
var options = ["1", "2", "3", "4", "5"];

    $.each(options, function(key, value) {
        $('#selectNumber,#selectNumber2').append($("<option/>", {
            value: key,
            text: value
        }));
    });

</script>

There is other option

<script>
        var select = document.getElementById("selectNumber");
        var select2 = document.getElementById("selectNumber2");
        var options = ["1", "2", "3", "4", "5"];
        for (var i = 0; i < options.length; i++) {
            var opt = options[i];
            var el = document.createElement("option");
            el.textContent = opt;
            el.value = opt;
            select.appendChild(el);
            select2.appendChild(el.cloneNode(true));
        }
    });
</script>

This is other option if you want separate the option code

<script>
    var select = document.getElementById("selectNumber");
    var select2 = document.getElementById("selectNumber2");
    var options = ["1", "2", "3", "4", "5"];
    for (var i = 0; i < options.length; i++) {
        var opt = options[i];

        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);

        var e2 = document.createElement("option");
        e2.textContent = opt;
        e2.value = opt;
        select2.appendChild(e2);
    }
</script>

If you find any problem or face any problem then please inform me.

Comment

How to get the ‘height’ and ‘width’ of the screen using jquery?

If you want to show the screen height and width then you can use jQuery. You can aslo get giv height , width using this same process. This is simple code.

var height = $(window).height(); // for height of the browser view
var height = $(document).height(); // for height of HTML document
var width = $(window).width(); // for width of browser view
var width = $(document).width(); // for width of HTML document

If you want to know the screen width, height then this code help you

var height = screen.height;
var width = screen.width;

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

Comment

Get all href value using jquery and replace it.

If you want to get all link using jQuery then you can use this code easily. Here is code which get all link using each function then check , if value is something and you want to change it.

<script type="text/javascript">
$('a').each(function() {
var value = $(this).attr('href');
if(value=='http://google.com')
{
$(this).attr('href', 'http://youtube.com');
}
});​
</script>

if you face any problem then please inform me.

Comment

Dynamic Drag and Drop using PHP & mysql and jQuery

This is very common feature that items list need to drag and drop and save it. Drag’n drop generally looks hard-to-apply but it is definitely not by using JavaScript frameworks. In this article i will show how the drag’n drop & saving the new positions to the database Will be working”. This is very simple process you can apply it. This is simple code which you can check

First create a simple database Suppose “drag” . Here is the code for create a table then run this code in mysql

CREATE TABLE `records` (
 `recordID` int(11) NOT NULL auto_increment,
 `recordText` varchar(255) default NULL,
 `recordListingID` int(11) default NULL,
 PRIMARY KEY (`recordID`)
 );
 
INSERT INTO `records` VALUES ('1', 'Once dropped, an Ajax query is activated', '3');
 INSERT INTO `records` VALUES ('2', 'Dragging changes the opacity of the item', '2');
 INSERT INTO `records` VALUES ('3', 'Returned array can be found at the right', '1');
 INSERT INTO `records` VALUES ('4', 'It is very very easy', '4');

The most important column in the database is recordListingID which shows us the order of the records.

Then create a php page which ready mysql connect .

<?php
/*
* Author : Ali Aboussebaba
* Email : bewebdeveloper@gmail.com
* Website : http://www.bewebdeveloper.com
* Subject : Dynamic Drag and Drop with jQuery and PHP
*/

// PDO connect *********
function connect() {
	$host = 'localhost';
	$db_name = 'drag';
	$db_user = 'root';
	$db_password = '';
    return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
?>

Then create index.php which is the main page to view list

<!DOCTYPE>
<html>
<?php
include('config.php');
$pdo = connect();
$sql = 'SELECT * FROM records ORDER BY recordListingID ASC';
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();

?>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jQuery Dynamic Drag'n Drop</title>
    <script type="text/javascript" src="http://techparkbd.com/subdomain/source_file/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="http://techparkbd.com/subdomain/source_file/jquery-ui-1.10.4.custom.min.js"></script>

    <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            margin-top: 10px;
        }

        ul {
            margin: 0;
        }

        #contentWrap {
            width: 700px;
            margin: 0 auto;
            height: auto;
            overflow: hidden;
        }

        #contentTop {
            width: 600px;
            padding: 10px;
            margin-left: 30px;
        }

        #contentLeft {
            float: left;
            width: 400px;
        }

        #contentLeft li {
            list-style: none;
            margin: 0 0 4px 0;
            padding: 10px;
            background-color:#00CCCC;
            border: #CCCCCC solid 1px;
            color:#fff;
        }

        #contentRight {
            float: right;
            width: 260px;
            padding:10px;
            background-color:#336600;
            color:#FFFFFF;
        }

    </style>
    <script type="text/javascript">
        $(document).ready(function(){

            $(function() {
                $("#contentLeft ul").sortable({ opacity: 0.6, cursor: 'move', update: function() {
                    var order = $(this).sortable("serialize");
                    $.ajax({
                        url: 'http://localhost/updatelist.php?action=updateRecordsListings',
                        type: 'POST',
                        data: order,
                        success: function (result) {
                            $("#contentRight").html(result);
                        }
                    });
                }
                });
            });

        });
    </script>

</head>
<body>

<div id="contentWrap">
    <div id="contentLeft">
        <ul>
            <?php
            foreach ($list as $rs) {
                ?>
                <li id="recordsArray_<?=$rs['recordID']?>"><?=$rs['recordText']?></li>
                <?php
            }
            ?>
        </ul>
    </div>

    <div id="contentRight">
        <p>New List will be displayed here.</p>
        <p>&nbsp; </p>
    </div>

</div>

</body>
</html>


After posting the array of “new order of the items” to updatelist.php, we must run a query to update our database that will reflect the last positions of every item:

<?php
include('config.php');
$pdo = connect();

$action = $_GET['action'];
$updateRecordsArray = $_POST['recordsArray'];

if ($action == "updateRecordsListings"){

    $listingCounter = 1;
    foreach ($updateRecordsArray as $recordIDValue) {

        $query = "UPDATE records SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
        $query = $pdo->prepare($query);
        $query->execute();
        $listingCounter = $listingCounter + 1;
    }

    echo '<pre>';
    print_r($updateRecordsArray);
    echo '</pre>';
    echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>

all done so run index.php and drag list , it will automatically save drag list and after refresh it will show new list

This is example output


this is output

Comment