javascript

[Jquery] Using jquery events

The jQuery library includes a nice event-handling system that supports all the underlying JavaScript events but makes them easier to use, consistent between browsers, and compatible with selectors.

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('tr').prepend("<td></td>");
    $('<input name="delete" type="radio"/>').prependTo('tbody td:first-child')
        .first().attr("checked", true);
    $(':button').bind("click", function (e) {
        $(':radio:checked').closest('tr').remove();
        $(':radio').first().attr("checked", true);
    });
});

The bind function takes two arguments—the name of the event that we want to handle and the function that will be executed when the event arises. We call the bind function on a jQuery collection, which has the effect of setting up the event handler on all of the selected elements.

In the example, we use the bind function to listen for the click event from all elements that are matched by the :button filter.

In our handler function, we select the checked radio button, use the closest function to find the nearest tr ancestor, and call the remove function to remove the row from the table. The effect is that clicking the Delete button removes the row whose radio button is checked.

After we have deleted the row, we find the first radio button in the document and set the checked attribute to true, so that subsequent button clicks will delete the first row in the table.

Selected jquery event-handler functions

  • click Corresponds to the click event, triggered when the user presses and releases the mouse
  • dblclick Corresponds to the dblclick event, triggered when the user presses and releases the mouse twice in quick succession
  • mouseenter Corresponds to the mouseenter event, triggered when the mouse enters the region of screen occupied by an element
  • mouseleave Corresponds to the mouseleave event, triggered when the mouse leaves the region of screen occupied by an element
  • change Corresponds to the change event, triggered when the value of an element changes
  • select Corresponds to the select event, triggered when the user selects the element value
  • submit Corresponds to the submit event, triggered when the user submits a form

We can rewrite the above example so we use click function instead of bind:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('tr').prepend("<td></td>");
    $('<input name="delete" type="radio"/>').prependTo('tbody td:first-child')
        .first().attr("checked", true);
    $(':button').click(function (e) {
        $(':radio:checked').closest('tr').remove();
        $(':radio').first().attr("checked", true);
    });
});

 

javascript

[Jquery] Using jquery functions

Jquery CSS functions

  • addClass(‘myClass’) Adds the specified class name to the class attribute of selected elements
  • hasClass(‘myClass’) Returns true if any of the selected elements have been assigned the specified class
  • removeClass(‘myClass’) Removes the specified class name from the class attribute of selected elements
  • toggleClass(‘myClass’) Adds the specified class if it isn’t present and removes it otherwise
  • css(‘property’, ‘value’) Adds the specified property and value to the style attribute of selected elements
  • css(‘property’) Returns the value of the specific property from the first matched element

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('td').addClass("highlight").css("color", "blue");
});

Chaining jquery functions call together. This will matches all td elements, add class “highlight” and set css value to blue for color property.

Using the DOM navigation functions

  • children() Gets the children of the selected elements
  • closest(‘selector’) Navigates through the ancestors of each of the selected elements to find the first instance of an element that matches the specified selector
  • filter(‘selector’) Reduces the selected elements to those that match the specified selector
  • first(‘selector’) Navigates through the descendants of the selected elements and locates all those elements that match the specified selector
  • next() Gets the sibling elements that immediately follow the selected elements
  • prev() Gets the sibling elements that immediately precede the selected elements
  • parent() Returns the immediate parent of the selected elements
  • siblings() Returns the siblings of the selected elements

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('table').find("td[class]").parent().filter(":odd").addClass("highlight");
});

In this example, we select the table element and then find all of the descendant td elements that have a class attribute. We use the odd filter to select only the odd numbered elements we selected and call the addClass function to apply our CSS class.

Using DOM manipulation functions

  • before(‘new’)after(‘new’) Inserts the element new either before or after the selected elements 
  • insertBefore()insertAfter() As for before and after, but the order of the new element and the selector is reversed, and these functions return the newly created elements
  • prepend(‘new’)append(‘new’) Inserts the element new inside of the selected elements, either as the first or last child
  • prependTo()appendTo() As for prepend and append, but the order of the new element and the selector is reversed, and these functions return the newly created elements
  • empty() Removes all children from the selected elements
  • remove() Removes the selected elements from the DOM
  • attr(‘name’, ‘val’) Sets the attribute name to value val on the selected elements; will create the attribute if it doesn’t already exist
  • removeAttr(‘name’) Removes the attribute name from the selected elements

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('tr').prepend("<td></td>");
    $('<input name="delete" type="radio"/>').prependTo('tbody td:first-child')
        .first().attr("checked", true);
});

We have used the DOM manipulation functions to add a new column to the table element, allowing the user to select one of the rows with a radio button.

There are two jQuery statements in this example. The first one selects all of the tr elements in the document and inserts an empty td element as the first child for each of them using the prepend function.

The second statement uses the prependTo function to insert a new radio button into the td elements that are the first children of their parents and that are descendants of a tbody element—this is, a subset of the td elements that we just created excluding the one we added in the table header.

The result of the prependTo function is the set of elements that have been added to the document. We use this fact to call the first function (which, when used without a selector, matches the first element in the collection, irrespective of what it is) and then the attr function to set the checked attribute to true.

The result is that we add a new column of td elements throughout the table and insert radio buttons in those new cells that are in the table body, ensuring that the first radio button is checked

javascript

[Jquery] Selecting elements

