Jquery function cannot fire event from new data in webgrid - javascript

Wasn't exactly sure how to title this problem, but essentially what my issue is, is calling a jquery function based on a new elements that gets put into my WebGrid. However, my webgrid is populated on toggling of radio buttons. The grid then gets updated with new data by an ajax call. Therefore, no page refresh is done and my elements exist in my grid, but my javascript does not know about them.
Below is some of my code.
Webgrid:
#grid.GetHtml(tableStyle: "table table-striped table-bordered",
headerStyle: "thead-default",
columns: grid.Columns(
grid.Column("account_number", "Account Number", canSort: true),
grid.Column("last_name", "Last Name", canSort: true),
grid.Column("first_name", "First Name", canSort: true),
grid.Column("middle_name", "Middle Name", canSort: true),
grid.Column("reject_reviewed", "Reviewed", canSort: true, format: (item) => Html.CheckBox("completed", (bool)(item.reject_reviewed == 1), new { disabled = "disabled" })),
grid.Column("comment", "Comments", format: (item) =>
new HtmlString(
Html.ActionLink("Add", "RejectAddComment", controller, new RejectCommentViewModel { reject_id = item.id, account_number = item.account_number, reject_message = item.reject_message },
htmlAttributes: new { data_modal = "", id = "btnCreate", #class = "" }).ToString()
+ " | " +
Html.ActionLink("View", "RejectViewComment", controller, new RejectCommentViewModel { reject_id = item.id, account_number = item.account_number, reject_message = item.reject_message },
htmlAttributes: new { data_modal = "", id = "btnCreate", #class = "" }).ToString())),
grid.Column("reject_message", "Reject Message", canSort: true)))
javascript:
$(function () {
$.ajaxSetup({ cache: false });
$("body").on("click", 'a[data-modal]', function (e) {
// hide dropdown if any
$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
/*backdrop: 'static',*/
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
//Refresh
location.reload();
} else {
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}

Change your event binding from:
$("a[data-modal]").on("click", function (e) {
To
$("body").on("click", 'a[data-modal]',function (e) {
and it is better to use a a better selector than body, something like you grid id or class
By the way this is a famous issue, googled

Changed the line to this
$("#scroll-grid").on("click", "#btnCreate", function (e)
and the javascript event now fires.
The first element must be a parent element, and after the click event must be the element you are looking for the event of.

Related

Updating server from Kendo Color picker inside kendo grid

The Problem
So i am currently trying to implement a color picker inside of a Kendo grid, that will hopefully send the chosen color to my Sql Table. Unfortunately, It doesn't seem as though the Update controller is being reached. I am relatively new to Kendo UI, so there might be some incredibly dumb errors shown.
Questions
I guess my main question would be: How can i call the update method when update is clicked on the grid. Essentially, the color picker and the edit command are showing up in beautiful fashion. I just want to know how i can be sure that the method is being called when 'Update' is clicked, seeing as it is not reaching my controller. Feel free to ask if you need to see more code or perhaps a screen shot.
Code
Config.cshtml ( Grid )
#model IEnumerable<STZN.Models.AGCData.ErrorCode>
#{
ViewBag.Title = "Config";
}
#section HeadContent{
<script src="~/Scripts/common.js"></script>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
editable: "inline",
selectable: "row",
dataSource: {
schema: {
model: {
id: "error_code",
fields: {
color: { type: 'string' }
}
}
},
transport: {
read: {
type: "POST",
dataType: "json",
url: "#Url.Action("ErrorCodes")"
},
update: {
type: "POST" ,
dataType: "json",
url: "#Url.Action("UpdateErrorCodes")",
}
}
},
columns: [
{ command : [ "edit" ] },
{
field: "error_code", title: "Error Code",
},
{
field: "error_description", title: "Error Description"
},
{
field: "color",
width: 150,
title: "Color",
template: function (dataItem) {
return "<div style = 'background-color: " + dataItem.color + ";' </div>"
},
editor: function (container, options) {
var input = $("<input/>");
input.attr("color",options.field);
input.appendTo(container);
input.kendoColorPicker({
value: options.model.color,
buttons: false
})
},
}
]
});
});
</script>
}
Update Controller
public JsonResult UpdateErrorCodes(ErrorCode model)
{
using (var db = new AgcDBEntities())
{
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
db.Configuration.ProxyCreationEnabled = false;
var data = db.ErrorCodes.Where(d => d.error_code == model.error_code).Select(x => new
{
error_code = x.error_code,
description = x.error_description,
color = x.color,
});
return new JsonResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
};
}
}
I actually managed to fix my issue by adding an additional input attribute to my editor function in the "color" field. It looks like this:
input.attr("data-bind","value:" + options.field);
There are still some present issues (unrelated to the fix/server update) , but as far as updating to the server, It work's as intended.

Bind Webgrid using JQuery failed

Hi I am using webgrid this time.and Binding json data using JQuery. My ajax call script providing data but I am unable to get it some how.I have gone thorugh all the questions available here but nothing worked. Look at the components and tell me what is wrong.
This is the web grid
<div id="GridContent">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 15, selectionFieldName: "Id", ajaxUpdateContainerId: "GridContent", canSort: true);
}
#grid.GetHtml(
tableStyle: "webgrid-table",
rowStyle: "webgrid-row-style",
htmlAttributes:"grid",
emptyRowCellValue: "--",
headerStyle: "webgrid-header",
selectedRowStyle: "webgrid-alternating-row",
columns: grid.Columns(
grid.Column(columnName: "CenterId", header: "Id"),
grid.Column(columnName: "CenterName", header: "CenterName"),
grid.Column(columnName: "CenterCode", header: "CenterCode"),
grid.Column(columnName: "Address", header: "Address"),
grid.Column(columnName: "EmailId", header: "EmailId"),
grid.Column(format: #<a id="EditCenter" class="fa-anchor" data-id="#item.CenterId">Edit</a>),
grid.Column(format: (item) => Html.ActionLink((string)"Delete", "DeleteCenter", new { CenterId = item.CenterId }, new { id = "DeleteCenter", onclick = "return confirm('Are You Sure Want To Delete The Center Data?');" }))))
</div>
and here is my ajax call for binding the data on dropdown change.
$(document).ready(function () {
$("#ListType").change(function () {
var webgrid;
$.ajax({
type: 'POST',
url: ListTypeUrl,
data: { id: $("#ListType").val() },
datatype:'html',
success: function (result) {
$("#GridContent").html(result);
alert("Success");
},
error: function (result) {
alert("On select Failed " + result);
}
});
})
});
Here is Controller method for getting JSON Results
public JsonResult GetCenterList(int id)
{
List<CenterDetails> cd = objDal.GetCenterListItem(id.ToString(), Session["AgentId"].ToString());
return Json(cd,JsonRequestBehavior.AllowGet);
}
public List<CenterDetails> GetCenterListItem(string type, string AgentId)
{
XElement xl = new XElement("root"
, new XAttribute("OType", "Select")
, new XAttribute("Target", "CenterList")
, new XElement("Type",Convert.ToInt32(type))
, new XElement("AgentId", AgentId));
ds = ExecuteDataSet("Sp_CenterAction", CommandType.StoredProcedure, new MySqlParameter("#xml", xl.ToString()));
dt = ds.Tables[0];
drc = dt.Rows;
List<CenterDetails> objList = new List<CenterDetails>();
foreach (DataRow dr in drc)
{
objList.Add(new CenterDetails
{
CenterId = Convert.ToInt32(dr["cm_Id"].ToString()),
CenterName = dr["cm_Name"].ToString(),
CenterCode = dr["cm_CenterCode"].ToString(),
Address = dr["cm_Address"].ToString(),
EmailId = dr["cm_EmailId"].ToString()
});
}
return objList;
}

How to use fillSelectors in casperjs

I need to get some content from the page, but if I use fillSelectors() the content is not load. Maybe i need use evaluate(), but i dont undestend where and how.
var casper = require('casper').create()
casper.start('http://console.matomycontentnetwork.com/', function() {
this.fillSelectors('form#login-form', {
'input[name="username"]': 'jpost',
'input[name="password"]': 'matomy123'
}, true);
this.clickLabel("Sign In", 'button');
});
casper.then(function() {
var start_date = '09/01/2015';
var end_date = '10/07/2015';
this.evaluate(function() {
$('#report-range').val('custom').change();
});
this.fillSelectors('form#report-form', {
'input[name="report[start_date]"]': start_date,
'input[name="report[end_date]"]': end_date,
'input[id="grouping-option-3"]' : true,
'input[id="grouping-option-2"]' : true,
'input[id="grouping-option-4"]' : true
}, true);
this.click("#run-report");
this.wait(10000, function () {
this.echo('.geo_country_name.innerText: ' + this.evaluate(function() {
return document.querySelector('.geo_country_name').innerText;
}));
this.echo('td.alignright:nth-child(5).innerText: ' + this.evaluate(function() {
return document.querySelector('td.alignright:nth-child(5)').innerText;
}));
});
});
casper.run();
Can you help with that?
Here are some guesses:
If you want to click on some button to submit a form, don't automatically submit a form. Remove the last argument:
this.fillSelectors('form#report-form', {
'input[name="report[start_date]"]': start_date,
'input[name="report[end_date]"]': end_date,
'input[id="grouping-option-3"]' : true,
'input[id="grouping-option-2"]' : true,
'input[id="grouping-option-4"]' : true
});
PhantomJS doesn't support element.innerText. You need to use element.textContent.

jQuery dialog jumping to full page in browser

I have a dialog with a WebGrid that displays a list of items:
#if (Model.ItemsByLocation != null)
{
#grid.GetHtml(
tableStyle: "table",
fillEmptyRows: true,
headerStyle: "header",
footerStyle: "footer",
mode: WebGridPagerModes.All,
firstText: "<<First",
previousText: "<Prev",
nextText: "Next>",
lastText: "Last>>",
htmlAttributes: new { id = "grid"},
columns: new []
{
//grid.Column("ItemNumber", "Item"),
grid.Column(header: "Item Number", format: (item) => Html.ActionLink((string)item.ItemNumber, "ShowItem", "Inventory", new { id = item.ItemNumber.ToString()}, new {onclick = "GetItemDetails(" + item.ItemNumber.ToString() + ");"})),
grid.Column("ItemDescription","Desc"),
grid.Column("ItemSerialNumber","SN"),
grid.Column("itemLocationSite","Site"),
grid.Column("ItemLocationBuilding","Bldg"),
grid.Column("ItemLocationFloor","Flr"),
grid.Column("ItemLocationOffice","Off"),
grid.Column("ItemTypeDescription","Type"),
grid.Column("FirstName","First"),
grid.Column("LastName","Last")
})
}
else {
<p><i>No item to display</i></p>
}
This is a dialog itself from another page - no problem with this. When I click on the link the JS function is called:
function GetItemDetails(id) {
var test = id;
$.ajax({
type: 'GET',
url: '#Url.Action("ShowItem")?id=' + id,
success: function (data) {
$("#divDetails").html(data);
$("#divDetails").dialog("open");
$("#divDetails").show();
}
});
return false;
}
This responds with another dialog on top of the first dialog, but only for a second or two and then both dialog close and the data in the second dialog is displayed full page in the browser. Any ideas why this is?
This is the dialog for the details:
$(document).ready(function () {
//debugger;
$("#divDetails").dialog({
autoOpen: false,
width: 'auto',
resizable: true,
title: 'Item Details',
modal: true,
closeOnEscape: false,
show: {
effect: 'drop', direction: 'up'
},
buttons: {
"OK": function () {
$(this).dialog("close");
}
}
}).prev("ui-dialog-titlebar").css("background", "#FF3300");
$(".dialog").click(function () {
$("#divDetails").dialog("open");
});
});
<div id="divDetails" style="display:none" class="ui-dialog-titlebar ui-widget-header">
</div>
I put some breakpoints in the code and after the second dialog is displayed the controller Index function is called. How does that happen? It does this if I remove the ShowItem from the link, But if I put that back in, it calls the ShowItem function twice. Why?
I still do not know what the problem was but if I change the webgrid column to this, it works just fine:
grid.Column(header: "Item Number", format:##item.ItemNumber.ToString()),

Take selected DDL value an use as parameter for actionlink

I have an MVC view with a few dropdown lists. There is some custom validation on there that under certain conditions will show an action link by the side of the drop down list. These action links will pop up a modal window with information related to the choice made in the dropdown list.
My problem is that I can seem to see how to take the value chosen from the dropdown and get it in to my ajax request!!
Here is my code: (dropdown)
<div id="holderlist">
#Html.DropDownListFor(i => i.holderid, (SelectList)ViewData["holdersList"], "", new { #class = "chosenlist" })
</div>
(action link)
<div id="add" style="display:none;">
#Html.ActionLink("Actions", "existingOfficers", "Roles",
new { id = ?????<how do I get DDL chosen ID here> },
new { #class = "openDialog", dialog_id = "productDetail", dialog_title = "Workflow Centre" })
</div>
(ajax request)
<script type="text/javascript">
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$(".openDialog").live("click", function (e) {
e.preventDefault();
$("<div></div>")
.addClass("dialog")
.attr("id", $(this).attr("dialog-id"))
.appendTo("body")
.dialog({
title: $(this).attr("dialog-title"),
close: function () { $(this).remove() },
modal: true,
width: 706,
height: 300
})
.load(this.href);
});
$(".close").live("click", function (e) {
e.preventDefault();
$(this).closest(".dialog").dialog("close");
});
});
What I cant do is get the ID set to the ID of the value chosen in the DDL. The DDL value isn't at this point stored in the database as this is essentially a new input form.
Any help would be greatly appreciated :-)
jQuery(function($) {
$('.helpButton').each(function() {
$.data(this, 'dialog',
$(this).next('.helpDialog').dialog({
autoOpen: false,
modal: true,
title: 'Info',
width: 600,
height: 400,
position: [200,0],
draggable: false
})
);
}).click(function() {
$.data(this, 'dialog').dialog('open');
return false;
});
}); ​
You can test here

Categories