Javascript to get the id of the hyperlink clicked - javascript

I would like to know how i can set the current hyperlink id to a hidden field on clicking the corresponding links. The html control code is as follows:
<a href="#TB_inline?height=155&width=300&inlineId=hiddenModalContent" class="thickbox" id="ExpressionsLink"
title="Create expression column" onclick="keepID()">Add Expressions Model</a>
<a href="#TB_inline?height=155&width=300&inlineId=hiddenModalContent" class="thickbox" id="AggregateMethodLink"
title="Create aggregate column">Add Aggregate Methods</a><input id="HiddenIdHolder"
type="hidden" />
I need the id of the link clicked on the hidden field 'HiddenIdHolder'.
Javascript
function keepID() {
var hiddenInput = document.getElementById("HiddenIdHolder");
hiddeninput.value= ? // What can i do here to get the id?
}

this refers to the element itself. Example on jsFiddle
onclick="keepID(this)"
Then
function keepID(element)
{
var hiddenInput = document.getElementById("HiddenIdHolder");
hiddeninput.value = element.getAttribute("id");
}

Use jQuery:
$('a').click(function() {
$('#HiddenIdHolder').val($(this).attr('id'))
})

You should modify your HTML to provide argument for KeepID function:
ooxx
note that you should provide a this argument when invoke KeepID function, then in KeepID function, you can access this element from argument:
function KeepID(src) {
document.getElementById("HiddenIdHolder").value = src.id;
}

Related

$(this).attr('id') gives blank values in jQuery

