Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Wednesday, 1 April 2015

Introduction: 

Some time it is needed to add items to array only if they are not there in array. This can be done by using jQuery.

In this article I will explain how to use jquery to add items or elements to an array if not exist in list. By using inArray property we can check whether elements exist or not in array using jQuery.

Method Used to check whether elements exist or not in array using jQuery:

<script type="text/javascript">
    $(function () {
        var arr = ["test", "test1"];
        $('#btnInsert').click(function () {
            var str = $('#txtItem').val();
            var stats = $.inArray(str, arr);
            if (stats == -1) {
                arr.push(str);
                for (var i = 0; i < arr.length; i++) {
                    alert(arr[i])
                }
            } else {
                alert('Item Already Exists')
            }
        });
    })
</script>

Full Source code for Sample Application:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jquery Add Items or elements to Array if not exists</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        var arr = ["test", "test1"];
        $('#btnInsert').click(function () {
            var str = $('#txtItem').val();
            var stats = $.inArray(str, arr);
            if (stats == -1) {
                arr.push(str);
                for (var i = 0; i < arr.length; i++) {
                    alert(arr[i])
                }
            } else {
                alert('Item Already Exists')
            }
        });
    })
</script>
</head>
<body>
<center>
<fieldset style="width:300px">
    <legend><strong>Insert Value to Array USing jQuery</strong></legend>
<div>
<br />
Enter Item: <input type="text" id="txtItem" value="Item" /><br /><br />
<input type="button" id="btnInsert" value="Insert Item" />
</div></fieldset></center>
</body>

</html>
Categories: , , ,

0 comments:

Post a Comment