Wednesday 26 April 2017

SQL Query interview question part - 3

Here I just created Employee table and on the basis of Write Some common query  which generally asking in interview.

CREATE TABLE [dbo].[tblEmployee](
[EmployeeID] [int] IDENTITY(1,1)  NOT NULL,
[LastName] [nvarchar](20) NOT NULL,
[FirstName] [nvarchar](10) NOT NULL,
[Title] [nvarchar](30) NULL,
[BirthDate] [datetime] NULL,
[HireDate] [datetime] NULL,
[Address] [nvarchar](60) NULL,
[City] [nvarchar](15) NULL,
[Country] [nvarchar](15) NULL
)
GO

 SELECT * FROM [tblEmployee]


1. Ques: List of all employee from tblEmployee table whose "FirstName" start with latter 'a'.

Answer: SELECT * FROM [tblEmployee] WHERE FirstName like 'a%'



2. Ques:  List of all employee from tblEmployee table whose "FirstName" start with any single character between 'a-j'.

Answer: SELECT * FROM [tblEmployee] WHERE FirstName like '[a-j]%'



3.Ques: Get only Year part of "HireDate".
Answer:SELECT DATEPART(YEAR, HireDate) FROM [tblEmployee]


Thursday 20 April 2017

ViewModel Example In MVC ASP.Net With bootstrap

What is ViewModel in MVC ?
Answer: ViewModel contain fields that are represented in the view.It allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view.

In this tutorials i am going to showing demo how to use of ViewModel class in MVC ASP.Net.





In this demo I used flowing version of framework
  • Using Visual studio 2012 MVC 4 version.
  • Sql Server 2012.
  • AutoMapper DLL references  
  • For css using bootstrap and jquery
  • Entity framework (4.4.0.0) references  


Step:1
Create a Three table in sql server database. The three table name as

  • y_category_master
  • y_vendor_master
  • y_Product_Master

CREATE TABLE [dbo].[y_category_master] (
    [CategoryID]   INT          IDENTITY (1, 1) NOT NULL,
    [CategoryName] VARCHAR (50) NULL,
    CONSTRAINT [PK_y_category_master] PRIMARY KEY CLUSTERED ([CategoryID] ASC)
);

GO
CREATE TABLE [dbo].[y_vendor_master] (
    [venderId]   INT          IDENTITY (1, 1) NOT NULL,
    [venderName] VARCHAR (50) NULL,
    CONSTRAINT [PK_y_vendor_master] PRIMARY KEY CLUSTERED ([venderId] ASC)
);

GO
CREATE TABLE [dbo].[y_Product_Master] (
    [ProductId]  INT             IDENTITY (1, 1) NOT NULL,
    [Name]       VARCHAR (50)    NULL,
    [Price]      DECIMAL (18, 2) NULL,
    [CategoryID] INT             NULL,
    [VendorID]   INT             NULL,
    CONSTRAINT [PK_y_Product_Master] PRIMARY KEY CLUSTERED ([ProductId] ASC),
    CONSTRAINT [FK_y_Product_Master_y_category_master] FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[y_category_master] ([CategoryID]),
    CONSTRAINT [FK_y_Product_Master_y_vendor_master] FOREIGN KEY ([VendorID]) REFERENCES [dbo].[y_vendor_master] ([venderId])
);

GO
CREATE NONCLUSTERED INDEX [IX_FK_y_Product_Master_y_category_master]
    ON [dbo].[y_Product_Master]([CategoryID] ASC);

GO
CREATE NONCLUSTERED INDEX [IX_FK_y_Product_Master_y_vendor_master]
    ON [dbo].[y_Product_Master]([VendorID] ASC);


Step:2 Create Entity Data Model to connect to database

Right-click on your project in Solution Explorer then click on ADD New ADO.NET Entity Data Model. name as "Product.edmx". Create database connection with the help of Entity framework
And drag & drop all three table in Entity modal design.



Step:3 Reffrence the AutoMapper DLL to your projects

Right Click on your project in Solution Explorer then select Manage NuGet Packages.search AutoMapper and install it.


Step:4 Add Model class

Here I created product modal partial class in Modal Folder with name Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ViewModelProj.Models
{
    public partial class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int CategoryID { get; set; }
        public int VendorID { get; set; }
 
    }

    public partial class Product
    {
        public string CategoryName { get; set; }
        public string VendorName { get; set; }
    }
}

Step:5 Add ViewModel class

Create new folder in project View_Model. In this folder right click and add class with name ProductViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ViewModelProj.Models;
using System.Web.Mvc;