I have a link as follows:
<a href="#" id="<?php $res['id'];?>" class='bid_accept'>Accept</a>
I need to pass the value of id to another page using Framework7 as follows:
$$('.bid_accept').on('click', function (e) {
e.preventDefault();
var value = $(this).attr('id');
var jsonstring = JSON.stringify(value);
myApp.confirm('Are you sure?', 'Custom Title',
function (jsonstring) {
myApp.alert('Your name is "' + value + '". You clicked Ok button');
},
function () {
myApp.alert('You clicked Cancel button');
}
);
});
I receive alerts as:
Your name is "". You clicked Ok button
I also tried:
var value = this.id;
Why am I not getting the id value?
If you use JSON.stringfy(value) it means you are setting that ID out of a JSON value, i do not know if i am write but the ID attribute takes a 1 word name and JSON.stringfy() produces multiple words separated by spaces. Let alone i think IDs have a specific number of characters so you might be intializing a very long name.
Not really sure what you want to achieve but HTML allows you to add attributes of your own and read them in JQuery like:
<a href="#" myAttr="<?php $res['id'];?>" class='bid_accept'>Accept</a>
such that when you click your code will be like:
$$('.bid_accept').on('click', function (e) {
var value = $(this).attr('myAttr');
....
}
This line has error
<a href="#" id="<?php $res['id'];?>" class='bid_accept'>Accept</a>
change it to
<a href="#" id="<?php echo $res['id'];?>" class='bid_accept'>Accept</a>
And in jquery part instead of $ you have to use $$.
var value = $$(this).attr('id'); // check $$ sign

$(this).attr("data-id") returning undefined

I'm building a webshop and on every item there is a button to add that item to the shopping cart.
<?php
$i = 0;
$path = "../images/women/winter/winter1";
$lang = "description_".get_param();
if(!$result = $db->query("SELECT * FROM cloths;")){
die("There was an error running the query [".$db->error."]");
}
while($winter = $result->fetch_assoc()){
echo "<div class = \"boxsale $winter[image]\">
<img src = \"$path.jpg\"/>
<div class = \"test\"> $winter[$lang] </div>
<select>
<option>S</option>
<option>M</option>
<option>L</option>
<option>XL</option>
<option>XXL</option>
</select>
<button class = \"addToCart\" onclick = \"executeJS()\"> <i class = \"fa fa-shopping-cart\" data-id = \"$i\" aria-hidden=\"true\"></i></button>
</div>";
$i++;
}?>
</div>
when you click on the button the executeJS() in the last few lines gets called from a seperate file.
addToCart.js
function executeJS(){
var id = $(this).attr("data-id");
$.ajax( {
type: "GET",
url: "ajax.php?id=" + id + "&action=add"
})
.done(function(){
alert("Product has been added.");
});
}
i wanted to grab the data-id from the button that has been clicked, with
$(this).attr("data-id"); but all i get is a header that has undefined as data-id.
id=undefined&action=add
can anyone please point me in the right direction?
thanks
The problem is because $(this) is not correctly being applied to the element you're trying to access. When using a string based onclick handler (onclick="test()"), this refers to the window, and NOT the element you're trying to access.
function test() {
console.log(this.id);
}
Link
If you want to use the string based onclick notation, pass your element in explicitly, and do $(element).
<button class = \"addToCart\" onclick = \"executeJS(this)\" data-id = \"$i\" />
Javascript:
function executeJS(element){
var id = $(element).data('id');
...
Personally, skip the attr-id all together, and simply pass your id directly:
<button class = \"addToCart\" onclick = \"executeJS($id)\" />
It looks like this may be pointing to the window instead of the button.
You can fix this by manually looking for the button:
var id = $(".addToCart").attr("data-id");
This will only really work if you only have one button. What you should do is use jquery to attach the event to the button.
In your javascript:
$(".addToCart").click(function(e){
var id = $(e.target).attr("data-id");
$.ajax({
type: "GET",
url: "ajax.php?id=" + id + "&action=add"
})
.done(function(){
alert("Product has been added.");
});
})
The e.target refers to the button that is being clicked.
Use regular function (function(){}) instead of arrow function:
$(document).on("click",".deleteBtn",function(){
//Your Code
});
Since you're using jQuery, this is how you should be doing it. First, remove the inline event handler in your PHP (e.g. onclick = \"executeJS()\")
The other issue is that your buttons don't have a data attribute but their <i> children do.
Next, create your jQuery event handler, binding to the button. By doing this you can use $(this).find('i') to get the fontawesone <i> element and its data attribute, .attr("data-id"):
$('button.addToCart').click(function() {
var id = $(this).find('i').attr("data-id");
$.ajax({
type: "GET",
url: "ajax.php?id=" + id + "&action=add"
})
.done(function() {
alert("Product has been added.");
});
})
jsFiddle example

getAttribute value with AngularJS

I have the following controller... I'm trying to get the name and rating attibute from an HTML input, but I get the error TypeError: angular.element(...).getAttribute is not a function
app.controller('courseReview', function ($scope, $http) {
$scope.rateThis = function rateThis(el){
var elName = angular.element(el).getAttribute('name');
var rating = angular.element(el).getAttribute('rating');
document.getElementById(elName+'Rating').value = rating;
}
});
HTML
<div ng-controller="courseReview">
<!-- radio input -->
<input class="star-5" id="wstar-5" rating="5" type="radio" name="welcome" ng-click="rateThis(this)"/>
</div>
Is there another way to do this?
As per the documentation "https://docs.angularjs.org/api/ng/function/angular.element", to get attribute of an element you need to use
.attr('name');
in place of
.getAttribute('name');
Important
You are passing this in your html, here this will not pass the DOM element to the function, rather it will refer to the scope. To pass the current element pass $event
HTML Change
ng-click="rateThis(this)" to ng-click="rateThis($event)"
JS Change
$scope.rateThis = function rateThis($event){
var elName = angular.element($event.target).attr('name');
var rating = angular.element($event.target).attr('rating');
document.getElementById(elName+'Rating').value = rating;
}
For reference - http://plnkr.co/edit/ZQlEG33VvE72dOvqwnpy?p=preview

How to display value of a ViewBag in my view with a JS function?

I want to display the data from a ViewBag in my View with Javascript. Here is my code.
View
<span id='test'></span>
Javascript
function myFunction()
{
$('#test').text('#ViewBag.Test');
}
When myFunction() is called I get the text #ViewBag.Test but not his value. How can I fix this ?
You need to place your JavaScript which takes the #ViewBag.Test value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.
If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:
// in the view:
var testText = '#ViewBag.Test';
// in external js
function myFunction() {
$('#test').text(window.testText);
}
Alternatively, you can use a data-* attribute:
<span id='test' data-text="#ViewBag.Test"></span>
// in external js
function myFunction() {
$('#test').text(function() {
return $(this).data('text');
});
}
What you should be ideally doing is passing the data to the view with a view model. Have a property to store that value you want to pass. For example. Let's think about a page to show the customer details and you want to get the last name in your javascript variable.
Your GET action method
public ActionResult View(int id)
{
var vm=new CustomerViewModel();
vm.LastName="Scott"; // You may read this from any where(DAL/Session etc)
return View(vm);
}
and in your view which is strongly typed to your view model.
#model CustomerViewModel
<div>
Some Html content goes here
</div>
<script type="text/javascript">
var lastName="#Model.LastName";
//Now you can use lastName variable
</script>
EDIT : (As per the question edit) To show the content on some event (ex : some button click), Store the value somewhere initially and then read it as needed and set it wherever you want.
#model CustomerViewModel
<div>
<span id="content"></span>
#Html.HiddenFor(s=>s.LastName)
<input type="button" id="btnShow" value="Show content" />
</div>
<script type="text/javascript">
$(function(){
$("btnShow").click(function(e){
$("#content").html($("#LastName").val());
});
});
</script>
Firstly make sure your ViewBag.Test does got a value, then use a div tag instead of a span and add the following code:
<script type="text/javascript">
$(document).ready(function () {
StartRead();
});
function StartRead() {
document.getElementById("test").innerHTML = '#ViewBag.Test';
}
</script>

How can I get the data-id attribute?

I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.
$("#list li").on('click', function() {
// ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
</a>
</li>
</ul>
To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use
$(this).attr("data-id") // will return the string "123"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the number 123
and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
OR
// If you updated the value, you will need to use below code to fetch new value
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).attr('data-fruit','7');
Read this documentation
Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will not be reflected in the data() jQuery function. You have to adjust it via data() function as well.
<a data-id="123">link</a>
JavaScript:
$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321
If you are not concerned about old Internet Explorer browsers, you can also use HTML5 dataset API.
HTML
<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>
JavaScript
var myDiv = document.querySelector('#my-div');
myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"
Demo: http://html5demos.com/dataset
Full browser support list: http://caniuse.com/#feat=dataset
You can also use:
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
This piece of code will return the value of the data attributes. For example: data-id, data-time, data-name, etc.
I have shown it for the id:
Click
JavaScript: Get the value of the data-id -> a1
$(this).data("id");
JQuery: This will change the data-id -> a2
$(this).data("id", "a2");
JQuery: Get the value of the data-id -> a2
$(this).data("id");
HTML
<span id="spanTest" data-value="50">test</span>
JavaScript
$(this).data().value;
or
$("span#spanTest").data().value;
ANS: 50
Accessing the data attribute with its own id is a bit easy for me.
$("#Id").data("attribute");
function myFunction(){
alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
var id = $(this).dataset.id
works for me!
I use $.data:
//Set value 7 to data-id
$.data(this, 'id', 7);
//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
Using jQuery:
$(".myClass").load(function() {
var myId = $(this).data("id");
$('.myClass').attr('id', myId);
});
Try
this.dataset.id
$("#list li").on('click', function() {
alert( this.dataset.id );
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />
</a>
</li>
</ul>
for pure js
let btn = document.querySelector('.your-btn-class');
btn.addEventListener('click',function(){
console.log(this.getAttribute('data-id'));
})
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.
$('#select').on('change', function(){
let element = $("#visiabletoID");
element.val($(this).find(':selected').data('record'));
});
For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See .tooltip('dispose').
HTML 5 introduced dataset: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset, the browser compa
But for older browser you can use getAttribute method to get the data-* attributes.
const getDataAttr = (id) => {
if(currentNode.dataset) return currentNode.dataset[id];
return currentNode.getAttribute("data-"+id);
}
The reason to use dataset is constant lookup time, get attribute would not be a constant time lookup, it'll go through all the attributes of the html element and then return the data once it'll find the exact attribute match.
The reason to provide this answer is that nobody mentioned about the browser compatibility and lookup time with the given solution, although both of these solutions are already given by people.
I have a span. I want to take the value of attribute data-txt-lang, which is used defined.
$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});

Categories