How can I get the data-id attribute? - javascript

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

Related

Dynamic attribute value element locator in Protractor

When I add a new button with some value it gets dynamically added into DOM. Non-Angular HTML element for this button is:
<li class="ui-state-default droppable ui-sortable-handle" id="element_98" data-value="2519">
25.19 EUR
<button type="button" class="btn btn-default removeParent">
<span class="glyphicon glyphicon-remove" aria-hidden="true">
</span>
</button>
</li>
Once I remove this button I want to check it is not present anymore. Element that I'm searching for is data-value="2519"and this could be anything I set, like for example 2000, 1000, 500, 1050,...
In page object file I have tried to use the following:
this.newValueButtonIsNotPresent = function(item) {
newValueButton = browser.element(by.id("containerQUICK_ADD_POINTS")).all(by.css('[data-value="' + item + '"]'));
return newValueButton.not.isPresent();
};
And in spec file I call this function as follows:
var twentyEurosButtonAttributeValue = '2000';
describe("....
it ("...
expect(predefined.newValueButtonIsNotPresent(twentyEurosButtonAttributeValue)).toBeTruthy();
I know this is not correct, but how I can achieve something like that or is there another way?
Stupid me, I found a simple solution. Instead dynamically locating an element I located the first on the list, which is always the one, which was newly added and then checked if it's text does not match:
Page object file:
this.newValueButtonIsNotPresent = function() {
newValueButton = browser.element(by.id("containerQUICK_ADD_POINTS")).all(by.tagName('li')).first();
return newValueButton.getText();
};
Spec file:
// verify element 20.00 EUR is not present
predefined.newValueButtonIsNotPresent().then(function(value) {
expect(value).not.toEqual(twentyEurosText);
});

$('#notificationClick').click not working

so I'm trying to make this works here is the jquery+php.
When I try to trigle the click in jquery it doesnt even does the "alert()".
PHP(Updated):
$MSG_Notification_sql = mysqli_query($Connection, "SELECT * FROM notifications WHERE user_id='".$bzInfo['id']."'");
while ($MSG_Notification_row = mysqli_fetch_array($MSG_Notification_sql)){
$MSG_Notification_rows[] = $MSG_Notification_row;
}
foreach ($MSG_Notification_rows as $MSG_Notification_row){
$bzWhen = date('d-m-Y H:m:i', strtotime($MSG_Notification_row['when']));
echo '<form method="POST">
<div class="notificationClick notification-messages info">
<div class="user-profile">
<img src="assets/img/profiles/d.jpg" alt="" data-src="assets/img/profiles/d.jpg" data-src-retina="assets/img/profiles/d2x.jpg" width="35" height="35">
</div>
<div class="message-wrapper">
<div class="heading"> '.$MSG_Notification_row['title'].'</div>
<div class="description"> '.$MSG_Notification_row['description'].' </div>
<div class="date pull-left"> '.$bzWhen.'</div>
</div>
<input name="notificationID" value="'.$MSG_Notification_row['id'].'" style="display: none" />
<div class="clearfix"></div>
</div>
</form>';
}
Javascript(Updated):
$(document).ready(function(){
$('.notificationClick').click(function(event){
alert('Ok');
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = $('#notificationClick').serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../../class/notifications/msgs_del.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
window.location = '/?page=messages&sub=inbox&bx=preview&id='+ data.notificationID +'';
});
event.preventDefault();
});
});
Can anybody help me please? I'm trying to complete this but nothing :(
First as the others say, ids need to be singular. So use the class you already have. Now inside, you need to use the current form that you clicked on, not all the forms.
$('.notification-messages').click(function(event){ //<-- change to class
var formData = $(this).closest("form").serialize(); //change to this
...
If you are loading these dynamically, you need to use event delegation
$(document).on("click", '.notification-messages', function(event){
var formData = $(this).closest("form").serialize();
...
You can concatenate the timestamp to your id to make it unique (separated by an _ if you like) and change your selector for the click event to $('[id*="notificationClick_"]')
On the other hand, you might want to use a class instead, that's what it's there for:
$(".notification-messages")
You're using ID, you can only bind click to 1 id not multiple ids.
You should use the class to bind the .click function.

Find an element value with jQuery

In the following HTML markup, how can I get the value of the input field which has the name module_id[], by clicking on the span class .click.
HTML:
<div class="module">
<div class="info">..</div>
<div class="ctrl"><span class="click">Click</span></div>
<input type="hidden" value="module1" name="module_id[]" />
<input type="hidden" value="title" name="module_title[]" />
</div>
I have tried this:
jQuery:
$('.module').on('click','.click',function(){
var target_module = $(this).parent();
var module_id = target_module.find('input[name=module_id\\[\\]]').val();
alert(module_id);
});
Demo:
http://jsfiddle.net/FKdNJ/
$(this).parent(); is giving you the <div class="ctrl"> instead.
You could use $(this).parent().parent(), but a more flexible solution is to use closest() instead;
$(this).closest('.module');
You can see this working here; http://jsfiddle.net/FKdNJ/5/
FWIW, you could also change your approach completely, and use e.delegateTarget to retrieve the .module element directly (http://jsfiddle.net/FKdNJ/7/);
$('.module').on('click','.click',function(e){
var target_module = $(e.delegateTarget);
var module_id = target_module.find('input[name=module_id\\[\\]]').val();
alert(module_id);
});
With:
$('input[name="module_id[]"').val();
jsFiddle example 1
$('.module').on('click', '.click', function () {
console.log($('input[name="module_id[]"').val());
});
If you have more than one set of this block of code, use $(this).closest('.ctrl').next().val():
as in:
$('.module').on('click', '.click', function () {
console.log($(this).closest('.ctrl').next().val());
});
jsFiddle example 2
Try this
$('.module').on('click','.click',function(){
alert($(this).closest('.module').find('[name="module_id[]"]:first').val())
});
http://jsfiddle.net/FKdNJ/3/
Try this. You're probably better off using html 5 data- attributes if possible.
$('span.click').click(function(){
var moduleId = $(this).closest("div.module").find("input[name='module_id[]']").val()
alert(moduleId);
});
I have added a answer in fiddle:
$('.click').on('click',function(){
alert($('input[name=module_id\\[\\]]').val());
})
http://jsfiddle.net/FKdNJ/6/

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

How do I change/replace the <h3> text: "Featured Offers" using javascript to say "Public Offers" instead?
</div> <!-- FEATURED OFFERS -->
<div class="panel">
<div class="head">
<h3>Featured Offers</h3>
</div>
<div class="body">
<table>
<thead>
<tr>
If you can select it, you can manipulate it.
Try this:
$(".head h3").html("your new header");
But as others mentioned, you probably want head div to have an id.
you don't - not like this.
give an id to your tag , lets say it looks like this now :
<h3 id="myHeader"></h3>
then set the value like that :
myHeader.innerText = "public offers";
$("h3").text("context")
Just use method "text()".
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method.
http://api.jquery.com/text/
Give an id to h3 like this:
<h3 id="headertag">Featured Offers</h3>
and in the javascript function do this :
document.getElementById("headertag").innerHTML = "Public Offers";
try this,
$(".head h3").html("New header");
or
$(".head h3").text("New header");
remember class selectors returns all the matching elements.
Something like:
$(".head h3").html("Public offers");
jQuery(document).ready(function(){
jQuery(".head h3").html('Public Offers');
});
You can try:
var headingDiv = document.getElementById("head");
headingDiv.innerHTML = "<H3>Public Offers</H3>";
Hope that help someone:-
Element with a class attribute with the value of "className":
<h3 class="className"></h3>
You will make a refernce of by the class name:
const newTitle = document.querySelector(".className");
Then change the content:
newTitle.textContent = "New Title";

Javascript to get the id of the hyperlink clicked

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

Categories