Rectangle 27 106

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.

Example without using the apply method:

function a(...args){
  b(...args);
  b(6, ...args, 8) // You can even add more elements
}
function b(){
  console.log(arguments)
}

a(1, 2, 3)

Note This snippet returns a syntax error if your browser still uses ES5.

console.log()

In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters

This is a very nice operator and I'm really looking forward to use it. However, it won't happen yet. The only browser that already supports spread operator is FF at the moment. See the compatibility table for a complete, up to date data: kangax.github.io/compat-table/es6/#spread_%28...%29_operator

Why shouldn't it be used? It's relatively easy to transpile with babel, you get all of the new features, and much more compatibility with older browsers.

Passing arguments forward to another javascript function - Stack Overf...

javascript
Rectangle 27 6

Here is a small plugin I made to allow you to do exactly this, it also works on multiple background images and multiple elements:

or go straight to the plugin code:

So just include the plugin and then call it on the element:

Obviously download the plugin and store it on your own hosting.

By default it adds an additional "bg-loaded" class to each matched element once the background is loaded but you can easily change that by passing it a different function like this:

<script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
<script type="text/javascript">
   $('body').bgLoaded({
      afterLoaded : function() {
         alert('Background image done loading');
      }
   });
</script>

Here is a codepen demonstrating it working.

javascript - How can I check if a background image is loaded? - Stack ...

javascript jquery
Rectangle 27 4

I've tried Sam's version first. Good idea, but it causes there to be multiple elements in the form with the same name. If you use any javascript that finds elements based on name, it will now return an array of elements.

html - Post the checkboxes that are unchecked - Stack Overflow

html forms post checkbox
Rectangle 27 4

I've tried Sam's version first. Good idea, but it causes there to be multiple elements in the form with the same name. If you use any javascript that finds elements based on name, it will now return an array of elements.

html - Post the checkboxes that are unchecked - Stack Overflow

html forms post checkbox
Rectangle 27 46

There are lots of issues with your code. Let's start with the markup. You have a table and inside each row of this table you are including hidden fields. Except that you have hardcoded the id attribute of those hidden elements meaning that you could potentially end up with multiple elements with the same id in your markup which results in invalid markup.

@foreach (var t in Model.Types.ToList())
{
    <tr>
        <td>                  
            <input type="hidden" value="@t.TransID" name="TransID" />
            <input type="hidden" value="@t.ItemID" name="ItemID" />
            <input type="hidden" value="@t.TypeID" name="TypeID" />
        </td>
    </tr>
}

Alright, now you have valid markup. Now let's move on to the javascript event which will be triggered when some submitTest button is clicked. If this is the submit button of the form I would recommend you subscribing to the .submit event of the form instead of the .click event of its submit button. The reason for this is because a form could be submitted for example if the user presses the Enter key while the focus is inside some input field. In this case your click event won't be triggered.

$(document).ready(function () {
    $('form').submit(function () {
        // code to follow

        return false;
    });
});

Alright, next comes the part where you need to harvest the values of the hidden elements which are inside the table and put them into a javascript object that we will subsequently JSON serialize and send as part of the AJAX request to the server.

var parameters = [];
// TODO: maybe you want to assign an unique id to your table element
$('table tr').each(function() {
    var td = $('td', this);
    parameters.push({
        transId: $('input[name="TransID"]', td).val(),
        itemId: $('input[name="ItemID"]', td).val(),
        typeId: $('input[name="TypeID"]', td).val()
    });
});

So far we've filled our parameters, let's send them to the server now:

$.ajax({
    url: this.action,
    type: this.method,
    data: JSON.stringify(parameters),
    contentType: 'application/json; charset=utf-8',
    success: function (result) {
        // ...
    },
    error: function (request) { 
        // ...
    }
});

Now let's move on to the server side. As always we start by defining a view model:

public class MyViewModel
{
    public string TransID { get; set; }
    public string ItemID { get; set; }
    public string TypeID { get; set; }
}

and a controller action that will take a collection of this model:

[HttpPost]
public ActionResult Update(IList<MyViewModel> model)
{
    ...
}

And here's the final client side code:

$(function() {
    $('form').submit(function () {
        if ($(this).valid()) {
            var parameters = [];
            // TODO: maybe you want to assign an unique id to your table element
            $('table tr').each(function() {
                var td = $('td', this);
                parameters.push({
                    transId: $('input[name="TransID"]', td).val(),
                    itemId: $('input[name="ItemID"]', td).val(),
                    typeId: $('input[name="TypeID"]', td).val()
                });
            });

            $.ajax({
                url: this.action,
                type: this.method,
                data: JSON.stringify(parameters),
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    // ...
                },
                error: function (request) { 
                    // ...
                }
            });
        }
        return false;
    });
});

