Wednesday, April 14, 2021

How to find a string within a jQuery or javascript string

 Sometimes, you required to find a the existence of a small string with in a string. This article will demonstarte, how could you do by using plain JavaScript.

First Method

//returns -1 if doesn't contains
if (str.indexOf("Hello") >= 0) 
{
 //string contains Hello
}
//OR
//For your are not sure about the case of the string
//returns -1 if doesn't contains
if (str.toLowerCase().indexOf("hello") >= 0)
{
 //string contains hello
}
This indexOf() method will return the position of the match, or -1 if it isn’t found.

Second Method

//returns false if doesn't contains
if (/hello/i.test(str))
{
 //string contain Hello
}

What are jQuery Selectors?

 Selector is simply a way to select the node from the DOM, the node is nothing but the HTML tag or element. When Browser loads all the different HTML element, it will set up a memory in DOM, JQuery uses the selector which allows into the memory and select the different nodes or elements and do something with that.

 <div id="empDiv" class="empDiv" >
 

Consider above HTML element to find the div tag from the DOM we can use Id or if the Id is not available we can use the class, so now the question is how to use the jQuery selector which is used to find the element from DOM, the answer is written below,

 $(selectorExpression) or jQuery(selectorExpression) 
 $ => jQuery Object 
 selectorExperssion =>
 

What it is you want to find . Number of ways to use the selectors is listed below,

  1. Selecting Element by Tag Name

  2. Selecting Element by its ID

  3. Selecting Element by CSS Class Name

  4. Selecting Element by Attribute

  5. Selecting Input Element

  6. Additional Selector Features