namespace ViewModelProj.View_Model
{
    public class ProductViewModel
    {
        public Product product { get; set; }
        public SelectList VendorList { get; set; }
        public SelectList CategoryList { get; set;}
    }
}


Step:6 Add Controller 
In Controller folder open the 'HomeController' and put the code given bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewModelProj.Models;
using ViewModelProj.View_Model;
using AutoMapper;

namespace ViewModelProj.Controllers
{
    public class HomeController : Controller
    {  
        TestEntities db = new TestEntities();
        public ActionResult Index()
        {
            List<Product> ProVModal = new List<Product>();
            using (TestEntities dc = new TestEntities())
            {
                var v = (from a in dc.y_Product_Master
                         join b in dc.y_category_master on a.CategoryID equals b.CategoryID
                         join c in dc.y_vendor_master on a.VendorID equals c.venderId
                         select new Product
                         {
                             Name = a.Name,
                             Price= (decimal)a.Price,
                             CategoryName= b.CategoryName,
                             VendorName = c.venderName
                         }).OrderBy(x => x.Name).ToList();
                ProVModal = v;
             
            }
            return View(ProVModal);
        }

        public ActionResult AddProduct()
        {
            ProductViewModel objProductViewModel = new ProductViewModel();
            var category = db.y_category_master;
            var vendor = db.y_vendor_master;

            objProductViewModel.CategoryList = new SelectList(category, "CategoryID", "CategoryName");
            objProductViewModel.VendorList = new SelectList(vendor, "venderId", "venderName");

            return View(objProductViewModel);
        }

        public ActionResult SaveProduct(ProductViewModel objProductViewModel)
        {        
            Mapper.CreateMap<Product,y_Product_Master>();
            y_Product_Master obj1 = Mapper.Map<Product, y_Product_Master>(objProductViewModel.product);
            db.y_Product_Master.Add(obj1);
            db.SaveChanges();

            return View();
        }

    }
}

Step:7 Adding View
Add three View against the controler. I added three view which given bellow as

Index.cshtml : This View showing all the product list in grid.
AddProduct.cshtml : This View use for add new product in system.
SaveProduct.cshtml : This View use shwoing Message to successfully product added.

@model IEnumerable<ViewModelProj.Models.Product>
@{
    ViewBag.Title = "Index";
}

<link href="~/Content/Bootstrap/bootstrap.css" rel="stylesheet" />

<h2 style="margin-left: 20px">All Product List</h2>
<p style="margin-left: 20px">
    @Html.ActionLink("Create New", "AddProduct")
</p>

 <div class="row" style="margin-left: 20px">
     <div class="form-group">
            <div class="col-md-6">
<table  class="col-md-12 table-bordered table-striped table-condensed cf" style="margin-left: 20px">
    <thead class="cf" style="border: 1px solid #ccc;">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CategoryName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.VendorName)
        </th>
        <th></th>
    </tr>
        </thead>
    <tbody style="border: 1px thin black">
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.VendorName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}
         </tbody>
</table>
</div>
         </div>
     </div>


AddProduct.cshtml
@model ViewModelProj.View_Model.ProductViewModel

@{
    ViewBag.Title = "AddProduct";
}

<h2 style="margin-left: 20px">AddProduct</h2>

@using (Html.BeginForm("SaveProduct","Home",FormMethod.Post)) {
    @Html.ValidationSummary(true)

    <div class="row" >
         <div class="col-xs-12 col-sm-12 col-md-12 ">
                    &nbsp;
                </div>
         <div>    
    </div>

         <div class="col-md-12">
        <table style="width:40%; margin-left: 20px" class="table-condensed" border="1">
        <tr>
            <td>
                <div class="row" >
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                        Product Name:                    
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.TextBoxFor(model => model.product.Name, new { @class="form-control", placeholder="Please Enter Product Name"})
                        @Html.ValidationMessageFor(model => model.product.Name, "Please Enter ProductName", new { @class = "text-danger" })
                    </div>
                </div>
              </div>

                <div class="row" >
               <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                        Price:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">

                        @Html.TextBoxFor(model => model.product.Price, new { @class="form-control", placeholder="Please Enter product Price"})
                        @Html.ValidationMessageFor(model => model.product.Price, "Please Enter product Price", new { @class = "text-danger" })
                     </div>
                </div>
                    </div>

                <div class="row" >
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                     Select Category:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.product.CategoryID, Model.CategoryList, "-- Select One --" , new { @style = "width:100%", @class="dropdown-header" })
                        @Html.ValidationMessageFor(model => model.CategoryList, "Please Select Department Location", new { @class = "text-danger" })
                     </div>
                </div>
                    </div>

                <div class="row" >
                 <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                      Select Vendor:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.product.VendorID, Model.VendorList, "-- Select One --" , new { @style = "width:100%", @class="dropdown-header" })
                        @Html.ValidationMessageFor(model => model.VendorList, "Please Select Department Location", new { @class = "text-danger" })
                     </div>
                </div>
                     </div>

                <div class="row" >
                <div class="col-xs-12 col-sm-12 col-md-12 " style="align-items:center">
                    <br />
                    <br />
                 
                     <button type="submit"  value="SAVE"  class="btn btn-success btn-group-lg"  >
                            <span class="glyphicon glyphicon-plus"></span> SAVE
                      </button>      
                </div>
              </div>
            </td>
        </tr>
    </table>
 </div>