Obviously if your view model is different (you haven't shown it in your question) you might need to adapt the code so that it matches your structure, otherwise the default model binder won't be able to deserialize the JSON back.

One of the best answers I've seen. Not because of the complexity but of the ability to walk the person through the answer and show them how to do something correctly.

c# - Post JSON array to mvc controller - Stack Overflow

c# asp.net-mvc arrays json post
Rectangle 27 1

Using multiple elements with the same ID is VERY bad practice. Use a class instead...that's what they're for.

<select class="select2" style="width: 300px">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
    <option value="NY">New York</option>
</select>
...
<select class="select2" style="width: 300px">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
    <option value="NY">New York</option>
</select>
$(document).ready(function() { $('.select2').select2(); });

javascript - jQuery select2 with multiple select tags - Stack Overflow

javascript jquery
Rectangle 27 29

If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript

function insertAt(array, index) {
    var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
    return insertArrayAt(array, index, arrayToInsert);
}

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
    return array;
}

And this is how you use the functions:

// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");

// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);

Wouldn't insertAt() do better to call insertArrayAt() once it has created a single-element arrayToInsert? That avoids repetition of identical code.

this is a great example of when to use 'apply'

I added a removeCount parameter to this method to take advantages of splice's ability to also remove items at that index: Array.prototype.splice.apply(array, [index, removeCount || 0].concat(arrayToInsert));

javascript - How to insert an item into an array at a specific index? ...

javascript arrays insert
Rectangle 27 29

If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript

function insertAt(array, index) {
    var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
    return insertArrayAt(array, index, arrayToInsert);
}

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
    return array;
}

And this is how you use the functions:

// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");

// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);

Wouldn't insertAt() do better to call insertArrayAt() once it has created a single-element arrayToInsert? That avoids repetition of identical code.

this is a great example of when to use 'apply'

I added a removeCount parameter to this method to take advantages of splice's ability to also remove items at that index: Array.prototype.splice.apply(array, [index, removeCount || 0].concat(arrayToInsert));

javascript - How to insert an item into an array at a specific index? ...

javascript arrays insert
Rectangle 27 28

If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript

function insertAt(array, index) {
    var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
    return insertArrayAt(array, index, arrayToInsert);
}

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
    return array;
}

And this is how you use the functions:

// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");

// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);

Wouldn't insertAt() do better to call insertArrayAt() once it has created a single-element arrayToInsert? That avoids repetition of identical code.

this is a great example of when to use 'apply'

I added a removeCount parameter to this method to take advantages of splice's ability to also remove items at that index: Array.prototype.splice.apply(array, [index, removeCount || 0].concat(arrayToInsert));

javascript - How to insert an item into an array at a specific index? ...

javascript arrays insert
Rectangle 27 27

If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript

function insertAt(array, index) {
    var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
    return insertArrayAt(array, index, arrayToInsert);
}

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
    return array;
}

And this is how you use the functions:

// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");

// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);

Wouldn't insertAt() do better to call insertArrayAt() once it has created a single-element arrayToInsert? That avoids repetition of identical code.

this is a great example of when to use 'apply'

I added a removeCount parameter to this method to take advantages of splice's ability to also remove items at that index: Array.prototype.splice.apply(array, [index, removeCount || 0].concat(arrayToInsert));

javascript - How to insert an item into an array at a specific index? ...

javascript arrays insert
Rectangle 27 2

Options 1 A-C are really a personal preference. I would go with ClientIDMode="Static" as it gives you the most control over the Ids and it will simplify accessing the elements with Javascript (if needed). I've always hated the ugly generated Ids in the earlier versions of ASP.NET. Using a unique CSS class for each element kinda defeats the purpose of a class, which is intended for use on multiple elements.

Just to confirm your thoughts of option 2, this is not the best approach. Putting your styles in an external CSS file will result in the file being downloaded once and cached, rather than having inline styles bloat your HTML that is sent to the client each time.

My thoughts exactly. I was just looking for confirmation. I'm surprised that this question didn't spur more interest. Thanks for your opinions and explanation.