Type
Selector
Example
Description
Selecting Element by Tag Name
p
$('p')
Selects all <p> elements in DOM.
p,a
$('p,a')
Selects all paragraph and anchor elements.
table tr
$(table tr')
Selects all descendants of the table element, that means it will select only <tr>element inside the <table>, not a <table>
Selecting Element by ID
#id
$('#paraContent)
Selects element with the ID paraContent.
Selecting Element by Class Name
.className
$(".paraClass")
Selects element with the class name paraClass.
Selecting the element by Attribute
[attribute]
$('div[title]')
Selects the <div> element with attribute title
[attribute=value]
$('div[title="Div Title"]')
Selects the <div> element with attribute title value as 'Div Title'
$('input[type="text"]')
Selects the input element with attribute type value as 'text'
[attribute!=value]
$('div[title!="DivTitle"]')
Selects the<div> elements with attribute title value not equal to 'DivTitle' .
Selecting input elements
:input
$(':input')
Selects all input element
input[attribute=value]
$(':input[type="radio"]')
Selects all input element with attribute type value 'radio'
Additional selector feature
:contains
$('p:contains(“Hello")')
Selects the <p>tag which match the specific text 'Hello'
:odd
$('tr:odd')
Will return the odd rows from the table
:even
$('tr:even)
Will return the even rows from the table
element:first-child
$('p:first-child')
Find all <p> and select first <p> element inside each parent
[attribute^="value"], $('input[value^="Hello"]')
Select all the input elements whose attribute value starts with “Hello"
[attribute$="value"]
$('input[value$="!"]')
Select all the input elements whose attribute value ends with “!"
[attribute*="value"]
$('input[value*="male"]' )
Select all the input elements whose attribute value contains male
  1. Selecting Nodes by Tag Name

    Let's start with the below example

     <p>Hello </p> 
     <a>click Me< /a>
     <p>Welcome to My Page </p> 
     
     $('p') => selects all <p> elements in DOM 
     

    this statement will go up in the DOM looks for all

    tags and returns it. In other scenarios from the above example, If we need to get all the elements, we can go with multiple tag selection, which is written below:

     $('p,a') => This will select all paragraph and anchor elements 
     

    To reference multiple tags, use the ',' character to separate the element

    HTML Code Snippet

     <div id="banner-message" >
     <p>Hello</p>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <button>Click Me</button>
     </div>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function(){
     console.log($("p")); 
     })
    

    Result in Browser Console

    Use Developer tool in the browser to check the result in console window

     
     <table> 
     <tr>
     <td> 
     </td> 
     </tr>
     </table>
    

    Consider above HTML where I need to select specific <tr> which is nested in <table>, In this scenario we need to use below jQuery statement.

    $('ancestor descendant') => select all descendant of the ancestor $(table tr') => selects all descendants of the table element, that means it will select only <tr> element inside the <table>, not a <table>

    Descendants are children, grandchildren, etc. of the designated ancestor elements

    HTML

     <div title="Div Title">
     <table style="width:100%">
     <tr>
     <th>Firstname</th>
     <th>Lastname</th> 
     </tr>
     <tr>
     <td>Jill</td>
     <td>Smith</td> 
     </tr>
     <tr>
     <td>John</td>
     <td>Miller</td> 
     </tr>
     </table>
     </div>
     

    JavaScript

     // find elements
     var button = $("button")
     button.on("click", function(){
     console.log($("table tr"));
     })
     
    

    Result in Browser Console

  2. Selecting Element by ID

    Use the # character to select the element by ID

     $('#paraContent) = > selects <p id=" paraContent"> element 
     

    Whenever we are using # it automatically goes in and look for something like ID, that the jQuery way of knowing the tag with specific ID.

    Code Snippet

    HTML

     <div id="banner-message" >
     <p>Hello</p>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <button>Click Me</button>
     </div>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function(){
     console.log($("#paraContent")); // ID Selector
     })
    

    Result in Browser Console

  3. Selecting Element by Class Name

    Class Name selector is very similar to the ID selector with a bit different in character syntax. Use the '.' Character to select the element by class name

     $('.paraClass') => selects <p class="paraClass"> element 
     
     $('.paraClass') =>
     

    says the jQuery, go find any element in the DOM that has the class attach to it called paraClass and returns the result sets.

    Code Snippet

    HTML

     <div id="banner-message" >
     <p>Hello</p>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <button>Click Me</button>
     </div>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function(){
     console.log($(".paraClass")); //Class Selector
     })
    

    For multiple tags, use the ',' character to separate the class name, as we do in tag selection

    $('.paraClass,.divClass') => select all elements containing the class paraClass and divClass

    HTML

     <div id="banner-message" >
     <div class="divClass" title="Div Title">
     <p>Hello</p> 
     <button>Click Me</button>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <input type="text" placeholder="Type here..." value="Hello World !!!"/>
     </div>
     </div>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     console.log($(".paraClass,.divClass")); // Multiple class selector
     })
    

    Result in Browser Console

    You can combine this with element name as well $('p.paraClass') = > this is more efficient than the way of selecting the element just by using the className because it doesn't require to scan whole DOM.

  4. Selecting the element by Attribute

    Use brackets [attribute] to select based on attribute name and/or attribute value. $('div[title]') = >This says the jQuery to go and find the elements in the DOM which has div and with title attribute $('div[title="Div Title"]') => select all div elements that have a “Div Title" title attribute value. This is very valuable selector when we have multiple div element.

     $('input[type="text"]') => will selects <input type=" text" />from the DOM 
     

    Code Snippet

    HTML

     <div id="banner-message" >
     <div class="divClass" title="Div Title">
     <p>Hello</p> 
     <button>Click Me</button>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <input type="text" placeholder="Type here..." value="Hello World !!!"/>
     </div>
     </div>
    

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     console.log($('input[type="text"]')); // Attribute selector
     })
    

    Result in Browser Console

    Note

    The attribute used as a selector is case sensitive

  5. Selecting input elements

    This selector is very useful when we are working with form, textarea, textboxes, checkboxes and other input elements $(':input') selects all input element including input, select, textarea, button, radio and more.

    Code Snippet

    HTML

     <div id="banner-message" >
     <div class="divClass" title="Div Title">
     <p>Hello</p> 
     <button>Click Me</button>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <input type="text" placeholder="Type here..." value="Hello World !!! "/>
     </div>
     <div>
     <input type="radio" name="gender" value="male" checked> Male<br>
     <input type="radio" name="gender" value="female"> Female<br>
     </div>
     </div>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     console.log($(':input')); // select all input from DOM 
     })
    

    Result in Browser Console

     $(': input[type="radio"]') =>

    targets all radio buttons on the page.

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     console.log($(':input[type="radio"]')); // select radio input type from the DOM 
     })
    

    Result in Browser Console

    Now the Question, is it more efficient selector while comparing with the selecting the element by attribute? This answer is simple, NO ??.

    Because $(':input[type="radio"]') will select all the input elements from the page from that it will fetch the element which has the attribute with value type ="radio", whereas $('input[type="textbox"]') will get the specific element instead of scanning from all the input element in DOM The major use case of this selector is, to iterate through all the input elements in the page.

  6. Additional selector feature

    jQuery provides additional selector feature where we can select the element based on the attribute startswith or endswith or contains

    Using contains in selectors

    :contains() will select elements that match the specific text.

     $('p:contains(“Hello")')
     Selects the <p> that contain the text Hello => it is case sensitive 
     <p>Hello</p>
     

    Code Snippet

    HTML

     <div id="banner-message" >
     <div class="divClass" title="Div Title">
     <p>Hello</p> 
     <button>Click Me</button>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <input type="text" placeholder="Type here..." value="Hello World !!!"/>
     </div>
     <div>
     <input type="radio" name="gender" value="male" checked> Male<br>
     <input type="radio" name="gender" value="female"> Female<br>
     </div>
     </div>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     console.log($('p:contains("Hello")')); // selects the 

    coantins "Hello" })

    Result in Browser Console

    Selecting Even or Odd Rows in a Table

    $('tr:odd') = >Will return the odd rows from the table, means return 1,3,5. .etc $('tr:even') = >will return the even rows from the table, means return 0,2,4…etc

    HTML

     <div class="divClass" title="Div Title">
     <p>Hello</p> 
     <button>Click Me</button>
     <p id="paraContent" class="paraClass">Welcome to My Page</p> 
     <input type="text" placeholder="Type here..." value="Hello World !!! "/>
     </div>
     <div>
     <input type="radio" name="gender" value="male" checked> Male<br>
     <input type="radio" name="gender" value="female"> Female<br>
     </div>
    
    <div title="Div Title">
    <table style="width:100%">
     <tr>
     <th>Firstname</th>
     <th>Lastname</th> 
     
     </tr>
     <tr>
     <td>Jill</td>
     <td>Smith</td> 
     
     </tr>
     <tr>
     <td>John</td>
     <td>Miller</td> 
     
     </tr>
    </table>
    </div>
    JavaScript
    // find elements
    var button = $("button");
    button.on("click", function()
    {
    console.log($('tr:odd')); // select odd rows in table 1,3,4.. etc 
    console.log($('tr:even')); // select odd rows in table 0,2,4.. etc })
    

    Result in Browser Console

    Selecting the First Child

    $('element:first-child') selects the first child of every element group. $('p:first-child') = > go find all

    and select first

    inside the each parent

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     console.log($('p:first-child')); //selects first child element of <p> from the parent 
     })
     

    Result in Browser Console

    Using starts with in the selector

    [attribute^="value"] will select all the element within an attribute that begins with the stated value $('input[value^="Hello"]' ) select all the elements whose attribute value starts with “Hello"

     <input type="textbox" value="Hello World"/>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {>
     console.log($('input[value^="Hello"]')); // selects the <input> where the values start with "Hello" 
     })
     

    in Browser Console

    Using Ends with in the selector

    The syntax is pretty much like startwith, the only change is symbols. [attribute$="value"] will select all the element within an attribute that begins with the stated value $('input[value$="!"]' ) select all the elements whose attribute value ends with “!"

     <input type="textbox" value="Hello World !!!"/>
     

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     
     console.log($('input[value$="!"]'));// selects the <input> where the values end with "!"
     })
     

    Result in Browser Console

    Find attributes containing a value

    The syntax is pretty much similar to starts with/ends with the only change is symbols. [attribute*="value"] will select all the element within an attribute that begins with the stated value $('input[value*="male"]' ) select all the elements whose attribute value contains male

    JavaScript

     // find elements
     var button = $("button");
     button.on("click", function()
     {
     console.log($('input[value$="!"]'));// selects the <input> where the values end with "!"
     })
     

    Result in Browser Console

