add onclick event of specific element (without id or class) - javascript

I want to get attribute value (data-resource-id) in tag. But this tag don't have id or class. I just need inside show alert when clicked. This is my code:
<table>
<tbody>
<div class="x">
<tr data-resource-id="first"> //will show alert "first" when clicked
<tr data-resource-input="second">//show nothing when clicked
</div>
<div class="y">
<tr data-resource-id="first"> //show nothing when clicked
</div>
this is my javascript code:
$('.x').on('click','????',function(){
var resourceid = $(this).attr('data-resource-id');
alert(resourceid);
})
I don't know what code to write in '????'. What code should i write?

This updated version of your code might work for you
$(document).on('click', '.x [data-resource-id]', function() {
const resourceId = $(this).attr('data-resource-id');
alert(resourceId);
})
Note, your original code had a variable named resource-id — but hyphens are illegal in javascript identifiers. So you must correct that variable name to resourceId instead
'????' became '.x [data-resource-id]' so that clicks to anything matching that selector are handled
var became const for good measure
Corrected tab consistency

Get all the tags that have your attribute and value:
'tr[data-resource-id="first"]'
Get just the first tag that matches your attribute and value:
'tr[data-resource-id="first"]:first'

You can use data attribute as selector. As below
$('.x').on('click','tr[data-resource-id="first"]:first',function(){
var resourceid = $(this).attr('data-resource-id');
alert(resourceid);
})

Related

select a string after a substring in an element's class name

I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', id);

How to get last element in the .find() object by jquery

I have DOM like this:
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
...
When I click on the Add button, I would like to get the value of the data attribute from the last of it own parent class.
I am using this method to get the last element,but it doesn't work.
$('.add-tr').click( function() {
var last = $(this).parent().find('.child:last').attr('data');
alert(last);
})
Any idea why? Or any other suggestion to get the last element in the table?
UPDATE
Yes, I found the problem, turn out is I forgot the 'tr'. Thanks for your guys answer. All your guys giving the correct answer, I wish I can accept all your answers. Thanks
Try this
var last = $(this).parent().find('.child').find('tr').last().attr('data');
In your example you get last table, but you need get last tr
Example
'.child:last' selector will select the last element having child class. As child class is applied to <table>, this selector will select table element, while you want to select last <tr>.
As there is no data attribute on <table>, .attr('data') on it will return undefined.
To get the value of data attribute on last <tr> use the selector tr:last.
var value = $(this) // Button that is clicked
.parent() // Direct parent element i.e. div.parent
.find('.child tr:last') // Get the last <tr> inside .child
.attr('data'); // Get value of data attribute
As the .child element is next to the button, next() can be used to get the table.child element.
var value = $(this) // Button that is clicked
.next('.child') // Next element i.e. table
.find('tr:last') // Get last <tr>
.attr('data'); // Get value of "data" attribute
I'll recommend to use data-* attribute to store data in custom attribute.
<tr data-num="0">Foo</tr>
<tr data-num="1">Bar</tr>
And to get the value of custom data attribute use data()
.data('num')
If you just want to get the index of the last tr, there is no need to store that on element. You can get the index by using the index().
.index()
This will return index of an element. Note that this is zero-based index which is exactly how you want.
$(".parent").click(function(){
$(this + " tr:last-child").attr("data");
});
should do.
Your code was almost correct, you missed tr:last , i.e.:
var last = $(this).parent().find('.child tr:last').attr('data');
DEMO
http://jsfiddle.net/tuga/vr1knxqq/3/
$('.add-tr').click( function(event) {
var last = $(event.target).next().find("tr").last().attr("data");
alert(last);
})
fiddle-example
You can get an array of the tr elements by using find('.child tr')
and to get the last element in that array you can use last().
Putting it all together you have this:
$('.add-tr').click( function() {
var lastTr = $(this).parent().find('.child tr').last(),
lastData = $(lastTr).attr('data');
alert(lastData);
});
I have setup a codepen here http://codepen.io/anon/pen/aOzmKg to show this working.

How do I use jQuery to click and option and have it populate a field

