Retrieve href attribute - javascript

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/.

Related

Access the attributes of the caller element in the options section of the jQuery plugin

I have some links that according to what they will show when clicked they have different width and height data (this links are generated in server side) like:
<a class="inline" href="#inline-content-1" data-width="80%" data-height="80%">content 1</a>
<a class="inline" href="#inline-content-2" data-width="50%" data-height="80%">content 2</a>
Now I want to use something like:
$('.inline').colorbox({inline:true, width:$(this).data('width'), height:$(this).data('height')});
but $(this).data('width') does not seem to be valid in the options section
Colorbox can be passed a function to be evaluated in place of a static
value for any of its properties.
$('.inline').colorbox({
inline: true,
width: function(){ return $(this).data('width'); },
height: function(){ return $(this).data('height'); }
});
You can do something like this:
$('.inline').each(function(){
$(this).colorbox({inline:true, width:$(this).data('width'), height:$(this).data('height')});
});
The best solution would be using data-cbox- prefix for data attributes:
<a class="inline" href="#inline-content-1" data-cbox-width="80%" data-cbox-height="80%">content 1</a>
<a class="inline" href="#inline-content-2" data-cbox-width="50%" data-cbox-height="80%">content 2</a>
All attributes that start with data-cbox- will be automagically added to options.
Demo
$('.inline').colorbox({inline: true});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js"></script>
<a class="inline" href="#inline-content-1" data-cbox-width="80%" data-cbox-height="80%">content 1</a>
<a class="inline" href="#inline-content-2" data-cbox-width="50%" data-cbox-height="80%">content 2</a>

jQuery: Disable onclick event using off() not working

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");

Need to get the "id" attribute of <a> tag using JS

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);
}

Toggle a class on an element click in Angular.js

In angular.js how can I toggle a css class active on and off on click of the element? I know I can use ng-class and ng-click but how do I reference itself? For example, let's say I have three buttons:
<a class="btn" ng-click="" ng-class"">First</a>
<a class="btn" ng-click="" ng-class"">Second</a>
<a class="btn" ng-click="" ng-class"">Third</a>
<a ng-click="firstActive = !firstActive" ng-class"{'btn':true, 'active':firstActive}">First</a>
<a ng-click="secondActive = !firstActive" ng-class"{'btn':true, 'active':secondActive}">Second</a>
<a ng-click="thirdActive = !firstActive" ng-class"{'btn':true, 'active':thirdActive}">Third</a>
You'll have to have separate scope variables in your controller for firstActive, secondActive, and thirdActive, all set to false by default.

Getting data-* attribute for onclick event for an html element

<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>

Categories

Resources