</div>
}
 <br />
<div>
    <div class="row" >
                <div class="col-xs-12 col-sm-12 col-md-12 " style="margin-left: 20px" >
                           @Html.ActionLink("Back to List", "Index")
                    </div>
        </div>
    </div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


SaveProduct.cshtml
@{
    ViewBag.Title = "SaveProduct";
}

<h2>Product Saved Successfully</h2>

<p>
    @Html.ActionLink("List of Prduct", "Index")
</p>


Conclusion : 
                     In this way you can use viewmodal class in mvc. Hope this article will helpful for you.

Tuesday 18 April 2017

HTML5 interview questions Part -3

1. Ques: What is HTML Local Storage ?
Answer:
With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. HTML5 Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.


2. Ques: What is the Geolocation API and why would you use it?
Answer:
HTML Geolocation API is used to get the geographical position of a user.Since this can compromise privacy, the position is not available unless the user approves it.

The HTML5 Geolocation API allows users to share their location with a website. This is a useful feature that asks a user permission to share their latitude and longitude with the app to receive the benefits of location-aware features, such as the ability to present the landing page of the business closest to the user’s location.

Sunday 16 April 2017

Bootstrap Interview Question Part - 1

1. Ques: What is Bootstrap ? Why we use Bootstrap ?
Answer:
Bootstrap is an open-source Javascript framework developed by the team at Twitter.  It is a combination of HTML, CSS, and Javascript code designed to build user interface components.It used for building the rich web applications with minimal effort. Bootstrap was also programmed to support both HTML5 and CSS3.  Also it is called Front-end-framework.Current Version of Bootstrap is v3.3.7

Bootstrap is a free collection of tools for creating a websites and web applications.It powerful mobile first front-end framework for faster and easier web development.

It contains HTML and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions.

Some Reasons for programmers preferred Bootstrap Framework
  • Easy to get started
  • Great grid system
  • Base styling for most HTML elements(Typography,Code,Tables,Forms,Buttons,Images,Icons)
  • Extensive list of components
  • Bundled JavaScript plugins
  • Browser Support
  • Responsive features
  • Mobile-first approach


2. Ques: What are the key components of Bootstrap?
Answer:
CSS : It comes with plenty of CSS files
Scaffolding : It provides a basic structure with Grid system , link styles and background
Layout Components : List of layout components
JavaScript Plugins: It contains many jQuery and JavaScript plugins
Customize: To get your own version of framework you can customize your components
glyphicons: a font (an icon font set)


3. Ques: Explain Bootstrap Grid System?
Answer:
Bootstrap's grid system allows up to 12 columns across the page. Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. It includes predefined classes for easy layout options, as well as powerful for generating more semantic layouts.


4. Ques:  What are different types of layout available in Bootstrap?
Answer:
  • Fluid Layout: Fluid layout adapts itself to different browser. Means design automatic adjust according to browser size.
  • Fixed Layout:Fixed layout doesn’t adapts itself to different browser but it can be responsive.


5 . What do you mean by responsive layout?
Answer:
Responsive layout which is able to adapt itself to different sizes as well, but when resizing, the number of columns changes according to the available space.responsive layout it is easy reading and navigation with a minimum of resizing, panning, and scrolling across a wide range of devices (from mobile phones to desktop computer monitors)


6 . What is Jumbotron?
Answer:
Jumbotron is used for content that you want to highlight like some slogan OR marketing headline.
Its indicates a big box for calling extra attention to some special content or information.
A jumbotron is displayed as a grey box with rounded corners. It also enlarges the font sizes of the text inside it.


7 . What is Bootstrap Container in Bootstrap?
Answer:
container is used to set the content's margins dealing with the responsive behaviors of your layout. It contains the row elements and the row elements are the container of columns (known as grid system).
The container class is used to create boxed content.

