Change hyperlink own text on its click event through jquery - c#

I have a dynamically generated list of hyperlinks and i'm using jquery to bind the click events, everything is working fine, just one thing i am unable to do is to changes its text
**this.value = s;**
This is what I was trying to do without any success.
My full code:
$(document).ready(function () {
$('[id*="lnkStatus_"]').bind('click', SaveRequirmentStatus);
});
function SaveRequirmentStatus(event) {
var itemID = $(event.currentTarget).attr('id');
var intProjectId = $('[id$="hdnProjectId"]').val();
var idRequirment = itemID.split('_')[1];
var idRequirementPhase = itemID.split('_')[2];
var idPhaseStatus = $(event.currentTarget).val();
if (intProjectId != '0' && idRequirment != '0' && idRequirementPhase != '0') {
$.getJSON('handler/RequirementLifecycleHandler.ashx? FuncName=SaveRequirment&idRequirment=' + idRequirment + "&idRequirementPhase=" + idRequirementPhase + "&idProject=" + intProjectId + "&idPhaseStatus=" + idPhaseStatus, function (ValueStatus) {
var s = ValueStatus;
alert(this);
this.value = s;
});
}
}

this in the context that you are using it does not refer to the link, so save a reference to it outside of the inner function and use that. Also, a link does not have a value, you can set the text using the jQuery text function.
Changing your code to this should do what you want:
function SaveRequirmentStatus(event) {
var $this = this; // save reference to the clicked link
var itemID=$(event.currentTarget).attr('id');
var intProjectId=$('[id$="hdnProjectId"]').val();
var idRequirment=itemID.split('_')[1];
var idRequirementPhase=itemID.split('_')[2];
var idPhaseStatus = $(event.currentTarget).val();
if (intProjectId != '0' && idRequirment != '0' && idRequirementPhase != '0') {
$.getJSON('handler/RequirementLifecycleHandler.ashx?FuncName=SaveRequirment&idRequirment=' + idRequirment + "&idRequirementPhase=" + idRequirementPhase + "&idProject=" + intProjectId + "&idPhaseStatus=" + idPhaseStatus, function(ValueStatus) {
$this.text(ValueStatus); // set the text of the link to ValueStatus
});
}
}

This should do
$(function() {
$('[id*="lnkStatus_"]').bind('click', SaveRequirmentStatus);
});
function SaveRequirmentStatus(event) {
$(this).text(ValueStatus);
}

Related

<asp:TreeView> Add an additional information to treenode accessible via JavaScript/JQuery?

