On some links on my HTML page I have a special CSS class, that when clicked, I make a ajax call to a click.aspx page and track the click.
blah-1
$(".click").bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
So what is happening is the value of source, after clicking a few links (that open in a new window) becomes:
source=blah1
then it becomes
source=blah1,blah2
Maybe you need to change it to:
$(".click")each(function(i) {
$(this).bind("click", function() {
$.get("/click.aspx?&source=" + $(this).attr("id"));
});
});
so that each is processed separately...
Related
I started down the path of adding an UpdatePanel to my Sharepoint page so that I can respond to events that take place (such as the checking of checkboxes and mashing of radio buttons, etc.). That so far has, however, been wrought with frustration and all that rot, as can be deduced from this question.
So I'm now probably going to traverse (no pun intended) the jQuery route and am trying to figure out/find out how to add jQuery to a WebPart.
Currenlty, I am dynamically creating controls in C# based on what a user selects in the WebPart's Editor (if they elect to show Section 1, I create all the controls for Section 1, etc.).
As an example, I'm currently conditionally creating a RadioButton in C# like so:
var radbtnEmployeeQ = new RadioButton
{
CssClass = "dplatypus-webform-field-input"
};
Now if I want to add jQuery to it, I can add an ID to it like so:
var radbtnEmployeeQ = new RadioButton
{
CssClass = "dplatypus-webform-field-input",
ID = "radbtnEmp"
};
...and then add jQuery of this nature (pseudocode):
$('radbtnEmp').click {
// visiblize/invisiblize other controls, assign certain vals to their properties
}
This seems feasible to me, but how do I go about adding jQuery to a WebPart? Is it a matter of adding a .js file at the same directory level as the *.ascx.cs file, and then referencing it from the *.ascx.cs file, or...???
UPDATE
For POC testing, I added a file to my project named "directpaydynamic.js" with this content:
<script>
$(document).ready(function () {
$('input:radio[name=radbtnEmp]:checked').change(function () {
if ($("input[name='radbtnEmp']:checked").val() == 'Employee?') {
alert("radbtnEmp checked");
}
else {
alert("radbtnEmp not checked");
}
});
});
</script>
(derived from an example here)
...and reference the .js file in my *.ascx.cs file like so:
SPWeb site = SPContext.Current.Web;
site.CustomJavaScriptFileUrl = #"C:\Projects\DirectPaymentWebForm\DirectPaymentSectionsWebPart\DPSVisualWebPart\directpaydynamic.js";
(I dragged the .js file onto the code to get the path)
However, running the solution and mashing the radiobutton causes neither alert() to display, so I reckon I've taken the road that was for a good reason less traveled.
UPDATE 2
Realizing I didn't need the script business (as this is a .js file, not an html file), I removed those, and also put an "at any rate" alert() in the jQuery:
$(document).ready(function () {
alert("What's new, pussycat, whoa-oh-oh-oh-OH-oh?");
$('input:radio[name=radbtnEmp]:checked').change(function () {
if ($("input[name='radbtnEmp']:checked").val() == 'Employee?') {
alert("radbtnEmp checked");
}
else {
alert("radbtnEmp not checked");
}
});
});
...but I still endure an alarming dearth of alerts...
Use below code on Page load method
string url = SPContext.Current.Site.ServerRelativeUrl;
if (!url.EndsWith("/"))
{
url += "/";
}
HtmlGenericControl styleCss = new HtmlGenericControl("link");
styleCss.Attributes.Add("rel", "stylesheet");
styleCss.Attributes.Add("type", "text/css");
styleCss.Attributes.Add("href", url + "Style Library/css/style.css");
HtmlGenericControl JsLink = new HtmlGenericControl("script");
JsLink.Attributes.Add("src", url + "Style Library/js/jquery.min.js");`enter code here`
this.Controls.Add(styleCss);
this.Controls.Add(JsLink);
The thing to do (or perhaps I should write, "a" thing to do) to get this to work is to add code like the following to the end of the WebPart's *.ascx file:
<script>
$(document).ready(function () {
alert("The ready function has been reached");
});
$(document).on("change", '[id$=ckbxEmp]', function () {
alert('Function has been reached');
if ($(this).is(":checked")) {
alert("Checked");
} else {
alert("Not checked");
}
});
</script>
The above works like a champ.
I am using MVC 4 with java script.
Today's i have a requirement to disable to back button in all browsers, need to prevent to go-back to previous page(home page) after click on log-out button with the help of back button of browsers.
Help Me thanks.
Try this
JavaScript Code Sample
javascript code to all the pages where we need to disable the browser back button.
<script type="text/javascript">
//Disable Back Button In All Browsers.
function DisableBackButtonAllBrowsers() {
window.history.forward()
};
DisableBackButtonAllBrowsers();
window.onload = DisableBackButtonAllBrowsers;
window.onpageshow = function (evts) { if (evts.persisted) DisableBackButtonAllBrowsers(); };
window.onunload = function () { void (0) };
</script>
ActionResult code sample in mvc 4
Code for response to ActionResult for log-out in MVC 4. i.e.
/// <summary> /// Logs user out and renders login <see cref="View"/> /// </summary> /// <returns>Login <see cref="View"/></returns>
public ActionResult Logout()
{
//Disable back button In all browsers.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
FormsAuthentication.SignOut();
return View("Login");
}
Try this, may it will help you.
Link: http://hightechnology.in/how-to-disable-browser-back-button-in-asp-net-using-javascript/
Javascript Code:
<script type = "text/javascript" >
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
You can use as below :
<script type="text/javascript" language="javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (0) }
</script>
Possible duplicate..
there is a solution mentioned befor here:
set cachebality to noCache..
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Disable browser "back" button
Disable browser's back button
Ideally you want to prevent your session history from getting populated in the first place.
location.replace(url)
From: https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
The Location.replace() method replaces the current resource with the one at the provided URL. After using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
If the session history is empty, the back button is disabled. If your app depends heavily on form submission, jQuery makes it easy to convert form variables to a query string for use with location.replace.
function submitForm() {
// this eliminates issues with the back button
window.location.replace('?' + jQuery.param(jQuery('form').serializeArray()));
}
I am working with an ASP.NET site with a C# back end. There is a .Master page where the tag is, and other search pages on the site will search when you hit enter after filling out the form. However we have one page that has a few text boxes and when you hit enter to search, it appears to just refresh and reload the page without searching. In order to search you have to hit the search button (which is an igtxt:WebImageButton ). All of the solutions I have found to this issue so far involve people using javascript to call some kind of function on submit. As far as I know there is no javascript being called when you hit the search button, it is all in the C# code. Once again I find myself searching SO and other sites for an answer but none of the solutions seem to fit my situation. The form tag is as follows:
<form id="form1" runat="server">
The web image buttons call a btn_SearchClick function that runs the search code. But since the form is started in the .Master file I can't edit that as it would effect all other pages as well. Is there any way to have enter call the btn_SearchClick from the form without having to put it in the form tag? I'm not sure what would've changed to cause this behavior on one page and none of the others.
if (!IsPostBack)
{
TextBox1.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
}
<SCRIPT type=text/javascript>
function doClick(buttonName,e)
{
//the purpose of this function is to allow the enter key to
//point to the correct button to click.
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13)
{
//Get the button the user wants to have clicked
var btn = document.getElementById(buttonName);
if (btn != null)
{ //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</SCRIPT>
or u can use default button.it's work while cursor's in this box
protected void Page_Load(object sender, EventArgs e)
{
this.Form.DefaultButton = this.btnSubmit.UniqueID;
}
Add some jquery to control the Enter key behavior on your textbox. Something like this:
$(function() {
$('#<%=txtTextbox.ClientID%>').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
$('#<%=btn_SearchClick.ClientID%>').click();
}
});
});
I'm a newbie in C# language and I'm quite lost trying to extend an already existent and non-mantained .NET web application.
The application has a Web User Control with a button that, when clicked, refreshes its inner content through this piece of JavaScript code within the .ascx:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler(sender, args) {
var btnId = '<%= btn.ClientID %>'
if (sender._postBackSettings.sourceElement.id == btnId) {
// loads a popup with the new content
}
}
This works perfectly. The problem comes when I try to add a new Web User Control which does practically the same, but of course through a different button and loading different content. I replicated the code structure, both in the front and in the back, but I cannot get the second endRequestHandler to execute:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandlerStats);
function endRequestHandlerStats(sender, args) {
alert("I'm here!");
var btnStatsId = '<%= btnStats.ClientID %>'
if (sender._postBackSettings.sourceElement.id == btnStatsId) {
// loads another popup
}
}
Suprisingly, that alert pops when the first btn is clicked, but not with the second btnStats.
I think the problem is caused because the btnStats doesn't trigger a request, but as I said I am new at this and I have no idea why. And the operation is done properly, the only thing that doesn't work is what is done in that script. Any hints, please?
I believe that is what the if condition is for - it is to check which button was clicked. The event model of JavaScript doesn't allow multiple handlers to be attached (at least not without some extra work), so this is probably the next best thing.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler(sender, args) {
var btnId = '<%= btn.ClientID %>'
var btnStatsId = '<%= btnStats.ClientID %>'
if (sender._postBackSettings.sourceElement.id == btnId) {
// loads a popup with the new content
}
else if (sender._postBackSettings.sourceElement.id == btnStatsId) {
// loads another popup
}
}
I'm trying to get jQuery to bind an onClick function when the document loads to my radio buttons.
ASP goes back to the database and finds all the open markers and then it sends a response to the page with the raw HTML to make a radio button and an image of the marker. What I need to do is have jQuery (or anything for that matter) bind an onClick that will signal what one is clicked so I can send that markerId back to the database to attach it to a person.
Here is a rough jsFiddle of what I've tried so far. In debugging I added alerts in the each function and I see them 3x like I should but the attr('id') comes back undefined.
This is the html that puts the radio buttons on the form
<br />
<p>Select open marker for new user:
<% getMarkers(); %>
</p>
This is the codebehind for that call
while (reader.Read())
{
if (readIndex % 3 == 0)
markerTable += "<tr>";
string markerId = reader["marker_id"].ToString();
string fileName = reader["marker_filename"].ToString();
markerTable += "<td><input type=\"radio\" name=\"openMarker\" value=\"" + markerId + "\" " +
"id=\"oMrk" + markerId + "\"><label for=\"oMrk" + markerId + "\"><img src=\"/Markers/" +
fileName + "\" /></label></input></td>";
readIndex++;
if (readIndex % 3 == 0)
markerTable += "</tr>";
}
if (readIndex % 3 != 0)
markerTable += "</tr>";
markerTable += "</table>";
}
else
markerTable = "<p>No empty markers. Please delete a user to continue.</p>";
sCon.Close();
return markerTable;
The fiddle I posted has the source pasted into it from this function.
I have two questions.
Why does this not work? It seems like it should, I am getting 3 elements from my jQuery selector statement, It's being called from $(document).ready() why are the attributes undefined?
Is there a better way to do this? I was planning on putting the value in a page variable and then sending it with an ASP button back to the server to a stored procedure to add that marker with some text from another field back to the database. I realize I could add the onClick event into the response html, but dang it I need to understand why what I'm doing isn't working.
I'm pretty new to web, so if I am way off the mark procedurally, I am open for suggestion.
LINK
$(document).ready(function () {
$('input:radio').each(function (radElem) {
var radId = $(this).attr('id');
alert(radId);
});
$('input:radio').on('click', function () {
alert('Clicked');
});
});
$(document).ready(function () {
$('input:radio').on('click', function() {
alert($(this).attr('id'));
});
});
Do you need to send the value to the server while staying on the page? (via ajax)
or do you need to post the form to another page?
It doesn't work because you are trying to bind onClick instead of
just click
The other answers have provided the jQuery for you. In the each you
just need to use this keyword
I tested this in a fiddle, it works. Others have provided similar answers, but here's the fiddle anyway: THE FIDDLE
$(document).ready(function () {
$("input:radio").each(function () {
var radId = $(this).attr('id');
alert(radId);
$(this).on('click', function () {
alert('Clicked');
});
});
});
As for a better way to do what you are trying to accomplish, I do not have a firm grasp of what you are trying to do really, sorry. It feels though, like you should be initially populating this in asp.net, but the constraints of your page may not make this possible. I can't say.
Also, go ahead and pick one of the previous answers, I just wanted to explain to you why what you had wasn't working.