There are two container classes in Bootstrap:
container
container-fluid

Thursday 13 April 2017

Paging and Sorting in MVC4 Using PagedList



In this tutorials i am going to showing Paging and Sorting in MVC4 Using PagedList . For this  Am using 

Step i am going to do here

  1. using Visual studio 2012 MVC 4 version.
  2. Sql Server 2012.
  3. For css using bootstrap and jquery
  4. Entity framework (4.4.0.0) references  
  5. Reffrence the PagedList.mvc in project

Step:1 

Create a table in sql server database and create store procedure (script given bellow)

CREATE TABLE [dbo].[DepartmentLocation](
[LocationId] [int] IDENTITY(1,1) NOT NULL,
[LocationName] [nvarchar](50) NULL,
[Address] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[Pincode] [nvarchar](50) NULL,
[PhoneNo] [nvarchar](50) NULL,
[CountryID] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED 
(
[LocationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Create PROCEDURE [dbo].[Sp_Get_DepartmentList]
AS
Begin
SELECT DL.LocationId,
      DL.LocationName,
  DL. Address,
  DL.City,
  DL.Pincode,
  DL.CountryID,
      C.CountryName
from Country C inner join DepartmentLocation DL On C.CountryID=DL.CountryID

End

Step:2 Create Entity Data Model to connect to database

Right-click on your project in Solution Explorer then click on ADD New ADO.NET Entity Data Model. name as "MyContactBookEntities" ...



Step:3 Reffrence the Pagedlist dll and css to your projects

on your project in Solution Explorer then select Manage NuGet Packages.search Pagedlist.mvc  and install it.





Step:3

Add new Controller with name 'DepartmentLocationController.cs' and put the code given bellow.

DepartmentLocationController.cs

using AutoMapper;
using MVCContactBook.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace MVCContactBook.Controllers
{
      public class DepartmentLocationController : BaseController
          {
           public ActionResult GetDepartmentLocationList(string sortOn, string orderBy, string                                pSortOn, int? page)
           {          
            int recordsPerPage = 10;
            if (!page.HasValue)
            {
                page = 1; // set initial page value
                if (string.IsNullOrWhiteSpace(orderBy) || orderBy.Equals("asc"))
                {
                    orderBy = "desc";
                }
                else
                {
                    orderBy = "asc";
                }
            }          
            if (!string.IsNullOrWhiteSpace(sortOn) && !sortOn.Equals(pSortOn, StringComparison.CurrentCultureIgnoreCase))
            {
                orderBy = "asc";
            }

            ViewBag.OrderBy = orderBy;
            ViewBag.SortOn = sortOn;
        
            MyContactBookEntities dc = new MyContactBookEntities();
            var list = dc.Sp_Get_DepartmentList().AsQueryable();
                     
            switch (sortOn)
            {
                case "LocationName":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.LocationName);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.LocationName);
                    }
                    break;
                case "Address":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.Address);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.Address);
                    }
                    break;
                case "City":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.City);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.City);
                    }
                    break;                
                default:
                    list = list.OrderBy(p => p.LocationId);
                    break;
            }

            var finalList = list.ToList().ToPagedList(page.Value, recordsPerPage);
            return View(finalList);
        }
 }

}

Step:4

Add View against the action method name 'GetDepartmentLocationList' and put the code given bellow.

View
GetDepartmentLocationList.cshtml

@using PagedList;
@using PagedList.Mvc;
@model IPagedList<MVCContactBook.Sp_Get_DepartmentList_Result>
@{
    ViewBag.Title = "GetDepartmentLocationList";
}

<script src="~/Scripts/jquery-3.1.1.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script>
        $(document).ready(function () {
            hideColumn = function (column) {
                $('tr').each(function () {
                    $(this).find('td,th').eq(column).hide();
                });
            };
            hideColumn(0);

        });
    </script>


<h2>Department Location List</h2>

<p>
    @Html.ActionLink("Create New", "AddNewLocation")
</p>

 <div id="no-more-tables">
