Category Archives: JavaScript

Insert Records in Salesforce by using JavaScript

In this article I’ll demonstrate how to insert record in Salesforce object by using javascript, in VF page without any standard or custom controller or by apex class.

By using AJAX Toolkit we can do this task easily. There are two types of AJAX Toolkit one is synchronous and another one is asynchronous call.

Here is a simple example of data insert using Javascript in Visualforce page. In below example I’m using synchronous call.
These are the steps to insert data using Javascript:

  1. Connecting to the AJAX Toolkit(By using login methods or getting Session_ID).
  2. Embedding the API methods in JavaScript.
  3. Processing the results.

Sample Code:

<apex:page id="pg">
    <script src="/soap/ajax/20.0/connection.js" type="text/javascript"></script>
		function insertAcc(){

			// Getting Session ID.
			sforce.connection.sessionId = "{!$Api.Session_ID}";

			//Creating New Account Record.
			var account = new sforce.SObject("Account");

			//Getting Account Name from inputText.
			account.Name = document.getElementById("pg:frm:pb:pbs:pbsi:txtName").value;

			//Create method 
			var result = sforce.connection.create([account]);

			//Getting result 
			if (result[0].getBoolean("success")) {
				alert("New Account is created with id " + result[0].id);
			else {
				alert("failed to create new Account " + result[0]);
	<apex:form id="frm">
		<apex:pageBlock title="Insert Account" tabStyle="Account" id="pb">
			<apex:pageBlockSection title="Account Name" columns="1" id="pbs">
				<apex:pageBlockSectionItem id="pbsi">
					<apex:outputLabel value="Name" />
					<apex:inputText title="Name" id="txtName" />
				<apex:commandButton onclick="return insertAcc();" value="Save"/>

Custom Label in JavaScript File

We use {!$Label.CustomLabelName}, when we call custom label in Visualforce page JavaScript function. But if we need to access custom labels in JavaScript file in static resource, then here is the way to get the custom label value.

Load the custom label in Visualforce Page before loading the static resource JavaScript file.

    window.$Label = window.$Label || {};
    $Label.MyCustomLable1 = '{!JSENCODE($Label.MyCustomLable1)}';
    $Label.MyCustomLable2 = '{!JSENCODE($Label.MyCustomLable2)}';

Use in JavaScript file.


Salesforce Check Permission Set in Custom Button


var result = sforce.connection.query("SELECT Id FROM PermissionSetAssignment WHERE PermissionSet.Name = 'Sample_Permission_Set' AND AssigneeId = '{!$User.Id}'");
var psAssignment = result.getArray("records");

if (psAssignment.length === 1) {
    //Write your logic
} else {
    alert('You don't have access to this feature.');

Select All Checkbox Using Javascript in Visualforce Page


public with sharing class Sample { 

    public List<AccountWrapper> accountWrapperList {get; set;}
    public Sample (){
        if(accountWrapperList == null) {
            accountWrapperList = new List<AccountWrapper>();
            for(Account a: [SELECT Id, Name From Account Limit 10]) {
                accountWrapperList.add(new AccountWrapper(a));
    public class AccountWrapper {
        public Account acc {get; set;}
        public Boolean isSelected{get; set;}
        public AccountWrapper(Account a) {
            acc = a;
            isSelected = false;

Visualforce Page:

<apex:page controller="Sample" sidebar="false" showHeader="false">
    <script type="text/javascript">
        function selectAllCheckboxes(obj,InputID){
            var inputCheckBox = document.getElementsByTagName("input");    
            for(var i=0; i<inputCheckBox.length; i++){          
                    inputCheckBox[i].checked = obj.checked;
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accountWrapperList}" var="a" id="table" title="All Accounts">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                    <apex:inputCheckbox value="{!a.isSelected}" id="inputId"/>
                <apex:column value="{!a.acc.Name}" />


JavaScript Array

An array is a collection of data values. we can store more than one values and retrieve values as per index. Also, we can store lists an array. Array indexes are zero-based, the first element in the array is 0, the second is 1, and so on.

Array Example:
var fruits = ["Apple", "Orange", "Banana", "Mango"];

Array Properties:
constructor: Returns the function that created the Array object’s prototype.
length: Sets or returns the number of elements in an array.
prototype: Allows you to add properties and methods to an Array object.

Array Methods:

concat(): Joins two or more arrays, and returns a copy of the joined arrays.

copyWithin(): Copies array elements within the array, to and from specified positions.

entries(): Returns a key/value pair Array Iteration Object.

every(): Checks if every element in an array pass a test.

fill(): Fill the elements in an array with a static value.

filter(): Creates a new array with every element in an array that pass a test.

find(): Returns the value of the first element in an array that pass a test.

findIndex(): Returns the index of the first element in an array that pass a test.

forEach(): Calls a function for each array element.

from(): Creates an array from an object.

includes(): Check if an array contains the specified element.

indexOf(): Search the array for an element and returns its position.

isArray(): Checks whether an object is an array.

join(): Joins all elements of an array into a string.

keys(): Returns a Array Iteration Object, containing the keys of the original array.

lastIndexOf(): Search the array for an element, starting at the end, and returns its position.

map(): Creates a new array with the result of calling a function for each array element.

pop(): Removes the last element of an array, and returns that element.

push(): Adds new elements to the end of an array, and returns the new length.

reduce(): Reduce the values of an array to a single value (going left-to-right).

reduceRight(): Reduce the values of an array to a single value (going right-to-left).

reverse(): Reverses the order of the elements in an array.

shift(): Removes the first element of an array, and returns that element.

slice(): Selects a part of an array, and returns the new array.

some(): Checks if any of the elements in an array pass a test.

sort(): Sorts the elements of an array.

splice(): Adds/Removes elements from an array.

toString(): Converts an array to a string, and returns the result.

unshift(): Adds new elements to the beginning of an array, and returns the new length.

valueOf(): Returns the primitive value of an array.