Using a variable in jquery selector - javascript

I want to change the src of an image file. Tried the below using with the variable, but it actually doesnt change it. Where did I made a mistake on using variable ?
jquery
var p2begen = "416";
$("[id=i'" + p2begen + "']").attr("src", "check.png");
html
<img src="nocheck.png" id="i416" \>

To reference an id in jquery you need to add the #. See here in the jquery docs. It is important to note that ids must be unique, but you can use a class on as many elements as you like.
var p2begen = "416";
$("#i" + p2begen).attr("src", "check.png");
If you wish to use classes instead your code should look like this:
<img src="nocheck.png" class="i416" \>
var p2begen = "416";
$(".i" + p2begen).attr("src", "check.png");

add the # at the start.
var p2begen = "416";
$("#i" + p2begen).attr("src", "check.png");
if you want to stick with the attribute selector, use:-
var p2begen = "416";
$("[id='#i" + p2begen + "']").attr("src", "check.png");
by adding the # and moving the ' back 2 places.

The simplest way for doing that is to use selector for ids, and your selector will looks like this:
var p2begen = "416";
$('#i' + p2begen).attr("src", "check.png");

Related

Use a variable for a datatable

I'm trying to doing something in jquery.
This is a part of my jquery:
console.log(tableid);
var table = $('"#'+tableid+'"').DataTable();
tableid = "Data-user1"
table is null....
but when i put table = $("#Data-user1").DataTable() it works. Whats wrong?
Because how you're initializing the datatable is incorrect. You don't need to explicitly quote quotes in the selector; you just need to concatenate the strings like this:
var table = $("#" + tableid).DataTable();
That should work.
You mean this?
console.log(tableid);
var table = $('#' + tableid).DataTable();
ID Selector correct format -> $(“#id”)
Description: Selects a single element with the given id attribute.
var table = $('#' + tableid).DataTable();
Take a look at documentation: https://api.jquery.com/id-selector/

Get the url of the background-image from an div elment with javascript

I have an element in a website that looks like this:
<div id="item" style="background-image: url('url to the image')"></div>
Now I need a javascript which extracts only the url of this background-image and replaces it with an url stored in a var.
How is this possible in a "neat" way :) ?
You could select the div by its id and use setAttribute to set the style attribute to a string containing the new url stored in yourVar like this:
var item = document.getElementById('item');
var newStyle = 'background-image: url(' + yourVar + ');';
item.setAttribute('style', newStyle);
$('#item').css('background-image', 'url(' + var + ')');

Get attr(id) with a known href variable

