Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, March 6, 2021

Postman Pre-Request: How to get Auth Token at Collection level?

Prerequisite:

You need latest Postman application installed.

You can download Postman application from here.

Steps:

  • Create a new collection.
  • Open the collection and click on Pre-request Script.
  • Paste below code there:
pm.sendRequest({
url: [AUTH_TOKEN_URL],
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "client_id", value: [CLIENT_ID_VALUE] },
{ key: "client_secret", value: [CLIENT_SECRET_VALUE] },
{ key: "resource", value: [RESOURCE_VALUE] },
{ key: "grant_type", value: [GRANT_TYPE_VALUE] }
]
}
}, function (err, response) {
if (null != err) {
const jsonResponse = response.json();
// Save token to env variable.
pm.environment.set('env_auth_token', jsonResponse.token);
} else {
console.log("Cannot fetch Auth token");
pm.environment.set('env_auth_token', '');
}
});

  • Replace all values as per your requirements.

Sunday, June 11, 2017

Install node.js using NVM and Homebrew on Mac OS X

Reference: http://dev.topheman.com/install-nvm-with-homebrew-to-use-multiple-versions-of-node-and-iojs-easily/
Less than a month ago, iojs was released (multiple releases followed) and 6 days ago, the v0.12.0 of node was released.
I still had the same v0.10.x (can’t remember the patch 🙂 ) of node on my computer I installed a few months ago … As a nodejs developer, I decided it was time to get rid of my old version and switch to nvm so that I could test my projects (websites and node modules) on different engines and versions – moreover not to be stuck in the case some module should only work on one or an other …
This post is more a reminder for future me when I’ll make the install again, though it could help some people.
First, you’ll need Homebrew. If you’re a MacPorts user (or a Linux user), I assume it’s nearly the same, you may even have your own way which is faster and better, no need to troll 😉 – for Windows users, you have some alternatives.
Start by :
brew update
brew install nvm
mkdir ~/.nvm
nano ~/.bash_profile
In your .bash_profile file (you may be using an other file, according to your shell), add the following :
export NVM_DIR=~/.nvm
source $(brew --prefix nvm)/nvm.sh
Back to your shell, activate nvm and check it (if you have other shells opened and you want to keep them, do the same) :
source ~/.bash_profile
echo $NVM_DIR
Now, you can install node :
nvm install 0.12
From now on, you’re using the v0.12.x of node on this shell, you can install your global dependencies such as grunt-cli (they will be tied up to this version of node).
You may want to install other versions, just do :
nvm install 0.10
nvm install iojs
...
You’ll have to npm install -g your global dependencies for each version.
Switch of node version with nvm use 0.10 (more infos here).
To have a node activated by default (not to have to nvm use on each new shell), run this (stable being the id of the version):
nvm alias default stable
Now, you can run multiple versions of node on your computer.
Sources :

Saturday, October 31, 2015

JQuery: Using Draggable control from JQuery

Draggable:

Below JSFiddle demo provides simple way to drag drop <div> around. It is very simple code and can be done easily using JQuery.
For more details visit JQuery website i.e. http://jqueryui.com/draggable/
Below is JSFiddle link where you can play with Draggable control.

JSFiddle:

Thursday, October 29, 2015

JavaScript: Opening HTML dropdown panel on MouseOver using JavaScript.

There could be a scenario where you have to open Dropdown panel on ‘mouseover’. It could become more irritating if you don't do it right. I got a JavaScript method to do that.

The code is below and demo could be seen here. (https://jsfiddle.net/SiddharthMishra/kzdkpmvq/1/embedded/result/)

You can play with it by using JSFiddle.

JSFiddle:


HTML Code

We have created a simple HTML Dorpdown element here.

<select id="actionList">
       <option action="">ACTIONS</option>
       <option action="add">ADD NEW</option>
<option action="edit">EDIT</option>
</select>


JavaScript Code: 

We will add JavaScript methods to ‘ onmouseover ’ and ‘onmouseleave’ events.

 
var actionList = document.getElementById("actionList");

actionList.onchange = 
function () { templateAction(templateActionList); }

actionList.onmouseover = 
function () { selectElementMouseover(actionList); }

actionList.onmouseleave = 
function () { selectElementMouseleave(actionList); }

function selectElementMouseover(element) {
    fireEvent(element, "mousedown");
    fireEvent(element, "mouseup");
}
 
function selectElementMouseleave(element) {
    fireEvent(element, "mousedown");
}


Now below method will take care of the rest:
// To fire any event from JavaScript.
function fireEvent(node, eventName) {
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9) {
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }
 
    if (node.dispatchEvent) {
        var eventClass = "";
 
        // Different events have different event classes.
        switch (eventName) {
            case "click"// 'click' works correctly in Safari. 
                          // For other we should use 'mousedown' or 'mouseup'.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;
 
            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;
 
            default:
                throw "fireEvent: Couldn't find an event class for event '" 
                        + eventName + "'.";
                break;
        }
        var event = doc.createEvent(eventClass);
 
        var bubbles = eventName == "change" ? false : true;

        // All events created as bubbling and cancelable.
        event.initEvent(eventName, bubbles, true); 
 
        event.synthetic = true
        node.dispatchEvent(event, true);
    } else if (node.fireEvent) {
        var event = doc.createEventObject();
        event.synthetic = true
        node.fireEvent("on" + eventName, event);
    }
};