Is there a way to add an information to the asp:TreeView, in the way that i can access it via JavaScript/Jquery?
My problem: I have to prevent via JQuery/Javascript (on client side) that checkboxes in an asp:TreeView are selectable in different subcategories (or parent-nodes grouped by a stereotype-prefix). It already worked when i asked for the TreeNode-Text with $(this).next().text();, because they had a prefix (stereotype) in the categories, but now i have to hide that information and cannot use it to check.
$("[id*=TreeView1] input[type=checkbox]").bind("click", function () {
var isChecked = $(this).is(":checked");
if (isChecked) {
zuletztSelektiert = zuletztSelektiert + $(this).next().text();
}
else {
zuletztSelektiert = zuletztSelektiert.replace($(this).next().text(), '');
}
if (zuletztSelektiert != '') {
// Welcher Stereotyp ist selektiert?
var stereotype = zuletztSelektiert.substring(zuletztSelektiert.indexOf('«') + 1, zuletztSelektiert.indexOf('»'));
$("[id*=TreeView1] input[type=checkbox]").each(function () {
var currentStereotype = $(this).next().text().substring($(this).next().text().indexOf('«') + 1, $(this).next().text().indexOf('»'));
if (currentStereotype != stereotype) {
var isChecked2 = $(this).is(":checked");
if (isChecked2) {
$(this).removeAttr("checked");
zuletztSelektiert = zuletztSelektiert.replace($(this).next().text(), '');
alert('It is not possible to select elements of different stereotypes. \n\n Selected Items:\n' + zuletztSelektiert);
}
}
});
}
});
Okay because nobody know the answer i just did it by adding the stereotype as GET-Param to the links target URL and navigated to the -Tag in the treenode
$("[id*=TreeView1] input[type=checkbox]").bind("click", function () {
var selectedStereoType = $.trim($(this).next().prop("href").substring($(this).next().prop("href").indexOf("=") + 1));
//return;
var isChecked = $(this).is(":checked");
if (isChecked) {
//zuletztSelektiert = zuletztSelektiert + $(this).next().text();
zuletztSelektiert = zuletztSelektiert + selectedStereoType;
}
else {
//zuletztSelektiert = zuletztSelektiert.replace($(this).next().text(), '');
zuletztSelektiert = zuletztSelektiert.replace(selectedStereoType, '');
}
if (zuletztSelektiert != '') {
// Welcher Stereotyp ist selektiert?
//var stereotype = zuletztSelektiert.substring(zuletztSelektiert.indexOf('«') + 1, zuletztSelektiert.indexOf('»'));
var stereotype = selectedStereoType;
var letzteMeldung = '';
$("[id*=TreeView1] input[type=checkbox]").each(function () {
//var currentStereotype = $(this).next().text().substring($(this).next().text().indexOf('«') + 1, $(this).next().text().indexOf('»'));
var currentStereotype = $.trim( $(this).next().prop("href").substring($(this).next().prop("href").indexOf("=") + 1) );
if (currentStereotype != stereotype) {
var isChecked2 = $(this).is(":checked");
if (isChecked2) {
$(this).removeAttr("checked");
zuletztSelektiert = zuletztSelektiert.replace($.trim( $(this).next().prop("href").substring($(this).next().prop("href").indexOf("=") + 1) ), '');
letzteMeldung='It is not possible to select elements of different stereotypes. \n\n Selected Items: ' + zuletztSelektiert;
}
}
});
if (letzteMeldung != '') alert(letzteMeldung);
}
});
This is how i did it in C#.NET
treeNode.NavigateUrl = "URL?stereotype="+stereotype;

Are there any alternatives of ASP Panels to insert html from code?

