I have a list of products, each one displayed whithin a div like this :
<div data-productSheetId="n" class="productSheet"></div>
My current selector is the following :
var productSheet = $('[data-productSheetId="' + $(this).data('productSheetId') + '"]');
I'm pretty sure i'm doing it wrong, how could i select it properly ?
You can use the .filter() method:
var productSheet = $("div.productSheet").filter(function() {
return $(this).data("productsheetid") == "n";
});
Update:
Thanks to #mplungjan. The data attributes should be all lowercase. Now, when the attribute has hyphens, the camel-case equivalent can be used to read the data:
//<div data-productsheetid="n" class="productSheet"></div>
//use:
.data('productsheetid')
//<div data-product-sheet-id="n" class="productSheet"></div>
//use either:
.data('product-sheet-id')
//or:
.data('productSheetId')
You likely meant to
have an all lowercase attribute
use the data-attribute to select the productsheet by its id
like this
<div id="xxx" class="productSheet"></div>
<div id="yyy" class="productSheet"></div>
<div id="zzz" class="productSheet"></div>
<button class="btn" type="button" data-productsheetid="xxx">Select XXX</button>
$(function() {
$(".btn").on("click",function() {
// get the id to access from the button's data attribute
var id = $(this).data("productsheetid"); // for readability
var productSheet = $("#"+id);
});
});
Just lowercase your key:
productSheet = $('[data-productSheetId="' + $(this).data('productsheetid') + '"]');
The camelcase key you are using (productSheetId) is used for attributes like
<div data-product-sheet-id="n" class="productSheet"></div>
var x = 5;
var productSheet = $('div[data-productSheetId =' + x + ']');
This is going to do trick. Just change the variable x when selecting.
Related
I got a string like this:
var select_string = '<select><option>1</option><option>2</option></select>';
I need to add some data params to select in this string and get this string back in order to get the following:
select_string = '<select data-param1="param1" data-param2="param2"><option>1</option><option>2</option></select>';
I tried to use jQuery functions like .html() or .text() but it did not work. Like this:
select_string = $(select_string).data('param1', 'param1').html() //or .text()
Any ideas how to make it work would be helpful. Thank you.
You can use attr to add that attributes to the element
var select_string = '<select><option>1</option><option>2</option></select>';
var select = $(select_string).attr({
'data-param1': 'param1',
'data-param2': 'param2'
});
console.log(select.prop('outerHTML'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Since your attribute name starts with data-, if you want to get the value, you can use:
select.data('param1'); // param1
select.data('param2'); // param2
EDIT: Titulum is right, jquery is not needed here.
But here is the working example usign jquery
var selectString = '<select><option>1</option><option>2</option></select>';
var $select = $(selectString);
$select.attr("prop_key","prop_value");
var selectChanged = $select.prop('outerHTML');
console.log(selectChanged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You don't need jQuery for this:
const myElement = document.createElement('div');
myElement.innerHTML = "<select><option>1</option><option>2</option></select>";
const selectElement = myElement.getElementsByTagName("select")[0];
selectElement.setAttribute("data-param1", "param1");
selectElement.setAttribute("data-param2", "param2");
You could use indexOf and substr() to split it into 2 parts, insert your new text, and put it back together again.
var first_half = select_string.substr(0, select_string.indexOf('>'));
var second_half = select_string.substr(select_string.indexOf('>'));
select_string = first_half + ' data-param1=\"param1\" data-param2=\"param2\" ' + second_half;
I need to get the classname from an element, but I only know a part of the name.
<div class="anotherclass my-class-no-1 onemoreclass...">div>
I can call the element with this
$([class*="my-class-no-"]...
But how can I get the complete classname?
Thanks a lot for explaining.
You can use className and search the class name containing your substring
let subclass = 'my-class-no-';
$('[class*="'+subclass+'"]').each(function() {
let name = this.className.split(' ').find((className) => {
return className.indexOf(subclass) !== -1;
});
console.log(name);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass">
<div>
try it
console.log( $(".anotherclass").attr("class").split(' '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass"><div>
I'll do something like that:
(See comments in the snipper)
var search = "my-class-no-"; // Added to enter the searched class only once
var elms = $("[class*=" + search + "]"); // Get match
var classstr = elms.attr("class"); // Get the class attribute
// Split the string class attribute string to only keep the class that was searched
var myClass = classstr.substring(classstr.indexOf(search)).split(" ")[0];
console.log(myClass);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass"></div>
Click here for code
Inside loop of {listOfValue}
i want to find different column values filtered by data-week = {listofvalueObject}
and want to add data in each row based on column segregated by this data-week attributes value.
I have assigned the values form a list so it every column has different data-week value.
I have tried :
var allColumnValClass = j$('.columnVal').filter('[data-week]');
var allColumnValClass = j$('.columnVal').filter('[data-week='Something dynamic ']');
You should be able to select them like this:
var allColumnValClass = j$('.columnVal[data-week]')
and
var allColumnValClass = j$('.columnVal[data-week="' + Something dynamic + '"]')
Hope this helps.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='columnVal' data-week="1"></div>
<div class='columnVal' data-week="2"></div>
<div class='columnVal' data-week="3"></div>
<script>
var dataList = $(".columnVal").map(function () {
return $(this).data("week");
}).get();
for (var i = 0; i < dataList.length; i++) {
console.log(dataList[i]);
}
</script>
cheers
This question already has an answer here:
Jquery get Name value of hidden field
(1 answer)
Closed 6 years ago.
I have little of an issue writing my script.
$(function(){
$(".wolny").click(function() {
var godzina = this.id;
var minuta = this.name;
alert(godzina + ":" + minuta);
});
Alert should give me output looking like so hour:minute. Instead of that I am getting this: hour:undefined. I really dont know what to do :x
Here's HTML code (php generated)
<div class="col-sm-3 kafelek wolny" name="15" id="9"></div>
Thank's for any help.
A div element doesn't technically have a name attribute. If you want to store a piece of data, store it as a data-* attribute. Something like this:
<div class="col-sm-3 kafelek wolny" data-name="15" id="9"></div>
Then retrieve it as such:
var minuta = $(this).data('name');
Try using .attr() function instead like so:
var minuta = $(this).attr('name');
This works because name in your case is a attribute and not a property. This will work with any random attribute like foo that you may add.
A better way is to add a data attribute like data-name="something" and read it with $(this).data(name).
Working Example:
$(function(){
$(".wolny").click(function() {
var godzina = this.id;
var minuta = $(this).attr('name');
alert(godzina + ":" + minuta);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3 kafelek wolny" name="15" id="9"> Click me! </div>
Try this instead:
$(function(){
$(".wolny").click(function() {
var godzina = $(this).attr('id');
var minuta = $(this).attr('name');
alert(godzina + ":" + minuta);
});
});
However, if possible, I would recommend using data attributes for your values. Here's an example:
<div class="col-sm-3 kafelek wolny" data-hour="9" data-minute="15"></div>
Then, in the JavaScript, you use "data-hour" and "data-minute" for the attributes instead of "id" and "name" like it is now.
I'm trying to add the content of each span along with the value in the title attribute.
<div id="group-wrap" class="group">
<span class="lbracket" title="&f">(</span>
<span class="grouptitle" title="&f"> Group </span>
<span class="rbracket" title="&f">) </span>
<span class="username" title="&f"> Username </span>
<span class="col" title="&f">:</span>
<span class="text" title="&f"> Helo There! </span>
</div>
Here is what I have so far:
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title'));
});
alert(str.join(''));
});
http://jsfiddle.net/B9QeK/3/
The output is &f&f&f&f&f (the value of each title attribute), but the expected output has the value, plus the content that is in the span. The value of the attribute should be appended before the content.
&f(&fGroup&f)&fUsername: &f text
How can I get this result?
Looks like you are looking for
str.push( this.getAttribute('title'), this.textContent || this.text );
As for performance reasons, you should not re-create a jQuery object for every single iteration. Even better, don't use jQuery at all to receive those values.
JSFiddle
And by the way, you can make usage of jQuerys .map() to do it a bit more elegant:
jQuery(function($){
var str = $('#group-wrap span').map(function(){
return this.getAttribute('title') + this.textContent || this.text;
}).get();
alert(str.join(''));
});
JSFiddle
Reference: .map()
jQuery(function($){
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Working JSFiddle
text:
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
docs
Just use the text method to get the text content of each span:
var str = [];
$('#group-wrap span').each(function(){
//Push value of title attribute and text content into array:
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Your line
str.push($(this).attr('title'));
Should look like:
str.push($(this).attr('title') + $(this).text());
Although, this is making two identical calls $(this), so you might consider caching:
var $this = $(this)
str.push($this.attr('title') + $this.text());
var str = "";
$('#group-wrap span').each(function(){
str+=$(this).attr('title')+$(this).text();
});
alert(str);
});