This isnt working, not sure what is wrong. I dont want to use href onclick at all, i usually use an id on ahref links then execure javascript that way but i need to pass parameters from the link to the function, not sure if there are other alternatives?
code using the parameters isnt shown, its basiacly a forum link but its loading the topic into a div
function changetotopicdetails(topicid, topicname) {
$('#loadingAjaxs').show();
$('#flubestext').hide();
#following.Title
I would usually do something like
$('#changeuserstwohour').click(function () {
$('#userswrap').load('#Url.Action("TrendingUsersMenutwohr", "Trending")');
});
but by doing so i cant send parameters to the function during a loop (list of topics)
any suggestions?
Answers pointed out that i need the variables passed to a new {}
$('#changeuserstwohour').click(function () {
$('#userswrap').load('#Url.Action("TrendingUsersMenutwohr", "Trending", new {#theid = id, #thename = name})');
});
You could do your usual click function, eventListener or bind and use data values to indicate you username and trending values.
so your tag would look like
<a href="#" data-id='#following.Id' data-short-name='#following.ShortName'>#following.Title</a>
and then your usual click function which would look like
$('#changeuserstwohour').click(function () {
$('#userswrap').load('#Url.Action($(this).data(id), $(this).data(short-name)');
});
you may need to use .each() if you have multiples or call it after each ajax load to make sure its listening to the new objects. I haven't tested this as I dont really have the functions but this should work! Please let me know how it goes and if you have another question :)
A combination of both techniques provided so far is what you're probably really after.
Your markup for your individual action links would look like:
<a href="#" class="selectorForYourActions" data-id='#following.Id' data-short-name='#following.ShortName'>#following.Title</a>
and then your on-click callback which would look like
$('#idOfContainerYourLoopCreatesItemsWithin').on("click", "a.selectorForYourActions", function () {
$('.userswrap').load('#Url.Action($(this).data(id), $(this).data(short-name)');
});
This will catch any dynamically created items that match that class if they are created within the element selected by the ID selector, but only handle clicks on anchor tags with the marker class, so you can both have many of those anchors with unique (or no) Ids and anchors with normal (or different) functionality.
Related
OK I am sure I am doing something simple fundamentally wrong but am unable to resolve this issue on my own. I have tried googling and searching this forum and reading through the relevant parts of the jquery documentation.
If you need any further information please let me know. Many thanks in advance.
What I am trying to do:
I have a table showing details of various tests at the bottom of which I have a button to ad a new test. As each test comprises several rows of the table I have a template in a hidden div which I have cloned and appended to the live table. I am the using jquery to add appropriate classes and ids based on a variable integer for the sake of uniqueness. I am also attempting to add a click event to an image within one of the table cell to delete the rows relating to that particular test.
My current function
function newTest(sampleID){
var testID = $("#testCount").val();
$("#newTest tr").clone(true)
.addClass("test"+testID)
.appendTo("#testsTable"+sampleID);
$(".newdelbox:first")
.attr("id","testDelete"+testID)
.addClass("delbox")
.removeClass("newdelbox");
$(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
testID++;
$("#testCount").val(testID);
}
What I need to happen
Function to be called when image is clicked.
What is happening
Function is called only when script is assigned (not clicked). Function will not subsequently run when clicked. I am seeing no errors within the console.
What I have tried
chained to preceeding code:
.click(delSample(testID));
.on("click",delSample(testID));
.bind("click",delSample(testID));
As new line within function:
$(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
document.getElementById("testDelete"+testID).onclick(delSample(testID));
document.getElementById("testDelete"+testID).addEventListener("click",delSample(testID),false);
try this:
.click(function(){
delSample(testID);
});
OR
.on("click",function(){
delSample(testID);
});
i do not know of your html but i supose something like
.on("click",function(){
var current_id = jQuery(this).attr('id');
delSample(current_id);
});
just locate your id
I am building an MVC 5 web app using Visual Studio 2013.
I am trying to create a list of Courses using anchor tags which when clicked will pass as a parameter the selected Course to a Javascript function. The Javascript function will in turn use Ajax to call a second function to retrieve a list of Students enrolled on the selected Course.
In the View I have:
#model IEnumerable<School.Models.Course>
...
#foreach (var item in Model)
{
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="#item.CourseName">#item.CourseName</a>
}
The Course list gets created as expected:
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="Chemistry">Chemistry</a>
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="Physics">Physics</a>
My Javascript function is defined as follows:
function selectedCourse() {
var selectedCourseName = $(this).data('cname');
}
The code reaches the Javascript function but the value of selectedCourseName is always 'undefined'.
Am I missing something really basic for this to work?
Any help would be greatly appreciated.
Walter
The reason that it's not working is because the context of this on an inline event handler is not the element itself, but the window element. Change your code so that the handler is applied separately from your markup, this is a best practice anyway, and the context will be correct.
$('.selectedCourse').on('click', function(e) {
e.preventDefault();
var selectedCourseName = $(this).data('cname');
...
});
An alternative, and one I don't recommend, is to add a parameter to your inline handler and pass this as the parameter. The value of the parameter will be the element that was clicked.
Don't do this!
See examples at http://jsfiddle.net/cJZpK/
I have a edit link with class "icon-edit" from twitter-bootstrap. I want to show downloading image when user click on this button in javascript. I did like this:
var editLink = $('.icon-edit');
editLink.onclick = function () {
document.getElementById("editLoading").style.visibility = "visible";
}
It doesn't work.
I think the proper CSS style you need to change is display to have the value "block" (or "inline").
In addition, you shouldn't/can't mix jQuery and Javascript like that. If you work with a jQuery object (using $("")), then you should use jQuery methods. If you want to use plain Javascript, then you can use Javascript methods.
In your case, you select an element by class, with jQuery. But then you attempt to bind the onclick handler to the selected element with .onclick, which is plain Javascript.
You should use:
$(".icon-edit").on("click", function () {
$("#editLoading").show(); // Basically the same as: $("#editLoading").css("display", "block");
});
Instead of saying "It doesn't work.", you should explain what's happening. Did you check your browser's console? Do you get error messages? Does something freeze? Did you attempt to debug in any way, even by placing alert statements in places to see how far the code gets?
I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});
For example, for accessibility reasons I want my onfocus and onmouseover to have identical values. For the sake of maintainability I want to declare this once only.
What I'd like to be able to do is this:
<a onmouseover,onfocus="assist('hello');">linktext</a>
But, of course, that would be too easy, and doesn't work. What's the best way I can achieve this DRYing out of my tags?
The better way is to move all your event handlers out of the HTML and into javascript.
<a id="some_id">link text</a>
(You don't need to use an ID, it's just for ease of demonstration.)
var link = document.getElementById('some_id');
link.onmouseover = link.onfocus = function() {
assist('hello');
};
If you wanted to take it to the next level, you could generalise it across many links. This example uses jQuery.
link text
another link
Then you apply the event handler to all the links in one go (very dry!)
$('a.assist').bind('mouseover focus', function() {
assist(this.href); // you'd need to clean up the href here, but you get the picture
});
Best I can think of is to use a function, set both events to call the function and put the common code in there.