I'm using an ASP panel as a placeholder to create things like menus that come from the database. For this I created a class with a function that returns a Panel.
Is there an alternative to this? I would like my code to be completly independed of the project. Maby some classic ASP function?
Code that creates the menu:
public static Panel createMenu(Panel panel)
{
List<menu> menuItems = menu.selectMenuitems();
panel.Controls.Add(new LiteralControl("<ul>"));
for (int i = 0; i < menuItems.Count; i++)
{
string menuPath = menuItems[i].virtualpath;
string menuName = menuItems[i].name;
panel.Controls.Add(new LiteralControl("<li>"));
// Get the full URL
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// Get last part of the URL
string path = url.Split('/').Last().ToLower();
// If the url is the same as the menu-item, add class active.
if (path == menuPath || (path == "default.aspx" && i==0))
panel.Controls.Add(new LiteralControl("<a class='active' href='/" + menuPath + "'>"));
else
panel.Controls.Add(new LiteralControl("<a href='/" + menuPath + "'>"));
panel.Controls.Add(new LiteralControl(menuName));
panel.Controls.Add(new LiteralControl("</a>"));
panel.Controls.Add(new LiteralControl("</li>"));
}
panel.Controls.Add(new LiteralControl("</ul>"));
return panel;
}
Your menu structure appears to be something like this:
<ul>
<li><a class href>name</a></li>
</ul>
Why not just create a routine that outputs a string. You can pass the string over to a literal control to load the menu. Something like:
myLiteral.Text = createMenu();
This code is not tested, but hopefully gives you a start:
public static string createMenu()
{
List<menu> menuItems = menu.selectMenuitems();
var m = new StringBuilder();
m.AppendLine("<ul>");
for (int i = 0; i < menuItems.Count; i++)
{
string menuPath = menuItems[i].virtualpath;
string menuName = menuItems[i].name;
m.AppendLine("<li>");
// Get the full URL
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// Get last part of the URL
string path = url.Split('/').Last().ToLower();
// If the url is the same as the menu-item, add class active.
m.AppendLine("<a " + setActiveClass(path, menuPath, i) + " href=\"/" + menuPath + "\">");
m.AppendLine(menuName);
m.AppendLine("</a>");
m.AppendLine("</li>");
}
m.AppendLine("</ul>");
return m.toString();
}
private static string setActiveClass(string path, string menuPath, int i) {
if (path.Equals(menuPath, StringComparison.OrdinalIgnoreCase) || (path.Equals("default.aspx", StringComparison.OrdinalIgnoreCase) && i==0)) {
return "class=\"active\"";
}
else {
return "";
}
}
You can also expand upon this to include sub-menus.
To be "independent" you could create the menu via Javascript/Jquery.
You can create a .ashx page or something like this that returns a JSON than you create the menu asynchronously. Your JSON should return a two keys structure like this
[{"menuName": "menu1","menuLink": "http://www.google.com"}, { "menuName": "menu2", "menuLink": "http://www.yahoo.com"}, { "menuName": "menu3", "menuLink": "http://www.pudim.com"}]';
Your JS/jQuery function would be like this
function createMenuAsync()
{
var menuContainer = $("#menuContainer");
var listRoot = $("<ul></ul>");
$.getJSON(callString, function (response) {
$.each(JSON.parse(response), function(key,value){
var listItem = $("<li></li>");
var itemLink = $("<a>" + value.menuName + "</a>").attr("href",value.MenuUrl);
itemLink.appendTo(listItem);
listItem.appendTo(listRoot);
})
});
listRoot.appendTo(menuContainer);
}
The code will be cleaner and will be lighter to your webserver, since the html tags elements will be created on client side instead of server side.
I create a fiddle with this code working
https://jsfiddle.net/h4ywwxm8/2/

Success callback not running

Can anyone tell me why my success callback in this jQuery isn't being called?
$(document).ready(function () {
var queueid = $('#hidqueueid').val();
var queuemax = $('#hidqueuemax').val();
var queuenext = $('#hidqueuenext').val();
var sid = $('#hidsid').val();
var acc = $('#hidacc').val();
var key = getCookie('account_key');
var processNext = function() {
var url = "functions.aspx?sid=" + sid + "&acc=" + acc + "&func=processqueue&id=" + queueid + "&next=" + queuenext + '&key=' + key;
showProgress();
$.post(url, function (data) {
alert(data); // <== never happens :(
var result = $(data).attr('result');
if (result == 'ok') {
queuenext = $(data).attr('next');
if (queuenext > 0) {
$('#hidqueuenext').val(queuenext);
processNext();
} else {
var newurl = 'Data.aspx?sid=' + sid + '&acc=' + acc;
location.href = newurl;
}
}
}, function() {
// error
alert('Oops!');
});
};
var showProgress = function() {
var output = "<div>" + queuenext + " of " + queuemax + "</div>";
$('#divprogress').html(output);
};
processNext();
});
The C# which returns the result is working fine and looks like this:
string xml = new Queue(sid, acc, queueId).ProcessItem(queueNext, key);
Response.ClearContent();
Response.ContentType = "text/xml";
Response.Write(xml);
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
The XML looks fine when I debug the C#
Thanks for any help! All suggestions welcome.
post has three initial parameters, first one is a address, second is data, which should be null in your case, and third is success callback.
If you need a fail callback, use fail method:
$.post('', null, null).fail(function(data) {} );
Also, if you feel more comfortable working with that XMLRequest object, you might want to use complete method:
$.post('/do/action', { Id: 120 }, null).fail(function(data) {
// code
}).complete(function(data) {
// code for complete, which is the same as success callback.
});
There is also .always() method which is being called back always, hehe. And others.

Read asp.net dynamic textbox content length using c#