I want to get the id name thanks to a href value that is set in a variable.
To do this, I want to:
get the attr('href') of a clicked element (that works).
put it in a variable (OK).
search this href in a every class called ".link" (not in #prev-ajax, #next-ajax id) (problem)
Get the parent id.
I tried this :
$('#prev-ajax,#next-ajax').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$(".link[href*= href ]:not('#prev-ajax,#next-ajax')");
var ajax = $(this).parents('.element').attr('id');
alert(ajax);
});
As you're using a JavaScript variable, you need to escape the quotes. Also, don't wrap items in the :not selector in quotes.
Try this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
Edit: Looking at your fiddle, you're also not doing anything with that selector. See this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = $(this).parents('.element').attr('id');
It should be:
var link = $(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = link.parents('.element').attr('id');
Demo: http://fiddle.jshell.net/UKyT4/1/

How to render a javascript variable in an HTML attribute using jQuery

Using the following code:
<div class="whatever" addthis:title="Hi, your name is [firstName]"></div>
If I have a JS variable like this
var name = John
How would I replace the "[firstName]" with my JS variable in the first code snippet using jQuery?
It's ok if I need to set the attribute using jQuery to begin with like:
$('.whatever').attr( 'addthis:title', 'Hi, your name is [firstName].' );
Simply run replace on your string...:
var name = 'John';
$('.whatever').attr('addthis:title', function(i, attr){
return attr.replace('[firstName]', name);
});
P.S. Are you sure you want an attribute addthis:title, not simply title? That's invalid HTML! If you want to create your own attributes, prefix them with data-:
<div class="whatever" data-addthis-title="Hi, your name is [firstName]"></div>
Did you try it? Your example code contains all the pieces you need.
var name = "John";
var element = $('.whatever');
var newAttrValue = element.attr('addthis:title').replace(/\[firstName\]/, name);
element.attr('addthis:title', newAttrValue);

jQuery/JavaScript: Avoid unique ID's for each row in a table?

I'm not sure if I'm doing this the right way. I have table which I fill with rows that each represent a song in a playlist. Right now, I assign a unique ID per row, and also assign som jQuery.data() to each ID.
html += '\
<tr id="track-' + i + '" class="tracks-row"> \
<td class="track"><a id="play-'+ i +'" class="play"></a><a id="play2-' + i + '">' + song.song_track + '<span class="mix-style">' + song_mix + '</span></a></td> \
<td class="artist">' + song.song_artist + '</td> \
<td class="favourites-holder"><a id="favourite-' + i + '" class="favourites"></a></td> \
' + delete_holder + ' \
</tr> \
';
So as you can see, each row has an ID like track-1, track-2 etc.
Is there another way to populate a playlist like this without assigning unique ID's to each track, or is this how it's supposed to be done? Each track has some properties like this:
$("#track-" + i).data("song_id", song.song_id);
$("#track-" + i).data("song_artist", song.song_artist);
$("#track-" + i).data("song_track", song.song_track);
$("#track-" + i).data("song_mix", song.song_mix);
$("#track-" + i).data("ps_id", song.ps_id);
... and also .click events for each track, which allows the user to play, sort, drag etc... It just feels like I'm doing it wrong :)?
You could store a reference to each generated row in your loop (assuming html only contains the HTML for a single row):
var row = $(html).appendTo("#table");
var data = row.data();
data["song_id"] = song.song_id;
data["song_artist"] = song.song_artist;
data["song_track"] = song.song_track;
data["song_mix"] = song.song_mix;
data["ps_id"] = song.ps_id;
row.click(function(){...});
It is not bad to have an ID for an element. But is definitely faster to make use of a reference if you have one and not use jQuery's selector engine over and over again.
Also if you attach the same click handler to every row, it is probably better to just attach one to the table and delegate it, e.g.
$('#table').delegate('tr', 'click', function(){...});
Unique id's makes sense or use the Metadata plugin to store all the extra data related to each row. http://plugins.jquery.com/project/metadata
It will store the data like:
<li class='someclass' data="{some:'random', json: 'data'}">...</li>
And you can query this like this:
var data = $('li.someclass').metadata();
if ( data.some && data.some == 'data' )
alert('It Worked!');
Whether the tr needs a unique id or simply a generic class is going to depend a lot on what you intend to do with either javascript (for targeting the rows) or css (also for targeting the rows). If you need to specifically target one row for styling or script effects, a unique id can be an effective way of doing it. If not, then it may be extra "mark-up" that is unnecessary.
In any case, if you do use id's, do make sure they are unique :-)
May be something like this with jquery:
var songs = function(songList){
this.songs = songlist;
this.init();
}
$.extend(songs.prototype, {
init: function(){
var self = this;
var table = $('#myTableID');
for(var i = 0; i < this.songs.length; i++){
var song = this.songs[i];
var songData = $('<tr><td class="track">'+song.track+'</td><td class="artist">'+song.artist + '</td></tr>');
table.append(songData);
songData.find('td.track:first')click(function){
self.SongClick(song.track);
});
//add other events here
}
}
},
SongClick : function(track){
//add here you click event
},
otherEvent : function(track){
//add otherEvent code
}
});
Like this you can create your javascript object and attach events to the dom elements directly as you parse them. You will not need any id's.
This approach will create a js object with its constructor
so you can say
var so = new songs(mySongList)
when it initializes it will retrieve a table with an id of myTableID and foreach song in the list, it will attach elements to it, and will attach the events directly to those elements.

Categories

Resources