<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);">
Click to do something
</a>
I want to get the data-id and data-option values inside the function goDoSomething(10, 21) I have tried to use this reference: this.data['id'] but it did not work.
How can I do this?
You can achieve this $(identifier).data('id') using jquery,
<script type="text/javascript">
function goDoSomething(identifier){
alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
javascript : You can use getAttribute("attributename") if want to use javascript tag,
<script type="text/javascript">
function goDoSomething(d){
alert(d.getAttribute("data-id"));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
Or:
<script type="text/javascript">
function goDoSomething(data_id, data_option){
alert("data-id:"+data_id+", data-option:"+data_option);
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
Click to do something
</a>
Like this:
$(this).data('id');
$(this).data('option');
Working example: http://jsfiddle.net/zwHUc/
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a element and gets the data-id attribute from it.
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at
https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
here is an example
<a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>
$('.facultySelecter').click(function() {
var unhide = $(this).data("faculty");
});
this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get
you can directly use anchor id or data-action attributes to trigger the event.
Html Code
<a id="option1" data-action="option1" data-id="10" data-option="21" href="javascript:void(0);" title="Click Here">Click Here</a>
jQuery Code:
$('a#option1').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option')) ;
});
OR
$('[data-action="option1"]').on('click', function(e) {
e.preventDefault();
console.log($(this).data('id') + '::' + $(this).data('option'));
});
User $() to get jQuery object from your link and data() to get your values
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>
Related
I have dropdown with different links, before that i have 2 radio buttons where you could select "mode".
<div class="radio">
<label><input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label><input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://example.com/index.php?mode=">Site1</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site2</a></li>
<li><a target="_blank" href="http://example.com/index.php?mode=">Site3</a></li>
</ul>
</div>
And i use this code snippet to detect what mode is selcted and add it to var mode:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
});
});
What i want to do is to add javascript var $mode to href tags.
href="http://example.com/index.php?mode={$mode}
How could i accomplish this ?
I think only way would be to do this with some javascript function ?
Its not possible to just "print" var to href ?
JSFIDDLE: https://jsfiddle.net/DTcHh/18683/
Use data-* attribute to keep static href value to be used later. .change() will trigger change event initially to set the value of href attributes.
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function() {
var mode = myRadio.filter(':checked').val();
$('ul.dropdown-menu a').prop('href', function() {
return this.getAttribute('data-href') + mode;
})
}).change();
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="radio">
<label>
<input type="radio" name="mode" checked="checked" value="mode1">MODE1</label>
</div>
<div class="radio">
<label>
<input type="radio" name="mode" value="mode2">MODE2</label>
</div>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a target="_blank" href="http://site1.com/index.php?mode=" data-href="http://site1.com/index.php?mode=">Site1</a>
</li>
<li><a target="_blank" href="http://site2.com/index.php?mode=" data-href="http://site2.com/index.php?mode=">Site2</a>
</li>
<li><a target="_blank" href="http://site3.com/index.php?mode=" data-href="http://site3.com/index.php?mode=">Site3</a>
</li>
</ul>
</div>
Fiddle here
Check this fiddle I've modified for you: https://jsfiddle.net/so2fw1o4/1/
Add this to your myRadio.on('change', function
//here change the urls
$('.dropdown-menu a').each(function(){
$(this).attr('href', $(this).data('url') + mode)
})
And you will need to add data attribute to each link to store initial link
<a target="_blank" data-url="http://site. com/index.php?mode=" href="http://site. com/index.php?mode=">Site1</a>
Try this :-
$(document).ready(function() {
var myRadio = $('input[name=mode]');
myRadio.on('change', function () {
var mode=myRadio.filter(':checked').val();
$("ul.dropdown-menu li a").each(function(){
$(this).attr('href',$(this).attr('href').split('?')[0] + "?mode=" + mode);
});
}).change(); //trigger on page load
});
DEMO
Although you already have some answers here, I figured I would post another alternative (not necessarily any better).
You could add a class to each link, handle their click events, and set the new window's location yourself to achieve a similar effect.
The following is a code snippet modifying the jQuery in your fiddle:
$(document).ready(function() {
var myRadio = $('input[name=mode]');
var mode = myRadio.filter(':checked').val(); // Initial setting
myRadio.on('change', function () {
mode=myRadio.filter(':checked').val();
});
$('.mode-link').click(function(e) {
e.preventDefault(); //stop the click action
// Check if the mode has been set
if (mode) {
// Create the href value
var newHref = $(this).attr('href') + mode;
// Open the new tab/window with the correct href value
window.open(
newHref,
'_blank'
);
}
});
});
I simply added the mode-link class to each a element in the dropdown, stored the radio button value change in a new variable mode, added the click event handler, and finally handled the click event to create the new href value and open a new tab/window with that location.
If you didn't want the new tab/window you could simply set location.href = newHref but this wouldn't mimic the new tab/window opening, hence why I use window.open().
I have a modified sample here: JSFiddle
Here is a simple example of what I'm trying to do, I have code in HTML and my aim is to disable the three hyperlinks #validate,#organize and #export:
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>
When I'm trying to call the following, nothing happend. I'm using jQuery 1.11.4 and I've read that the methods for disabling event listeners have changed since 1.7. So I would like to know if there is an error in my JavaScript code below or some new changes:
$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');
One way would be to temporarily set the onclick to null, but store the original element onclick in the element or jquery object (e.g. data). With a helper function you can switch the elements on or off:
function setEnabled($a, Enabled ){
$a.each(function(i, a){
var en = a.onclick !== null;
if(en == Enabled)return;
if(Enabled){
a.onclick = $(a).data('orgClick');
}
else
{
$(a).data('orgClick',a.onclick);
a.onclick = null;
}
});
}
Which can be called with something like:
setEnabled($('#validate'), false);
(also works on jquery objects with multiple elements because of the each)
Example fiddle
You need to unbind the click event (which was declared inline) as follows.
document.getElementById("import").onclick = null;
document.getElementById("validate").onclick = null;
document.getElementById("organize").onclick = null;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>
You could have jQuery take over your inline event, so that you can off() it later. Note that off() does remove the listener. You can't really disable it unless you put some logic in the handler itself to bail out if it shouldn't be running.
function switchScreen(screenName) {
console.log(screenName);
};
$(function() {
$('#menuitems a').each(function() {
var oldClick = this.onclick;
$(this).on('click', $.proxy(oldClick, this));
this.onclick = null;
});
$('#import').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >>
<a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
</p>
try unbind instead of Off since click event is defined inline, if click is attached using on then it will work with off.
Event attached through javascript doesn't recognize by jquery, so javascript and jquery mixed approached can't work properly - that's the reason jquery
.off('click'); doesn't detach click event.
Modify html:
<p id="menuitems" class="inline textcenter">
<a id="import" href="javascript:void(0);">IMPORT</a> >>
<a id="validate" href="javascript:void(0);">VALIDATE</a> >>
<a id="organize" href="javascript:void(0);">ORGANIZE</a> >>
<a id="export" href="javascript:void(0);">EXPORT</a>
</p>
Attach click event using jquery:
$(document).ready(function () {
$('#import').on("click", function () {
switchScreen('Import');
});
$('#validate').on("click", function () {
switchScreen('Validate');
});
$('#organize').on("click", function () {
switchScreen('Organize');
});
$('#export').on("click", function () {
switchScreen('Export');
});
});
Disable click event whenever required:
$('#import').off('click');
$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');
The above approach works for all standard browsers but just for IE we can have one more approach:
$('#validate').attr("disabled", "disabled");
$('#organize').attr("disabled", "disabled");
$('#export').attr("disabled", "disabled");
<a aria-expanded="false" data-toggle="tab" href="#pictures">
<i class="pink ace-icon fa fa-gift bigger-120"></i>
Pictures
</a>
I want to wire on click #picture event to alert some message so I add
$(document.ready(function() {
$("#pictures").click(function(){
alert('clicked!');
});
})
but this doesnt work, I've got no error messages inside firebug console.
Jquery is loaded before correctly.
In your html there is no element with ID pictures, change it, like so
$("#pictures").click(function(){
alert('clicked!');
});
// or use selector like this, if you can't change html
$('a[href="#pictures"').click(function(){
alert('clicked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a aria-expanded="false" data-toggle="tab" href="#pictures" id="pictures">
<i class="pink ace-icon fa fa-gift bigger-120"></i>
Pictures
</a>
Update:
Also you have error in this line
$(document.ready(function() {
change it
$(function() {
// put your code
});
Did You try tout set the click handler on document?
jQuery(document).on('click', '#pictures', function(e) {
alert('clicked');
});
You also have to add :
id="pictures"
In your . Or an y other selector.
If you want to still use the #picture in href check on bellow code
jQuery(document).ready(function($) {
$("a[href='#pictures']").click(function(){
alert('clicked!');
return false;
});
})
Try this Demo, even changed some markup for the same.
$(document).ready(function() {
$("#pictures").click(function(){
alert('clicked!');
});
})
My JSP has a tag whose id is getting populated dynamically:
c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview()" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
</c:forEach>
JS:
function GetAdvisorReview(){
var domElement =$(event.target);
console.log(domElement.attr('id'));
alert($(this).attr('id'));
alert(this.id);
alert(event.target.id);
}
Every alert is giving undefined.Please tell me what is wrong with the code.Thanks in advance!!!!
Try using this inside the onclick()
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview(this)" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
And the Js should be:
function GetAdvisorReview(e){
alert(e.id); //Get the Id
}
Where the e is the element that fired the event.
You have HTML markup errors in your loop. I'm assuming those are SO
pasted typos only. Otherwise, fix those as well as my code block displays.
An event listener solution is the approach I would take.
remove the onclick, replace it with a class:
<c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" href="#" class="advisors" data-toggle="modal" data-target="#datepay">
<img src="assets/img/services/Icon_Reviews.png" width="50" alt="">
</a>
</c:forEach>
and then listen for that class click event to happen
$(".advisors").click(function() {
alert($(this).attr('id'));
});
demo:
http://jsfiddle.net/pcx6csph/1/
Wilfredo P's is a good approach, but I would suggest to avoid using inline JS by adding a CSS class to all your links and to use addEventListener() (pure JS) or .on() (jQuery) to bind the click event:
JSP:
c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" class="someClass" href="#" onclick="GetAdvisorReview()" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
</c:forEach>
Pure JS:
var elems = document.getElementsByClassName("someClass");
for ( i=0; i<elems.length; i++ ) {
elems[0].addEventListener("click", function() {
alert( elems[0].getAttribute("id") );
});
}
jQuery:
// jQuery
$(document).ready(function() {
$(".someClass", this).on("click", function() {
alert( $(this).attr("id") );
});
});
Demo:
// Pure JS
var elems = document.getElementsByClassName("someClass-js");
for ( i=0; i<elems.length; i++ ) {
elems[0].addEventListener("mouseup", function() {
alert( this.getAttribute("id") );
});
}
// jQuery
$(document).ready(function() {
$(".someClass-jquery", this).on("click", function() {
alert( $(this).attr("id") );
});
});
a {
display: block;
}
p {
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>With Pure JS:</p>
<a id="some-link-1" class="someClass-js" href="#">Some Link 1</a>
<a id="some-link-2" class="someClass-js" href="#">Some Link 2</a>
<p>With jQuery:</p>
<a id="some-link-3" class="someClass-jquery" href="#">Some Link 3</a>
<a id="some-link-4" class="someClass-jquery" href="#">Some Link 4</a>
If you want to have the sender element and the event object, you should do this instead:
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview(this, event)" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
Then you can access them like that:
function GetAdvisorReview(sender, e){
alert(sender.id);
alert(e.target.id);
}
My HTML page contains:
<a id="show" href="monlien1" onclick="show()"> Facebook</a>
<a id="show" href="monlien2" onclick="show()"> Twitter</a>
<a id="show" href="monlien3" onclick="show()"> Google</a>
I want to show the href attribute for each click. For example if I click on "Facebook", it will show monlien1, on "Twitter" monlien2, etc.
I tried this but it shows only the value of the first link, monlien1, even if I click on "Twitter" or "Google".
function show(){
var lien=$('#show').attr('href');
alert(''+lien+'');
}
How can I do this?
Start using classes (you shouldn't have the same ID multiple times, it will cause issues) also, pass in this as an argument:
<a class="show" href="monlien1" onclick="show(this)"> Facebook</a>
<a class="show" href="monlien2" onclick="show(this)"> Twitter</a>
<a class="show" href="monlien3" onclick="show(this)"> Google</a>
function show(obj) {
var lien = obj.href;
alert(''+lien+'');
}
Edit: Thanks #FelixKling -- the equivalent to $('#show').attr('href') is obj.getAttribute('href'). obj.href will return a full URL not the actual value of the href attribute.
You cannot have multiple elements with same ID. $('#show') will always select the first elements with that ID.
Give the elements a class and use jQuery to bind the event handler:
<a class="show" href="monlien1"> Facebook</a>
<a class="show" href="monlien2"> Twitter</a>
<a class="show" href="monlien3"> Google</a>
and
$('.show').click(function() {
alert($(this).attr('href'));
});
Learn about jQuery and event handling: http://learn.jquery.com/events/.