Summary

We have learned how to use the jQuery selector based on the HTML element tag, class name, ID, attribute and some additional selector. jQuery selector is a powerful feature which really useful to increase the productivity and flexibility in the developed.

Disable cut, copy and paste in textbox using jquery, javascript

 Due to some reasons (like don’t allow to copy Email from Email TextBox to Confirm Email TextBox), we restrict users to copy, paste and cut contents from TextBox by using CTRL+C, CTRL+V and CTRL+X. We can implement this functionality by using below methods.

Disable cut, copy & paste using Javascript

  1. When we don't want to display any message on cut, copy & paste

     <asp:TextBox ID="TextBox1" runat="server" oncopy="return false" onpaste="return false" oncut="return false"></asp:TextBox> 
  2. When we want to display an alert message on copy, paste and cut

     <script language="javascript" type="text/javascript">
    function DisableCopyPaste (e) 
    {
     // Message to display
     var message = "Cntrl key/ Right Click Option disabled";
     // check mouse right click or Ctrl key press
    var kCode = event.keyCode || e.charCode; 
    //FF and Safari use e.charCode, while IE use e.keyCode
     if (kCode == 17 || kCode == 2)
     {
     alert(message);
     return false;
     }
    }
    </script>
     <asp:TextBox ID="TextBox1" runat="server" onKeyDown="return DisableCopyPaste(event)"onMouseDown="return DisableCopyPaste (event)"></asp:TextBox> 

Disable cut, copy & paste using JQuery

 <script type="text/javascript">
$(document).ready(function() {
 $('#TextBox1').bind('copy paste cut',function(e) { 
 e.preventDefault(); //disable cut,copy,paste
 alert('cut,copy & paste options are disabled !!');
 });
});
</script>
 <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox> 

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...