How to get first day date and last day date of a week in jquery ?

If you want to get first day and last day of a week,  code is here :

 


var curr = new Date; // If you want of any date then just pass date in Date('08/22/2019')
        var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
        var last = first + 6; // last day is the first day + 6
        var firstday = new Date(curr.setDate(first)).toLocaleDateString();
        var lastday = new Date(curr.setDate(last)).toLocaleDateString();
        console.log(firstday );
        console.log(lastday );

This will give you Sunday as First Day and Saturday as last day
Tested on Chrome Browser Console :

Remove all li from ul in jquery

If you have a <ul> and <li> in <ul>, and if you want to clear or remove all li from <ul>, here jquery code to empty this <ul>

HTML Code :

<ul class=”attachmentList”>

<li>First</li>

<li>Second</li>

<li>Third</li>

</ul>

 

$('.attachmentList').empty();

Multiple email validations in multiple text boxes with comma separate email ids in Javascript

Before Form submit, if you have multiple text boxes for emails like To Email and Cc Email, and both text boxes having multiple email ids with comma separate, then before form submit you can add validation through JQuery or java script.

 

<!DOCTYPE html>
<html>
<body>

<form>
To Email: <textarea name=”ToEmail” id=”ToEmail”></textarea><br>
CC Email: <textarea name=”CCEmail” id=”CCEmail”></textarea><br>
<input type=”submit” value=”Submit”>
</form>
</body>
</html>

 


$('form').submit(function () {
        var ToEmail = $('#ToEmail').val();
        var CCEmail = $('#CCEmail').val();
        var validArray = [];
        var emails = ToEmail.replace(/\s/g, '').split(",");
        Array.prototype.push.apply(emails, CCEmail.replace(/\s/g, '').split(","));
        var valid = true;
        var regex = /^(([^&amp;amp;lt;&amp;amp;gt;()[\]\\.,;:\s@\"]+(\.[^&amp;amp;lt;&amp;amp;gt;()[\]\\.,;:\s@\"]+)*)|(\".+\"))@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        for (var i = 0; i &amp;amp;lt; emails.length; i++) {
            if (emails[i] == "" || !regex.test(emails[i])) {
                valid = false;
            }
            validArray.push(valid);
        }
        var isFalse = validArray.includes(false);
        if (isFalse == true) {
alert("Please enter emails in proper format !");
            return false;
        }
        else {
            return true;
        }
    });

Now Here an array will store comma separate email ids of first text box and then same array will append the more email ids from another text box, for this we have used :


Array.prototype.push.apply(emails, CCEmail.replace(/\s/g, '').split(","));

Above line of code will append second text box email ids into array, that already having values of first textbox.(email)

Note:- If you are working on ASP.NET MVC Razor then in Regex Expression you have to replace @ to @@, because @ will determine as razor syntex.

Sending Mail To Admin On USB Insertion or Removal In C#

Here is the c# console code to create a event watcher to monitor, if any usb attached or detached from PC.

Simple just create a console application in visual studio and install a package from nuget to import namespace System.Management.

Install-Package System.Management -Version 4.5.0

And Code is Bellow :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace USB
{
    class Program
    {
        public enum EventType
        {
            Inserted = 2,
            Removed = 3
        }

        static void Main(string[] args)
        {
            ManagementEventWatcher watcher = new ManagementEventWatcher();
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");

            watcher.EventArrived += (s, e) =>
            {
                string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
                EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));

                string eventName = Enum.GetName(typeof(EventType), eventType);

                Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);
                Console.WriteLine("Mail Sending...to admin"); //You can write your email code here
            };

            watcher.Query = query;
            watcher.Start();

            Console.ReadKey();
        }
    }
}




you can write your email sending code after Console.WriteLine(“{0}: {1} {2}”, DateTime.Now, driveName, eventName);

Editable Text Box In Jquery And Post Data to ASP.NET

 

Here i have a grid, and in grid i have a column with Quanity, so if i want to change this quantity with editable text box.

so Here will be Link tag and text box with some id and selectors.

And this will work if there will multiple editable textboxes are there in table grid.

Here First HTML Code

<a href="JavaScript:Void(0);" id="editqty">@item.Qty</a>
<input type="text" style="width:70px;display:none;" class="form-control" id="qtyValue" value="@item.Qty" data-value="@item.PKId" data-target="@item.Qty" />

So above is html code and only <a> tag will be shown on grid, and when you will click on Link then it will hide and text box will show.
In this jquery code all other text box in grid and all things will be same as previous.
Below is jquery code
$("a[id$='editqty']").each(function () {
$(this).on('click', function () {
$("input[type='text'][id$='qtyValue']").hide();
$("a[id$='editqty']").show();
$(this).next('input[type=text]').show();
$(this).next('input[type=text]').val($(this).html());
$(this).hide();
});
});

$("input[type='text'][id$='qtyValue']").blur(function () {

$(this).prev("a[id$='editqty']").show();
$(this).hide();

var prevValue = $(this).attr('data-target');
var savedValue = $(this).val().trim();
var id = $(this).attr('data-value');

if (prevValue != savedValue)

{

$.ajax({
cache: false,
type: "POST",
url: '@Url.Action("Index","Employee")',
data: { savedValue: savedValue, id: id },
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 401) {
window.location.href =  "Account/Login/";
}
}
});

}

}

Validate textbox only numeric or number in JQuery

If you want to validate text for for entering only number or numeric values then here is jquery/javascript code.(Tested)

Below Is for All text box on page

$(document).ready(function () {
            $("input[type='text']").keypress(function (e) {
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    return false;
                }
            });
        });

And if you want to apply on specific text box then you can use selecter ID or class as you wish.



$(document).ready(function () {
            $("#txtbox1").keypress(function (e) {
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    return false;
                }
            });
        });

Function For Comma separate string to Column in SQL Server

Here is a user defined function that we have created to convert comma separate string values to Table Column,
Mostly we use for IN statement in Select QUERY like

select * from Emp WHERE PKId IN(fn_SplitParameters('1,2,3',','))

CREATE FUNCTION [dbo].[fn_SplitParameters](@String varchar(max), @Delimiter char(1))           
returns @temptable TABLE (ID int,items varchar(max))           
as           
begin           
declare @idx int           
declare @slice varchar(max)           
 declare @ID int           
  set  @ID=0       
select @idx = 1           
if len(@String)&lt;1 or @String is null  return           
           
while @idx!= 0           
begin           
set @idx = charindex(@Delimiter,@String)           
set @ID=@ID+1  
if @idx!=0           
set @slice = left(@String,@idx - 1)           
else           
set @slice = @String     
if(len(@slice)&gt;0)      
insert into @temptable(ID,Items) values(@ID,@slice)           
set @String = right(@String,len(@String) - @idx)           
 if len(@String) = 0 break           
end       
return           
end