Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, 15 August 2019

Understanding the Spread Operator in JavaScript



Today we are going to discuss about the ES6 feature of Spread operator, Based on MDN docs.

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Syntax for how to use:

For function calls:

myFunction(...iterableObj);

For array literals or strings:

[...iterableObj, '4', 'five', 6];

For object literals (new in ECMAScript 2018):

let objClone = { ...obj };


Example of Replace of apply:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

concatenate arrays

var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5]


Spread in object literals

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }

Monday, 9 February 2015

How to clear/reset dropdownlist Using JQuery

Hi Folks,

While Working with Drodownlist's today i faced one problem it is not clearing the Old data.
Then realised to clear the data except default value using jQuery

My asp.net MVC Razor Code:



@Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Cities, "--Choose Your City--", new { @id = "ddlCity", @style = "width:200px;" })

and Javascript section as below



@section Scripts {
    <script type="text/javascript">
function GetCities(_Id) {              
            var ddlcity = $("#ddlCity");   
            $.ajax({
                cache: false,
                type: "GET",
                url: '@Url.Action("GetCities", "Admin")',
                data: { "id": _Id },
                success: function (data) { 


   //Clearing the Data except first default value.

                    ddlcity.children('option:not(:first)').remove();
                    $.each(data, function (id, option) {
                                      ddlcity.append($('<option></option>').val(option.id).html(option.name));
                    });
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve Cities.');

                }
            });
        }
    </script>
}