Selecting elements by Type, Class or Id

  • $(‘*’) – Select all the elements in document
  • $(‘.myClass’) – Select all the elements that have class myClass
  • $(‘element’) – Select all the elements of type element
  • $(‘#myId’) – Select element with id myId

Selecting elements by using relationship or union

  • $(‘tr td’) – Matches td elements that are descendants of tr elements
  • $(‘tr > td’) – Matches td elements that are immediate descendants of tr elements
  • $(‘h2 + table’) – Matches table elements that immediately follow h2 elements
  • $(‘h2 ~ table’) – Matches table elements that follow h2 elements
  • $(‘tr, td’) – Matches tr and td elements

Selecting elements using attribute

  • $(‘[attr]’) – Selects elements that have an attribute called attr, irrespective of the
    attribute value
  • $(‘[attr]=”val”‘) – Selects elements that have an attr attribute whose value is val
  • $(‘[attr]!=”val”‘) – Selects elements that have an attr attribute whose value is not val
  • $(‘[attr]^=”val”‘) – Selects elements that have an attr attribute whose value starts with val
  • $(‘[attr]~=”val”‘) – Selects elements that have an attr attribute whose value contains val
  • $(‘[attr]$=”val”‘) – Selects elements that have an attr attribute whose value ends with val
  • $(‘[attr]|=”val”‘) – Selects elements that have an attr attribute whose value is val or starts with val followed by a hyphen (val-)

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('[type][value="Delete"]').addClass("highlight");
});

The selector in this statement matches those elements that have a type attribute (with any value) and a value attribute whose value is Delete

Selecting elements using filters

  • :eq(n) – Selects the nth item in the selection, using a zero-based index
  • :even:odd – Selects the even-numbered or odd-numbered elements
  • :first:last – Selects the first or last element
  • :gt(n):lt(n) – Selects all the elements whose index relative to their siblings is greater
    or less than
    n
  • :header – Selects all elements that are headers (h1, h2, and so on)
  • :not(selector) – Selects all the elements that do not match the selector

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('tr:eq(1)').addClass("highlight");
});

This selector matches all of the tr elements and filters the one that is at position 1 in the selection. Elements are selected in the order that they appear in the document, which means that we have selected the second tr element to appear in the document (because the eq filter uses a zero-based index).

Selecting elements using content filters

  • :contains(‘text’) Selects elements that contain text or whose children contain text
  • :has(‘selector’) Selects elements that have at least one child element that matches selector
  • :empty Selects elements that have no child elements
  • :parent Selects elements that have at least one other element
  • :first-child Selects elements that are the first child of their parent
  • :last-child Selects elements that are the last child of their parent
  • :nth-child(n) Selects elements that are the nth child of their parent, using a one-based index
  • :only-child Selects elements that are the only child of their parent

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $('tr:has(td:contains("Kili"))').addClass("highlight");
});

In this example, we select tr elements that contain td elements whose text contains Kili

Selecting elements using form filters

  • :button Selects button elements and input elements whose type is button
  • :checkbox Selects check boxes
  • :checked Selects check boxes and radio button elements that are checked
  • :disabled:enabled Selects items that are enabled or disabled, respectively
  • :input Selects input elements
  • :password Selects password elements
  • :radio Selects radio buttons
  • :reset Selects input elements whose type is reset
  • :selected Selects option elements that are selected
  • :submit Selects input elements whose type is submit
  • :text Selects input elements whose type is text

Example:

/// <reference path="jquery-1.8.2.js" />
$(document).ready(function () {
    $(':button').addClass("highlight");
});

 

javascript

[Jquery] Waiting for the DOM

When you load a page, you need to make sure that all elements (HTML elements) have been loaded before making any change. This is because the main idea of jquery is to find elements in the document using CSS selectors.

We will get unexpected results if we apply those selectors before the browser has managed to load and process the entire HTML because some elements we are looking for may not be available yet.

There are 2 ways to do this:

  • Put the script at the end of the body section of HTML document
  • Use the jquery ready function
/// <reference path="jquery-3.2.1.js" />
$(document).ready(function() {
    //
});

 

Note: We need to add the reference to jquery by dragging the jquery file into the editor area of the jquery file we are going to use jquery. It will be commented out but ASP.NET still process the line.

asp.net · ebook

[ASP.NET] Performing validation

Step 1: Decorate property with validation attribute

public class GuestResponse
    {
        [Required(ErrorMessage = "Please enter your name")]
        public string Name { get; set; }
 
        [Required(ErrorMessage = "Please enter your email")]
        public string Email { get; set; }
 
        [Required(ErrorMessage = "Please enter your phone")]
        public string Phone { get; set; }
 
        [Required(ErrorMessage = "Please enter your answer")]
        public bool? WillAttend { get; set; }
    }

Step 2: Add validation summary server control

<form id="rsvpform" runat="server">
        <strong><asp:ValidationSummary runat="server" 
ShowModelStateErrors="True" ID="validationSummary"/></strong>
        
            Your name:                       
...     </form>

Source: ASP.NET 4.5 Pro Apress – Chapter 1

 

asp.net · ebook

[ASP.NET] Calling a code-behind method

We can call a code behind method by using server-side evaluation syntax <%=.

Example:

In code behind, we have:

protected string GetYes()
        {
            var yesData = ResponseRepository.GetRepository().GetAllResponses()
                .Where(r => r.WillAttend.HasValue && r.WillAttend.Value);
 
            var html = new StringBuilder();
 
            foreach (var rsvp in yesData)
            {
                html.Append($"{rsvp.Name}{rsvp.Email}{rsvp.Phone}");
            }             
            return html.ToString();         
}

We can get the string value from aspx by following syntax in aspx:

<form id="form1" runat="server">
        <h2>RSVP Summary</h2>

        <h3>People who will attend:</h3>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                </tr>
            </thead>
            <tbody>
                <strong><%= GetYes() %></strong>
            </tbody>
        </table>
    </form>

Source: ASP.NET 4.5 Pro Apress – Chapter 1