jQuery Examples

.attr

The data- attribute can hold any data

1
2
3
<div class="item" data-square="1">
@Html.DisplayFor(m => Model.Square1)
</div>

To read this data

1
2
3
$(document).ready(function () {
$(".item").click(function () {
var squareNumber = $(this).attr("data-square");

.ajax

Type needs to match the Http Verb, the POST below is intended to create/insert and can be used with these example api controller methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(document).ready(function () {
$(".item").click(function () {
$.ajax({
type: "POST",
url: "/api/apigame",
data: JSON.stringify({ Id: "1", Player: "O" }),
success: success,
contentType: "application/json",
error: function (xhr, error, status) {
console.log(error, status);
}
});
});
});

function success(data) {
alert(data);
}

.datepicker

1
2
3
4
5
6
7
8
$(document).ready(function () {
$('input[type=datetime]').datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
yearRange: "-10:+10"
});
});

.append

1
2
3
var heading = "<div class='chart-wrapper__item-heading'>" + json.chartModelsWithMany[i].Heading + "</div>";
var chart = "<div id='" + json.chartModelsWithMany[i].renderAt + "'>loading ...</div>";
$("#chartVerticalBars").append("<div class='chart-wrapper__item'>" + heading + chart + "</div>");

.dialog

Some sweet HTML and CSS hacks

1
2
3
.ui-dialog {
z-index: 1032 !important;
}
1
2
3
4
5
6
<div id="dialog" class="dialog" style="z-index: 1050!important;" title="SWEET HEADING">
<div style="text-align:center;height:100%;padding-top:220px;color: #76b729;">
LOADING...
</div>
</div>
<input type="text" id="someCode" class="hidden" />

The Javascript to trigger, includes close hacks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$(document).ready(function () {
$(".dialog").dialog({
autoOpen: false,
height: 550,
width: 900,
draggable: false,
resizable: false,
dialogClass: 'sweet-dialog',
open: function () {
$(this).scrollTop(0);
},
buttons: [
{
text: "DOWNLOAD PDF",
click: function () {
window.open("/Controller/Action/?code=" + $("#someCode").val());
}
},
{
text: "CLOSE",
click: function () {
CloseDialog();
}
}
]
});

$(".ui-dialog-titlebar-close").click(function () {
CloseDialog();
});
});

function CloseDialog() {
$(".dialog").dialog("close");
}

.load

1
$('#fooDiv').load("/Controller/Action/?id=42");

References