I am using the below code to create a dynamic textbox and their onchange event.Event fired successfully and it doesn't return any value.Please help me to solve this.
txt_box.Attributes.Add("onchange", "loadValues('" + txt_box.ClientID + "')");
function loadValues(controlName) {
alert(controlName);
//control name comes here
var txtValue = document.getElementById(controlName);
//control also return null
if (txtValue.value.length > 0)
{
alert(txtValue.value.length);
}
}
Was just about to answer the same as Ankush Jain, but then none jquery version:
function loadValues(control) {
alert(control.id);
//control name comes here
var txtValue = control.value;
//control also return null
if (txtValue.length > 0) {
alert(txtValue.length);
}
}
txt_box.Attributes.Add("onchange", "loadValues(this);");
try the following
txt_box.Attributes.Add("onchange", "loadValues(this)");
function loadValues(controlName) {
if($(controlName).attr('id').length > 0){
var id= $(controlName).attr('id');
var val= $('#'+id).val();
alert(val);
}
}

Check if adobe reader is installed on client machine

Currently I am working on a web page which will tell user about certain configurations on client machine. Out of this there is also requirement of detecting if Adobe Reader is installed on client machine or not. I am using ASP.NET/C#.
I have looked the following url for the answer
"Check Adobe Reader is installed (C#)?" but the code look into the server registry entires where IIS is installed and not the client machine where browser is running.
Is it possible to detect if Adobe reader is installed on client machine and not the server which is hosting the website?
pls, check the script below, it worked fine for me in IE, FireFox and Chrome
<html>
<body>
<script type="text/javascript">
var found = false;
var info = '';
try
{
acrobat4 = new ActiveXObject('PDF.PdfCtrl.1');
if (acrobat4)
{
found = true;
info = 'v. 4.0';
}
}
catch (e)
{
//???
}
if (!found)
{
try
{
acrobat7 = new ActiveXObject('AcroPDF.PDF.1');
if (acrobat7)
{
found = true;
info = 'v. 7+';
}
}
catch (e)
{
//???
}
if (!found && navigator.plugins && navigator.plugins.length>0)
{
for (var i = 0; i<navigator.plugins.length; i++)
{
if (navigator.plugins[i].name.indexOf('Adobe Acrobat') > -1)
{
found = true;
info = navigator.plugins[i].description + ' (' + navigator.plugins[i].filename + ')';
break;
}
}
}
}
document.write("Acrobat Reader Installed : " + found);
document.write("<br />");
if (found) document.write("Info : " + info);
</script>
</body>
</html>
hope this helps, regards
I used this script and called it on ready function :
Note: i used the alerts here just to know how to use it.
<script type="text/javascript">
$(document).ready(function () {
alert(getAcrobatInfo().browser);
alert(getAcrobatInfo().acrobat === "installed");
alert(getAcrobatInfo().acrobatVersion);
});
var getAcrobatInfo = function () {
var getBrowserName = function () {
return '<%=Session["browser"].ToString()%>';
};
var getActiveXObject = function (name) {
try { return new ActiveXObject(name); } catch (e) { }
};
var getNavigatorPlugin = function (name) {
for (key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name == name) return plugin;
}
};
var getPDFPlugin = function () {
return this.plugin = this.plugin || function () {
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
}
else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF') || getWebKitPlugin();
}
}();
};
var getWebKitPlugin = function () {
for (var key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name && plugin.name.substring(0, 6) == "WebKit" && (plugin.name.indexOf("pdf") != -1 || plugin.name.indexOf("PDF") != -1)) return plugin;
}
};
var isAcrobatInstalled = function () {
return !!getPDFPlugin();
};
var getAcrobatVersion = function () {
try {
var plugin = getPDFPlugin();
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if (plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch (e) {
return null;
}
}
// The returned object
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
</script>
Also add this code behind:
public void detectBrowser()
{ //Set the Browser session variable
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Session["Browser"] = browser.Browser;
}
Hope it helps.

Categories

Resources