Reference: http://jsfiddle.net/mendesjuan/rHMCy/4/

Tuesday, November 5, 2013

JavaScript to validate Price input into a TextBox

Guys, first time in my life I am writing JavaScript for one of my project. I need a client side validation for an input into asp:TextBox.
I wrote a JavaScript function that would, actually, take whole element as object and use a regex to match the input with a pattern.
I learned that we don’t need to create an object of a RegEx() as we do in C#.
A “var” variable has “match” function that will use regex pattern to match the input.
Below is the javascript function that I wrote to validate my input.

<script language="javascript">
    function validatePrice(textBoxId) {
        var textVal = textBoxId.value;
        var regex = /^(\$|)([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$/;
        var passed = textVal.match(regex);
        if (passed == null) {
            alert("Enter price only. For example: 523.36 or $523.36");
            textBoxId.Value = "";
        }
    }
</script>


I wanted to fire the validation after I lost a focus on text box. To achieve this I did Google and went through all Form, Window etc type of event described at http://www.w3schools.com/tags/ref_eventattributes.asp . I used “onblur” event which is as same as OnLostFocus() in most of the WinForm controls.

<asp:TextBox ID="TextBox19" runat="server" Visible="False" Width="183px"
      onblur="javascript:return validatePrice(this);"></asp:TextBox>


This is my first javascript function. There may be best chance to improvise it. Please post your comments with changes.
Thanks & Enjoy!

Tuesday, April 3, 2012

Check/Uncheck checkboxes in GridView using JavaScript

Reference :- http://wiki.asp.net/page.aspx/281/check-uncheck-checkboxes-in-gridview-using-javascript/

The question regarding how to check/uncheck CheckBoxes within a GridView control using JavaScript has been asked many times. Here is a quick reference you can follow.

First we have the .aspx markup.

<script type="text/javascript">
function SelectAll(id) {
var frm = document.forms[0];
for (i=0;i<frm.elements.length;i++) {
if (frm.elements[i].type == "checkbox") {
frm.elements[i].checked = document.getElementById(id).checked;
}
}
}
</script>
<!-- assuming that SqlDataSource1 is the datasource for my GridView -->
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>

Next we have the code-behind in both VB and C#

VB

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.Header) Then
'adding an attribute for onclick event on the check box in the header
'and passing the ClientID of the Select All checkbox
DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).Attributes.Add("onclick", "javascript:SelectAll('" & _
DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).ClientID & "')")
End If
End Sub

C#

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header) {
//adding an attribute for onclick event on the check box in the header
//and passing the ClientID of the Select All checkbox
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
}
}

The example above is fantastic, but there are a couple things that could be improved.

  1. The JavaScript Pseudo Protocol (Javascript:your method here) should be avoided, it's a fragment from the old Netscape days. Today there are better alternatives
  2. In this case we probably don't need the server-side portion altogether.

An excerpt about the JavaScript Pseudo Protocol:

"The javascript: pseudo-protocol should not be used in event handlers like onclick. It should only be used in attributes that contain a URL, for example in the href attribute of <a> elements and the action attribute of <form> elements. You can also use it to make bookmarlets." - Common JavaScript Mistakes

Another solution the .aspx markup:

<script type="text/javascript">
// Let's use a lowercase function name to keep with JavaScript conventions
function selectAll(invoker) {
// Since ASP.NET checkboxes are really HTML input elements
// let's get all the inputs
var inputElements = document.getElementsByTagName('input');
for (var i = 0 ; i < inputElements.length ; i++) {
var myElement = inputElements[i];
// Filter through the input types looking for checkboxes
if (myElement.type === "checkbox") {
// Use the invoker (our calling element) as the reference
// for our checkbox status

myElement.checked = invoker.checked;
}
}
}
</script>
<!-- assuming that SqlDataSource1 is the datasource for my GridView -->
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" OnClick="selectAll(this)" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>

Thursday, February 24, 2011

Javascript Enable or Disable control on CheckBox checked

If you want to enable disable asp.net controls on click event of checkbox control then here is the solution.
The solution will work for any control.
What we have to do is, just get the controls to be enable and disabled using getElementById by putting their client id as an argument.


Javascript:-
javascript called by checkbox given below.

CheckBox control calling javascript.