I have an anchor tag with the href set as:
; Click Here
When I click on Click here, it redirects to http://mywebsite/$myfunction(1234).
This page obviously does not exist. How do I ensure that clicking on the above link does not map to the root? I would like it to call the javascript function.
Note: I cannot do this:
Click Here.
The reason is that we have a 3rd party crawler (no source code available) that searches for anchor tags on our page and picks up the href part for the link and fails if not found in the exact format $myfunction(param)$
HTML anchor link specification does not support adding a javascript function as the value of the href attribute. Per https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a you should add an URL or an URL fragment.
If you need to add it this way you can add the onclick event to anchor like this:
; Click Here
Then you just need to make sure you function returns false and/or calls event.preventDefault this is to avoid redirection.
You can use the onClick event handler to call the function and prevent the default action of the link with event.preventDefault().
Click Here
<br/>
Link that does NOT have its default action prevented
<script>
function myfunction(e){
e.preventDefault();
console.log("Function myfunction() called");
}
function function2(){
console.log("Function function2() called");
}
</script>
have you tried to invoke the onClick handler?
; Click Here
Another approach is the following
function MyFunction(param){
alert(param);
}
(function() {
var aElements = document.getElementsByTagName("a");
var aList = Array.prototype.slice.call(aElements);
aList.forEach(function(elem) {
var regex = /\$(.*?)\$/g;
var result =regex.exec(elem.href);
if (result != undefined && result.length > 0) {
elem.onclick= function(){
//executes function
eval(result[result.length-1]);
//prevents href action;
return false;
}
}
});
})();
I have a function
<br/>
I have a normal link
<br/>
I have another function
You can use the 'onclick' attribute of the link tag instead of href,
For example "Click Here"
Related
__doPostBack() function works in FF and IE,but not working in safari and chrome.
I have following code in my asp.net c# application
ASPX Code
Click here
JS Function
function SetPosition() {
__doPostBack('ahref', 'link');
}
CS Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Other code is here
}
else if (Request.Params["__EVENTARGUMENT"] != null && Convert.ToString(Request.Params["__EVENTARGUMENT"]).Trim() == "link")
{
Session["TopPossition"] = "9999";
}
}
I believe you need to pass the server control id as the EventTarget and not the client id when you use __doPostBack call. Try changing the __doPostBack call as so...
<a id="someclientid" name="someuniqueid" href="javascript:void(0);" onclick="__doPostBack('someuniqueid', '');">val</a>
By default, controls use __doPostBack to do the postback to the server. __doPostBack takes the UniqueID of the control (or in HTML, the name property of the HTML element). The second parameter is the name of the command to fire.
The onclick event handler needs to supress the links default behavior to navigate to what's specified in the href attribute.
It should be like this:
<a href="#" onclick="SetPosition(); return false " >Click here</a>
you can provide redirection in SetPosition() if required.
I have written the code on
ascx script:
<script src="JScripts/jquery.alerts-1.1/jquery.alerts.js" type="text/javascript"></script>
<script>
$(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
</script>
and on
Code behind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
the problem is alert box is automatically getting disabled after some time when page load fully
What could be the reason that the alert box is being disable after clicking on OK button and how to call the callAlert function in proper way.
If you are using Master page or pages then you won't get the Client Id of the button as you are declared it should be declared as $('#<%=ImageButton1.ClientID%>') or $('[id$=ImageButton1]') hope it will solve you problem.
$(document).ready(function(){
$('#<%=ImageButton1.ClientID%>').click(function() {
alert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
You can try to put the following line before the function
$(document).ready(function() {
This will make it:
$(document).ready(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
});
If you wait till the page is ready, the alert box won't be overwritten (I hope x)).
Also when you check that text box, check if the condition is false, then give the alert.
Is the condition not false? Build in a check to check if the condition is really true. If so? Redirect.
EDIT:
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
//redirect
else
return
OK, so first it's important to understand that $(function(){... and $(document).ready(function() {... are equivalent, and nothing inside either will execute until the page is fully loaded. In other words, there's no need to use
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
That can be removed. Also, I see that you're probably using web forms. Be mindful that the Id attribute that will be rendered is not equal to the Id of the control attribute. In other words, if you have a runat="server" control with an Id of ImageButton1, using the syntax $('#ImageButton1') in your jQuery won't work.
Taking this into account, I've added an example below that uses selectors based on class attributes.
<script type="text/javascript">
$(function () {
$('.ImageButton1').click(function (e) {
var text = $('.TextBox1').val();
var redirect = true;
if (!text) {
redirect = confirm('Empty...are you sure?');
}
if (redirect) {
window.location.href = 'http://your-redirect-here.com';
}
});
});
</script>
<input class="TextBox1" type="text" />
<input class="ImageButton1" type="button" value="Click" />
That should get you where you want to go. Let me know if you have any questions.
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
{
//redirect
} else
{
return false;
}
Put this after jAlert Box:
return false;
And call the function like this:
return callAlert();
I need to detect a postback in the frontend so I can use it with JQuery to change a class on page load. How can I do this?
You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
Stolen from this post:
On the server side have this
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
On client side this
if(isPostBack) {
// do your thing
}
I put this variable inside the header tag of my asp.net web forms page.
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
The var contains a Boolean. The comparison can probably be shortened.
Simple:
if you're using jquery it has to go after(jquery goes nuts otherwise):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
Then
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});
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...
How to hide a div if validation summary is available in javascript/Jquery.
if(yourCondition){
$("div#mydiv").hide()
}
what is validation summary?
var validationSummary = $('#<%= this.ValidationSummary.ClientID %>');
var myDiv = $('#myDiv');
if (validationSummary.length || validationSummary.is(':visible')) {
myDiv.hide();
}
the cause for .is(':visible')is, that i don't know if an empty validationSummary renders the html-tags either or not. if not, you can leave out the .is()-check
you can use the HeaderText property to clean the HTML from inner ValidationSummary, seek in console for your content and you can see what change to erase.
I use this: create an element and call javascript function
ValidationSummary ID="vsGeral" runat="server" HeaderText="create element and call the HTML clean function destroy "
var validationSummary = $('[id$=vsGeral]');
if (validationSummary.length || validationSummary.is(':visible')) {
function destroy() {
$("[id$=vsGeral]").html("");
}
}