I need to get elements by data attribute and part of id in jQuery.
I have following code.
<div class="bridgeSelectedDiv" id="bridgeDiv_13234" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
<div class="bridgeSelectedDiv" id="bridgeDiv_13432" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
<div class="bridgeSelectedDiv" id="bridgeDiv_45646" onclick="SelectBridgeLine(this);" data-bridgeuid="b2a42066-00e2-4b6e-bdef-397468573b75"></div>
function SelectBridgeLine(element) {
var bridgeuid = $(element).attr("data-bridgeuid");
var partofSelectedBridgeLine = $('div[id^="bridgeDiv_"]').data("bridgeuid");
console.log(partofSelectedBridgeLine);
}
But it returns only 1 element not all of them.
Any clue? Thank you!
From the docs of .data()
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
So whats happening here is it gets the data value for first element only. You need to iterate over them using .each() to get for all elements in matched selector:
$('div[id^="bridgeDiv_"]').each(function(){
console.log($(this).data('bridgeuid'))
});
Demo
It returns only 1 element because you are doing onclick="SelectBridgeLine(this);", and this will always point to current element on which the click handler exists, instead do:
$('.bridgeSelectedDiv').click(function(){
console.log($(this).data('bridgeuid')); //you can use .data()
});
or
$('div[id^="bridgeDiv_"]').click(function() {
console.log($(this).data('bridgeuid'));
});
Try
$('div[id^="bridgeDiv_"]').each(function(){
console.log($(this).data("bridgeuid")); });
Related
So I know that using "a:first" will get the first link of a page. Lets assume we have the following:
<div class="masterclass">
Link 1
Link 2
</div>
<div class="masterclass">
Link 1
Link 2
</div>
Naturally I can use the following code to get the first "a" of the class "masterclass"
$('.masterclass a:first').click(function() {
alert('yayfirstlink');
});
However I do not understand how to get the first link of every "masterclass"
You need to use find() here because your selector will find all the anchor elements with in .masterclass then filter only the very first one. But when you use .find(), it will find all the .masterclass elements first then will find the first anchor element in each of them.
$('.masterclass').find('a:first').click(function() {
alert('yayfirstlink');
});
or if you are sure that the target element will be the first child of its parent then you can use :first-child
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
Try this,
var oFirstAnchor = $(".masterclass a:first-child");
$(".masterclass a:first-child") is what you are looking for.
so:
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
This is how u loop through each of the masterclass and get the first link of it.
i don't know what you want to do with it though so i can only provide this
$(document).ready(function(){
var fields = $('.masterclass a:first-child');
$.each(fields, function(index, val){
alert(index);
});
});
this alerts the current links array index
http://jsfiddle.net/kBd82/6/
I would recommend using the first of type selector for this.
$('.masterclass a:first-of-type')
This way it will always select the first anchor tag in each masterclass div even if you put other things in the div later.
http://api.jquery.com/first-of-type-selector/
I dont know Javascript at all, so sorry for asking a question like this...
This is what I have:
$(document).ready(function(){$("#more0").click(function(){$("#update0").slideToggle("normal");});});
$(document).ready(function(){$("#more1").click(function(){$("#update1").slideToggle("normal");});});
$(document).ready(function(){$("#more2").click(function(){$("#update2").slideToggle("normal");});});
$(document).ready(function(){$("#more3").click(function(){$("#update3").slideToggle("normal");});});
$(document).ready(function(){$("#more4").click(function(){$("#update4").slideToggle("normal");});});
$(document).ready(function(){$("#more5").click(function(){$("#update5").slideToggle("normal");});});
$(document).ready(function(){$("#more6").click(function(){$("#update6").slideToggle("normal");});});
$(document).ready(function(){$("#more7").click(function(){$("#update7").slideToggle("normal");});});
$(document).ready(function(){$("#more8").click(function(){$("#update8").slideToggle("normal");});});
$(document).ready(function(){$("#more9").click(function(){$("#update9").slideToggle("normal");});});
$(document).ready(function(){$("#more10").click(function(){$("#update10").slideToggle("normal");});});
And So On.. Until #more30 and #update30...
So... Right now, my pages has 30 lines :)
Is there a way to do it less complicated?
Thanks!
Use attribute selector ^= . The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value.
$(document).ready(function(){
$("[id^='more']").click(function(){
$("#update" + $(this).attr('id').slice(4)).slideToggle("normal");
});
});
Try to use attribute starts with selector to select all the elements having id starts with more , then extract the numerical value from it using the regular expression and concatenate it with update to form the required element's id and proceed,
$(document).ready(function(){
$("[id^='more']").click(function(){
var index = $(this).attr('id').match(/\d+/)[0];
$("#update" + index).slideToggle("normal");
});
});
use attribute start with selector
$(document).ready(function(){
$("[id^='more']").click(function(){
$("[id^='update']").slideToggle("normal");
});
});
//select all elements that contain 'more' in their id attribute.
$('[id^=more]').click(function(){
//get the actual full id of the clicked element.
var thisId = $(this).attr("id");
//get the last 2 characters (the number) from the clicked elem id
var elemNo= thisId.substr(thisId.length-2);
//check if last two chars are actually a number
if(parseInt(elemNo))
{
var updateId = "#update"+elemNo;//combine the "#update" id name with number e.g.5
}
else
{
//if not, then take only the last char
elemNo= thisId.substr(thisId.length-1);
var updateId = "#update"+elemNo;
}
//now use the generate id for the slide element and apply toggle.
$(updateId).slideToggle("normal");
});
Well first of all, you could replace the multiple ready event handler registrations with just one, e.g
$(document).ready(
$("#more0").click(function(){$("#update0").slideToggle("normal");});
//...
);
Then, since your buttons/links has pretty much the same functionality, I would recommend merging these into a single click event handler registration as such:
$(document).ready(
$(".generic-js-hook-class").click(function(){
var toggleContainer = $(this).data('toggleContainer');
$(toggleContainer).slideToggle("normal");
});
);
The above solution uses HTML Data Attributes to store information on which element to toggle and requires you to change the corresponding HTML like so:
<div class=".generic-js-hook-class" data-toggle-container="#relatedContainer">Click me</div>
<div id="relatedContainer>Toggle me</div>
I would recommend you to use Custom Data Attributes (data-*). Here You can store which element to toggle in the data attributes which can be fetched and used latter.
JavaScript, In event-handler you can use .data() to fetch those values.
$(document).ready(function () {
$(".more").click(function () {
$($(this).data('slide')).slideToggle("normal");
});
});
HTML
<div class="more" data-slide="#update1">more1</div>
<div class="more" data-slide="#update2">more2</div>
<div id="update1">update1</div>
<div id="update2">update2</div>
DEMO
I have a jquery selection like this:
elements= $($('#mytab').find('form').attr('elements')).not('button');
// access elements by name
elements['id']=1;
which is not working obviously :(
I need the jquery to return the collection as HtmlCollection e.g
$('#mytab').find('form').attr('elements')
My qeuestion is, is there any function available e.g like toArray() etc to
return the collection as HtmlCollection, instead of jquery array/ object collection ?
My main objective is to access form elements by name not by index e.g
elements['id'], elements['name']
Html Form elements
Lots of confusion around elements. elements is attribute of html form object which is collection of all the elements in the form
Here is a JSfiddle for this.
elements is a property not an attribute, you should use prop method instead:
var elements = $('#mytab').find('form').prop('elements');
or:
var elements = $('#mytab').find('form')[0].elements;
Well, if you want to filter input elements, you can use get method, there is no need to use elements property:
var elements = $('#mytab form input').get();
http://api.jquery.com/get/
Yup, there is:
$.makeArray($('div'));
This returns a array of all div elements on the page. Obviously, you can use any selector you want.
To get a array of elements, by their name, just use native JS:
document.getElementsByName('myFormElementName');
I want to reload a particular div, which has an id corresponding to a table element's id... (the div has only one table child).
the alert says tID is undefined.
javascript:
function (msg) {
var tID = $("table", msg).attr('id');
alert(tID);
$("#reloadme_"+tID).html(msg);
}
html:
<div id="reloadme_2036">
<table id="2036" class="customCSSclass">
...table contents...
</table>
</div>
Where have I gone wrong?
find looks for descendants of the current set of elements inside the jQuery object, you should use .filter which filters the elements in the jQuery object itself:
$('<table id="001">[...]</table>')
//the jQuery object will contain a reference to the parsed <table> element,
//so you have to .filter() the jQuery object itself to extract it
Of course, if it is the only element inside the jQuery object, there is no need for filtering. =]
Also, you'd use .find for e.g. looking for tr/tds (or any other element(s)) that are descendant of the table element referenced inside of your jQuery object.
Maybe this is what you're looking for?
function reload(msg) {
var tID = msg.match(/id="(\d{1,4})"/i)[1]; //find 1 to 4 digits in the id attribute
alert(tID); //alerts 2036
$("#reloadme_"+tID).html(msg); //adds the content to the div
}
reload('<table id="2036" class="customCSSclass"> ...table contents... </table>');
If so, what you are likely looking for is javascript's .match() method which will find the id number within a string.
Check out the JSFiddle.
You have to try like this
var msg='<table id="2036" class="customCSSclass"></table>';
alert($(msg).attr("id"));
Perhaps I'm using $.data incorrectly.
Assigning the data:
var course_li = sprintf('<li class="draggable course">%s</li>', course["fields"]["name"]);
$(course_li).data('pk', course['pk']);
alert(course['pk']); // shows a correct value
alert($(course_li).data('pk')); // shows null. curious...
course_li is later appended to the DOM.
Moving the li to a different ul:
function moveToTerm(item, term) {
item.fadeOut(function() {
item.appendTo(term).fadeIn();
});
}
Trying to access the data later:
$.each($(term).children(".course"), function(index, course) {
var pk = $(course).data('pk');
// pk is undefined
courses.push(pk);
});
What am I doing wrong? I have confirmed that the course li on which I am setting the data is the same as the one on which I am looking for it. (Unless I'm messing that up by calling appendTo() on it?)
When you store the data:
$(course_li).data('pk', course['pk']);
you're creating an element but not saving it, so it's lost. Your alert test test the wrong value; it should be:
$(course_li).data('pk', course['pk']);
alert($(course_li).data('pk'));
which is null. Consider:
$(course_li);
$(course_li);
This creates two different elements with source equal to course_li, which are then promptly lost. What you need to do is create the element first, then work with that single element (i.e. don't call $(course_li) more than once). For example,
var course_li = $(sprintf('<li class="draggable course">%s</li>',
course["fields"]["name"]));
course_li.data('pk', course['pk']);
parent.append(course_li);
Note that course_li now holds an element, rather than a string.
try checking to see if the element being created by this call:
$(course_li)
is a single 'li' element, or a div. From the doco:
When the HTML is more complex than a single tag without attributes, as it is in the above example... snip ...Specifically, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in
So it's probably creating a div that you are assigning the data to, so when you select the 'li' itself, you are getting a child of the actual element that you set the data on.