Note: If jquery cannot find your element it will simply give up. (no errors)
Those fucking radiobuttons
$("input[name='rbAddItem']:checked").val()
To post a list of values
First generate the list of values
var postValues = [];
...
if (typeof test != 'undefined') {
if ($(this).val() != test) {
var postValue = { fieldKey: $(this).prop('id'), fieldValue: test };
postValues.push(postValue);
}
}
Then post to server (seems like you need to use $.ajax)
$.ajax({
type: "POST",
url: "/PostProductDetail/",
data: JSON.stringify(postValues),
contentType: 'application/json',
success: function () { alert('done'); }
});
on the server (api)
[HttpPost]
[Route("PostProductDetail")]
public string PostProductDetail(List<ProductDetailPost> postValues)
{
int o=0 ;
return "";
}
need an object defined in c#
public class ProductDetailPost
{
public string fieldKey { get; set; }
public string fieldValue { get; set; }
}
Find a radio or checkbox by their value and set checked
$("#itemConditionDiv").find("input[name='ItemCondition']").val(selectedItem.ItemCondtion).first().prop("checked", "checked");
Templates
Define a template
$.templates({
CodeFor: '<div id="rulesTitle" class="rulesTitle">{{:CodeFor}}</div>'
+ '<div class="rulesDiv"><div class="rulesLine">'
+ '<div style="font-weight:normal;" class="itmDesc1">Code</div><div style="font-weight:normal;" class="itmDesc2">Name</div>'
+ '</div><div class="rulesLine"><div class="itmData1"><input type="text" id="rulesCode2" class="idTxt1" value="{{:Code}}" /></div>'
+ '<div class="itmData2"><input type="text" id="rulesName2" class="idTxt2" value="{{:Name}}" /></div></div>'
});
Fill the template (obj is a json record)
var html = $.templates.CodeFor.render(obj);
$("#ruleBox" + obj["RuleMastID"]).html(html);
To find and change a data- element
$('#uomDiv').find('input[data-value="' + UOM + '"]').first().prop("checked", "checked");
The HTML code looks like this
<div id="uomDiv" style="width:250px;" class="stdBox3line">
<div class="stdBoxTitle">UOM (Unit of Measure)</div>
<div class="stdBoxLine">
<div class="BoxLineDiv"><input name="itemCondition" data-value="EA" type="radio" /><div class="rbcbDesc">Each</div></div>
</div>
<div class="stdBoxLine">
<div class="BoxLineDiv"><input name="itemCondition" data-value="HR" type="radio" /><div class="rbcbDesc">Hour</div></div>
<div class="BoxLineDiv"><input name="itemCondition" data-value="DY" type="radio" /><div class="rbcbDesc">Day</div></div>
<div class="BoxLineDiv"><input name="itemCondition" data-value="MT" type="radio" /><div class="rbcbDesc">Month</div></div>
<div class="BoxLineDiv"><input name="itemCondition" data-value="YR" type="radio" /><div class="rbcbDesc">Year</div></div>
</div>
<div class="stdBoxLine">
<div class="BoxLineDiv"><input name="itemCondition" data-value="LB" type="radio" /><div class="rbcbDesc">Pound</div></div>
</div>
</div>
The load function
$(document).ready(function() { // Handler for .ready() called.});
Extending DataTable to sort on the title data of a column
First add the extension code
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"title-numeric-pre": function (a) {
var x = a.match(/title="*(-?[0-9\.]+)/)[1];
return parseFloat(x);
},
"title-numeric-asc": function (a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"title-numeric-desc": function (a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
Then configure the table on initialization
$(document).ready(function () {
$('#equipmentPropertyTable').dataTable(
{ "iDisplayLength": 4 ,
"aoColumns": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
{ "sType": "title-numeric" },
null
]
}
);
To move fields from a dialog to a form for posting
"Save": function () {
// Move all the hidden fields into the form
$("#assetInfoDiv input").each(function () {
var splitId = $(this).attr("id").split('-');
$("#" + splitId[1]).val($(this).val());
});
$(this).dialog("close");
}
To trigger any event on an element
$('#userid').val(myValue)
.trigger('change');
Another table display plugin
http://www.overset.com/2008/08/30/animated-sortable-data-table-jquery-plugin--jtps/
OMG Just try and get the value of a radio button
var findit = "input:radio[name=" + $(this).attr("name") + "]:checked";
console.log($(findit).val());
also if you just have a set of radio buttons you can add a class that is unique to them and then:
var findit = "input:radio[name=" + $(".rblType").attr("name") + "]:checked";
To allow cross domain load call
jQuery.support.cors = true;
To position a jquery ui dialog
$("#caUncertainBox").dialog({
height: 200,
width: 300,
resizable: false,
modal: false,
position: {
my: 'top',
at: 'top',
of: $('#caUncertain')
},
autoOpen: true,
title: "Please explain",
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "explode",
duration: 50
}
});
To go thru a list of options on a select and only show the ones that match a value (like the value of a previously selected select .)
Good for cascading selects.
NOTE: the setting of a select to the first option is included.
function SetBins() {
$("#binNum option").each(function () {
if ($(this).attr("itemref") == $("#storageLoc").val() || $(this).val()=="0") {
$(this).show()
}
else {
$(this).hide()
}
});
$('#binNum option[value="0"]').attr('selected', 'selected');
}
To add an element (or html) to the first row of a table (instead of the last with append). This can be used for any element structure.
var row = "<tr class='charge-code-select-input-row' ><td><input class='accessoryItem' readonly='true' name='accessories' value='" + $("#ddlAccessory").val() + "' /></td><td class='invisible-cell' ><img class='delete-btn' alt='Delete' onclick='RemoveThisRow(this)' src='/images/delete.png'> </td></tr>";
$(row).insertAfter("#selectedAccessories tr:first");
To pass in an element (no class or id)
function IncrementPercent(obin, amt) {
alert($(obin).parent().attr('class'));
To access elements in an Iframe
$("#uploadFrame").contents().find("#id").val(type);
To get the errors from validation ( validate plugin)
var validator = $("#favoriteEditForm").validate();
errorMessage = ""
errors = validator.errorList;
for (var i = 0; i < errors.length; i++) {
errorMessage += errors[i].message.toString() + "\n";
}
alert(errorMessage);
To find out if there are multiple copies of an element
$('body').find('#JobsCreateForm').length;
Basic Dialog
$("#dialog-modal").dialog({
height: 140,
modal: true,
autoOpen: true,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
then just add a div to your page
<div id="dialog-modal" style="display:none;" >
</div>
To add a floating dialog (withing a dialog)
Note: instead of using a content var you need to use a div in the DOM in order for the closing function to see the inputs.
// global scope the var
var $dialog = "";
$(document).ready(function () {
var mon = dnow.getMonth() + 1;
var cyear = dnow.getFullYear();
BuildWeek(dnow);
content = "<div style='padding: 5px;'><div style='padding: 5px;'><div style='float: left'> New hours: </div><div style='float: left'><input style='width: 25px;' id='newHours' /></div></div><div style='padding: 5px;clear: left'><div style='float: left'> Note: </div><div style='float: left'> <textarea style='width:300px' id='newHoursText' rows='3' cols='15'></textarea> </div> </div>"
$dialog = $('<div></div>')
.html(content)
.dialog({
autoOpen: false,
width: 400,
height: 235,
stack: true,
modal: true,
title: 'Modify Time Record',
buttons: {
Done: function () {
PostModify();
$dialog.dialog("close");
}
}
});
});
// call the dialog
$dialog.dialog('open');
You can also use a div for the floating dialog like :
$dialog = $("#innerDialog")
.dialog({
To add an event with Jquery
$("#ContractorsTable input:checkbox").bind('click',
function (event) {
AddCandidate(this)
});
Jquery Get
$.get('/TimeRecords/RecordApprove/' + obin,
function (data) {
if (data == "0") {
$("#r-" + obin).find(".approverDatecell").html(today.toShortDateString());
$("#r-" + obin).find(".approverCell").html(ApproverUname);
//alert("posted");
}
else {
alert(data);
}
});
Jquery Post (with non form data)
process = $(selectIn).val();
serviceRequests = new Array();
$("#dailyTable").find("input:checkbox").each(function () {
if (this.checked) {
console.log($(this).parent().next().next().children(0).html());
serviceRequests[serviceRequests.length] = $(this).parent().next().next().children(0).html();
}
});
var parameters = {
"opId": process,
"srAr[]": serviceRequests
};
$.post("/DoBatchOperation/",
parameters,
function (data) {
alert(data);
});
Jquery Load
In MVC if we want to have mutiple tabs on a screen and we need to 'navigate' to pages on a tab you can use JQuery load
<script type="text/javascript">
function PostProfileEdit() {
if ($("#ProfileEditForm").validate().form()) {
$.post("User/ProfileEdit",
$("#ProfileEditForm").serialize(),
function (data) {
$("#profiledisplay").html("<div class='profileSpacer' ></div>").load("License/ProfileLicense")
});
}
}
</script>
In this code we validate the form with id ProfileEditForm. We then post it to User/ProfileEdit. We set the return from the controller to be null and then we load a markup from
License/ProfileLicense.
To set a select element option
$("#PositionId option").eq($("#r-" + row).find(".td-position_id").html().trim()).attr('selected', 'selected');
Autocomplete
On the client:
$(function () {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#selection").autocomplete({
source: "/Home/GetAuto",
minLength: 2,
select: function (event, ui) {
// more functionality can go here to use the ui object that was selected.
log(ui.item ? ui.item.value :"Nothing selected, input was " + this.value);
}
});
});
You need this model
<span style="height: 151px; width: 692px;"> public class Autocomplete
{
public int id { get; set; }
public string label { get; set; }
public string value { get; set; }
}
</span>
In the html
<div class="ui-widget">
<label for="birds">Pick a User: </label>
<input id="selection" />
</div>
<div class="ui-widget" style="margin-top:2em; width:400px; font-family:Arial">
<div class="fl">Selected : </div> <div class="fl" id="log" ></div>
</div>
<div style="clear:both"> </div>
On the Server - Note part of your json object has to be 'label' and 'value'
public ActionResult GetAuto(string term)
{
List<Autocomplete> ausers = new List<Autocomplete>();
ausers = (from ret in db.Users where ret.last_Name.StartsWith(term) select new Autocomplete { label = ret.first_Name + " " + ret.last_Name, value = ret.first_Name + " " + ret.last_Name, id = ret.id }).ToList();
return Json(ausers, JsonRequestBehavior.AllowGet);
}
Dialogs
Succint Dialog
$("#userDialog")
.dialog({ autoOpen: false, title: "Manage User", width: 780, height: 540, modal: true,
buttons: {
Close: function () { $("#userDialog").dialog("close"); },
Save: function () { PostProfileEdit(); }}
})
.load("/User/ProfileEdit/"+ userId, function () {
$("#userDialog").dialog("open");
});
for a dialog that just shows something and is closed by the user use this pattern
function ShowCandidate(canId) {
$("#jobDialog")
.dialog({ title: 'Candidate Information', width: 500, height: 400 })
.load("/PharmacyProfessional/Details/" + canId, function () { $("#jobDialog").dialog("open"); });
}
for a dialog that will automatically close at the end of the process use this pattern
function SelectCandidate(canId) {
$("#selectDialog") // this dialog is defined below
.dialog()
.load("/Contracts/Edit?jobId=" + jobId + "&candId=" + canId , function () { $("#selectDialog").dialog("open"); });
}
// define the dialog prior to calling it
// this is so we can have a 'success action' connected to a button
$(function () {
$("#selectDialog").dialog({ title: 'Create Contract', autoOpen: false, width: 600, height: 300 , modal: true,
buttons: {
Create: function () {
if ($("#ContractCreateForm").validate().form()) {
$.post("/Contracts/Edit/",
$("#ContractCreateForm").serialize(),
function (data) {
if(data=="0"){
$("#selectDialog").dialog("close");
alert("Contract Created");
}
else{
alert(data);
}
});
}
},
Cancel: function () { $("#selectDialog").dialog("close"); }
}
});
});
To get values (object) from the server and use as object on client
1. declare the object and make the call on the client
var JobDetails = new Object();
JobDetails.startDate = "";
JobDetails.endDate = "";
JobDetails.state = "";
function SetJob() {
$.get("/PharmacyJobs/JobDetails/" + $("#companyJobs").val(), function (data) {
JobDetails = eval(data);
alert(JobDetails.state);
});
}
if the object coming back is a list then you can use
var test = jQuery.parseJSON(data);
2. Build the object and return as Json on the server.
public class JobDetail{
public string startDate { get; set; }
public string endDate { get; set; }
public string state { get; set; }
}
public ActionResult JobDetails(int id)
Job job = db.Jobs.Find(id);
JobDetail jobDetail = new JobDetail();
jobDetail.state = job.state;
jobDetail.startDate = job.startDate.ToShortDateString();
jobDetail.endDate = job.endDate.ToShortDateString();
return Json(jobDetail, JsonRequestBehavior.AllowGet);
}
JQuery Plugin template
called as
$(
"#PharmacyEditForm").MvcValidate()
//You need an anonymous function to wrap around your function to avoid conflict
(function ($) {
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
MvcValidate: function () {
isValid = true;
//Iterate over the current set of matched elements
this.find(".text-box").each(function () {
if($(this).attr("data-val-required")!=undefined){
if($(this).val().length==0) {
isValid = false;
$("#errorContent").append($(this).attr("data-val-required") + "<br>")
}
}
});
if (!isValid) {
$("#errorPane").show();
}
return isValid;
}
});
//pass jQuery to the function,
//So that we will able to use any valid Javascript variable name
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )
})(jQuery);
To Load a select box with data from a get
<span style="height: 176px; width: 690px;">
$.get("/api/rooms/" + $("#_building").val(), function (retVal)
{
for (var i = 0; i < retVal.length; i++)
{
var key = retVal[i].abbrev;
var value = retVal[i].name;
$('#_room')
.append($("<option></option>")
.attr("value",key)
.text(value));
}</span>