I'm using the following code to have jQuery handle the click of an option and put that value in a field.
The code works except for the part I have in the tag.
I can't figure out why the part within the bold tag isn't doing anything when clicked, while the text after it does.
Here's the HTML:
<div id="result" style="display: block;">
<div class="show" align="left">
<b>This text doesn't work when clicked</b>
This text works when clicked
<span class="name" align="left">113096G</span>
</div>
And Here's the jQuery:
// When clicking an option, the value populates the #projectsearchid field
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
$('#projectsearchid').val($name);
});
Possibly there's a simpler way to accomplish this?
var $name = $clicked.parent().find('.name').html();
find(): Description: Get the descendants of each element in the current set of
matched elements, filtered by a selector, jQuery object, or element.
Thus the method will look inside <b></b> for an element with the class name of name.. which of course it won't find anything, because in this case the element with the class name of name is a sibling and not a child. You'll notice that it will find something if you add .parent()
DEMO
$('#result').on('click',function(e){
var $clicked = $(e.target);
var $name = $clicked.parent().find('.name').html();
//$('#projectsearchid').val($name);
alert($name);
});
firstly, jquery.live is deprecated you should use jquery.on. the reason your code doesn't work is because when you click on the b element, the e.target is associated with and not div#result. when you call:
$clicked.find('.name').html();
it can't find the span.name because the element has no children with that class. the same happens when you click on as well. instead do
$clicked.parent('#result').find('.name').html();
that should get you what you need.

What is the line mean? "this.parentNode.firstChild.nodeName" in jQuery Hilghlight plugin

What is the use of the line
this.parentNode.firstChild.nodeName
in following code from jQuery Highlight plugin.
http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
jQuery.fn.removeHighlight = function () {
return this.find("span.highlight ").each(function () {
this.parentNode.firstChild.nodeName;
with(this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
this.parentNode.firstChild.nodeName is not assigning its value to any variable. Basically it's a property not a function, so it won't make any effect. Looks pointless. It should find out parentNode of current node, then firstChild node of that parentNode and then get its nodeName. But in this case it's not getting used anywhere in the code snippet you provided
Consider the following eg:
<span class= "highlight">...</span>
<span class= "highlight">...</span>
<span class= "highlight">...</span>
<span class= "highlight">...</span>
....
Now there are multiple spans with the same class name.
If you try to highlight ONE of these spans the jquery is fired.
Now which span to highlight is based on this.parentNode.firstChild.nodeName;
this refers to the span which has a request for highlight and the remaining is just internals inside the span.
this.parentNode.firstChild.nodeName
This gets the tag's name (if it's an element, see RobG's comment) of the first sibling in reference to this.
Because it is not being assigned, it is weird. If it's being called for a side effect (perhaps to fix a browser bug), it's not clear (it should be commented).
That plugin's code is kind of weird.

Where is this JQuery wrong?

I want to add the click event to all elements where the `id="violacao":
$(document).ready(function () {
jQuery('#violacao').click(function() {
alert('teste');
});
});
But just the first link responds to the click. This is the HTML generated:
<tr>
<td>40954589</td>
<td>Perda de Comunicação</td>
</tr>
<tr>
<td>88692020503</td>
<td>Perda de Comunicação</td>
</tr>
When I try this way:
jQuery("a").click(function() {
alert('teste');
});
It works fine, except that all links are affected. What is wrong?
IDs in HTML are meant to be unique (one per document). Change the ID to a class (and use . instead of #) and it should work.
While what Steve Mason says it's true, the actual problem is not that.
If you change ID to a class a problem persists: all links will get affected.
Instead, if you aim to affect one single <A>, you should do one of the following:
a) Assign unique IDs to each <A>, then do something like you were doing first; or
b) Assign classes and use the :first selector:
jQuery("a.violacao:first").click( function (){
alert('teste');
} );
That will apply to the first matching anchor with class violacao. Alternatively, if you want to affect a specific anchor, you could use :eq(index).
For a comprehensive list of selector, visit http://docs.jquery.com/Selectors.

Categories