The difference between a class selector and an ID selector is trivial at best. I'm not sure why some people seem to think one is better than the other. Regarding asp.net control IDs, if you're going to use static, just remember to give the controls names that aren't likely to be repeated anywhere else. What if you need to have two instances of the same control on a page?

asp.net - VS2010 and CSS: What is the best strategy to individually po...

asp.net css visual-studio-2010 webforms
Rectangle 27 926

The .push method can take multiple arguments, so by using .apply to pass all the elements of the second array as arguments to .push, you can get the result you want:

>>> a.push.apply(a, b)

or perhaps, if you think it's clearer:

>>> Array.prototype.push.apply(a,b)

I think this is your best bet. Anything else is going to involve iteration or another exertion of apply()

Array.prototype.push.apply(a,b)

This answer will fail if "b" (the array to extend by) is large (> 150000 entries approx in Chrome according to my tests). You should use a for loop, or even better use the inbuilt "forEach" function on "b". See my answer: stackoverflow.com/questions/1374126/

@Deqing: Array's push method can take any number of arguments, which are then pushed to the back of the array. So a.push('x', 'y', 'z') is a valid call that will extend a by 3 elements. apply is a method of any function that takes an array and uses its elements as if they were all given explicitly as positional elements to the function. So a.push.apply(a, ['x', 'y', 'z']) would also extend the array by 3 elements. Additionally, apply takes a context as the first argument (we pass a again there to append to a).

a.push(...b)

How to extend an existing JavaScript array with another array, without...

javascript arrays concatenation
Rectangle 27 922

The .push method can take multiple arguments, so by using .apply to pass all the elements of the second array as arguments to .push, you can get the result you want:

>>> a.push.apply(a, b)

or perhaps, if you think it's clearer:

>>> Array.prototype.push.apply(a,b)

I think this is your best bet. Anything else is going to involve iteration or another exertion of apply()

Array.prototype.push.apply(a,b)

This answer will fail if "b" (the array to extend by) is large (> 150000 entries approx in Chrome according to my tests). You should use a for loop, or even better use the inbuilt "forEach" function on "b". See my answer: stackoverflow.com/questions/1374126/

@Deqing: Array's push method can take any number of arguments, which are then pushed to the back of the array. So a.push('x', 'y', 'z') is a valid call that will extend a by 3 elements. apply is a method of any function that takes an array and uses its elements as if they were all given explicitly as positional elements to the function. So a.push.apply(a, ['x', 'y', 'z']) would also extend the array by 3 elements. Additionally, apply takes a context as the first argument (we pass a again there to append to a).

a.push(...b)

How to extend an existing JavaScript array with another array, without...

javascript arrays concatenation
Rectangle 27 922

The .push method can take multiple arguments, so by using .apply to pass all the elements of the second array as arguments to .push, you can get the result you want:

>>> a.push.apply(a, b)

or perhaps, if you think it's clearer:

>>> Array.prototype.push.apply(a,b)

I think this is your best bet. Anything else is going to involve iteration or another exertion of apply()

Array.prototype.push.apply(a,b)

This answer will fail if "b" (the array to extend by) is large (> 150000 entries approx in Chrome according to my tests). You should use a for loop, or even better use the inbuilt "forEach" function on "b". See my answer: stackoverflow.com/questions/1374126/

@Deqing: Array's push method can take any number of arguments, which are then pushed to the back of the array. So a.push('x', 'y', 'z') is a valid call that will extend a by 3 elements. apply is a method of any function that takes an array and uses its elements as if they were all given explicitly as positional elements to the function. So a.push.apply(a, ['x', 'y', 'z']) would also extend the array by 3 elements. Additionally, apply takes a context as the first argument (we pass a again there to append to a).

a.push(...b)

How to extend an existing JavaScript array with another array, without...

javascript arrays concatenation
Rectangle 27 11

Another way to reset the values (for multiple selected elements) could be this:

$("selector").each(function(){

    /*Perform any check and validation if needed for each item */

    /*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */

    this.selectedIndex=0;

});

+1 it's actually a good answer, but you could have made it more specific to the question domain; instead of $("selector") you could have just written $('#target')

This is what I needed as I have multiple selects, thanks :)

How to make first option of

Rectangle 27 11

Another way to reset the values (for multiple selected elements) could be this:

$("selector").each(function(){

    /*Perform any check and validation if needed for each item */

    /*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */

    this.selectedIndex=0;

});

+1 it's actually a good answer, but you could have made it more specific to the question domain; instead of $("selector") you could have just written $('#target')

This is what I needed as I have multiple selects, thanks :)

How to make first option of