<table  class="col-md-12 table-bordered table-striped table-condensed cf">
     <thead class="cf" style="border: 1px solid #ccc;">
    <tr>
        <th  class="numeric">
            @*@Html.DisplayNameFor(model => model.LocationId)*@
        </th>
        <th  style="text-align:center;">
            
            @Html.ActionLink("Location", "GetDepartmentLocationList", new { sortOn ="LocationName", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
         <th style="text-align:center;">
            @Html.ActionLink("Address", "GetDepartmentLocationList", new { sortOn ="Address", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
         <th style="text-align:center;">
            @Html.ActionLink("City", "GetDepartmentLocationList", new { sortOn ="City", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
        <th style="text-align:center;">
            Pincode
        </th>
      
        <th style="text-align:center;">
            Country
        </th>
        <th>Edit</th>
        <th>Delete</th>
    </tr>
         </thead>
      <tbody style="border: 1px thin black">

         
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.LocationId)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.LocationName)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.Pincode)
        </td>
      
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.CountryName)
        </td>
        <td style="text-align:center;">
            @Html.ActionLink(" ", "Edit", new { id = item.LocationId }, new { @class = "glyphicon glyphicon-edit", title = "Edit" }) 
            </td>

            <td style="text-align:center;">
            @Html.ActionLink(" ", "Delete", new { id = item.LocationId }, new { @class = "glyphicon glyphicon-trash", title = "Delete" })        
            
        </td>
    </tr>

}
          </tbody>
 </table>
    <div class="pagedList">
        @Html.PagedListPager(Model, page => Url.Action("GetDepartmentLocationList", new { page,
sortOn = ViewBag.SortOn, orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn }), PagedListRenderOptions.ClassicPlusFirstAndLast)
    </div>
   </div>

Monday 10 April 2017

jQuery attribute Selector

  • The [attribute] selector selects each element with the specified attribute.
Syntax

$('[attribute]')
$('[attribute="value"]')

Ex:
$('[title]') :-  Selects all elements that have title attribute.
$('div[title]'):-  Selects all div elements that have title attribute.
$('[title="divtitle"]') :-  Selects all elements that have title attribute value - divtitle.
$('div[title="divtitle"]') :-  Selects all div elements that have title attribute value - divtitle.
$('[title^='Ajay']') :- Selects  all elements with a title attribute value starting with "Ajay".
$("[title~='welcome']") :- Selects  all elements with a title attribute value containing the specific word "welcome".
$("[title*='welcome']") :- Selects all elements with a title attribute value containing the word "welcome".


$('[title]') :-  Selects all elements that have title attribute.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
        $(document).ready(function () {
            $('[title]').css('border', '5px solid red');
        });
    </script>

  </head>
      <body>    
      <div title="dvTitle">
        DIV with Title
    </div>
    <br />
    <div title="dvTitle1">
        DIV with another Title
    </div>
      <span title="spanTitle">
        SPAN element
    </span>
    <p>I live in Mumbai.</p>
    </body>
</html>

output:



$('div[title]'):-  Selects all div elements that have title attribute.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
        $(document).ready(function () {
            $('div[title]').css('border', '5px solid red');
        });
    </script>

  </head>
      <body>    
      <div title="dvTitle">
        DIV with Title
    </div>
    <br />
    <div title="dvTitle1">
        DIV with another Title
    </div>
      <span title="spanTitle">
        SPAN element
    </span>
    <p>I live in Mumbai.</p>
    </body>
</html>

output:

Thursday 6 April 2017

JQuery interview questions Part - 4

1. Ques: Write a code for get the text value of a selected option?

<select id="ddl">
   <option value="1">Employee</option>
   <option value="2">Manager</option>
   <option value="3">HR</option>
   <option value="4">Teacher</option>
</select>

Answer: $("#pcdsselect").val();


2. Ques: Write a code for check or unchecked a checkbox input or radio button?
Answer:
$('#pcds').attr('checked', true);
$('#pcds').attr('checked', false);


3. Ques: How do You disable or enable a form element?
Answer:
// Disable #pcds
$('#pcds').attr('disabled', true);
// Enable #pcds
$('#pcds').attr('disabled', false);


4. Ques: What is the Document Ready Event syntax ?
Answer:
$(document).ready(function(){

});

5. Ques: Write a code for hide method of different selector ?
Answer:
<p id="myherder" class="myherderclass">This is a paragraph Element in html.</p>

$(this).hide() -its  hides the current element.

$("p").hide() -its   hides all <p> elements.

$(".myherderclass").hide() -its  hides all elements with class="myherder".

$("#myherder").hide() - its  hides the element with id="myherder".


6. Ques: Explain the code syntax and example of  hide() and show() method in Jquery ?
Answer:
Syntax:  $(selector).hide(speed,callback);

Ex:
<p id="ParaId">This is a paragraph Element in html.</p>

$("#ParaId").click(function(){
    $("p").hide();
});

$("#ParaId").click(function(){
    $("p").show();
});

7. Ques: What are the use of jQuery toggle() method ?
Answer:
toggle() method just toggle between the hide() and show() methods in jQuery ?
Ex:
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle();
    });
});
</script>