How do I return a specific attribute of a variable using d3?
For example, I want to select an element by mouseover, and pass on the selection to a function, but only if the element's id is a particular name.
Something like this?
d3.select("body").on("mouseover", function(){
if (d3.select(this).attr("id") == "correct") {
enableInteraction(d3.select(this));
}
});
Yes. Select this and then use the usual functions to access properties.
Related
I'm trying to select element by data attribute defined with jquery (it's not visible in DOM), therefore I cannot use $('.foo:data(id)')
example: if user clicks element I add data property to it as following
$(this).data('id', '1');
now I would like to find element which has
data-id == 1
how can I select this element by data-id?
Use filter()
$('.foo').filter(function(){
return $(this).data('id') === `1`
}).doSomething()
You could use the attribute selector [attribute=...].
In your case, this would be
$('[data-id=1]')
But keep in mind, if you change the data of an element with .data(), the change isn't reflected in the dom attribute, so you can't use this (or additionally change the dom attribute).
The other way would be to select every candidate and then filter for each element, which has a matching data value.
$('.foo').filter(function(){
return $(this).data('id') == 1;
});
sorry for asking that stupid:D However what did i do wrong here?
html:
<div onclick="prompt()" value="test">test</div>
javascript:
function prompt() {
var error = this.value;
alert("sdsd");
}
Thanks!
First off, <div>s don't have a value attribute, so .value won't work. Second, you should not use inline JavaScript.
What you should do is:
<div id="test" value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
// You need to get the attribute from the element
var error = $(this).attr('value');
});
});
If you must use inline events, then you need to pass the element to the prompt() function. The problem is that it doesn't know what this is. This is why you should bind the event as shown above. Anyway, you can also do:
<div onclick="prompt(this)" value="test">test</div>
Then:
function prompt(ele){
// You can't use `.value` because `<div>`s
// don't have a value property
var error = ele.getAttribute('value');
}
P.S. May I also suggest using data-* attributes for this instead of invalid attributes?
<div id="test" data-value="test">test</div>
Then:
$(function(){
$('#test').click(function(){
var error = $(this).data('value');
});
});
The value of this depends on how the function that it appears in was called.
When the browser calls the onclick function from the event trigger, this is the input.
When you call prompt(), because you provided no context and you are no in strict mode, this is the window.
You need to explicitly pass the value.
onclick="prompt.call(this)"
Better yet, don't use intrinsic event attributes in the first place. They mix your HTML and logic and have a whole collection of gotchas to go with them.
Then you have a second problem.
Div elements don't have values. Only inputs and other form controls do. You would need to use .getAttribute("value") instead of .value … but that still leaves your HTML invalid (as well as inappropriate - div elements aren't designed to be interacted with, they give no visual indication that they should be clicked on, and they won't receive the focus should the user not be using a mouse or other pointing device anyway).
You should use a control designed to be interacted with.
Finally, prompt is a built in function, so you should avoid overwriting it and pick a different name instead.
function show_value(event) {
var value = this.value;
document.body.appendChild(document.createTextNode(value));
}
document.querySelector("button").addEventListener("click", show_value);
<button type="button" value="test">test</div>
Div does not have value attribute.
If you need to get the value inside div element you can do it by innerHTML property.
function prompt() {
var error = this.innerHTML; // OR this.getAttribute("value");
}
I have to add a list of checkboxes dynamically. I then need to know which one performed the click, then ask if it's checked or not.
I have this code:
$('#MyContainerOfChecksDiv').click( '.MySelectorClass', function(){
if ("MyCheckClicked".is(':checked'))
{
//...here i need to use the label and id
}
else{...}
})
using "$(this)" i get the "MyDiv", obviously using $(this).find('input:checkbox') I get the whole list of checks.
I have to get this checkbox because I need to use its properties.
Add a formal parameter to click handler and use it like this
$('#myDiv').click('.MySelectorClass', function (e) {
if ($(e.target).is(':checked')) {
alert(e.target.id);
}
})
fiddle
Also it's not quite clear to me how you distinguish dynamically added elements and static. Do you have different class for them? If so then you dynamic and static elements can have different handlers and this will be the way to tell whether it was created dynamically
To delegate to dynamic elements you have to use .on(). The element that you clicked on will be in this.
$("#myDiv").on("click", ".MySelectorClass", function() {
if (this.clicked) {
// here you can use this.id
} else {
// ...
}
});
You can't use .click() to delegate like you tried. You're just binding the click handler to the DIV, and the string ".MySelectorClass" is being passed as additional data to the handler.
im working with my first webapp, Im using ajax parsed object to add dynamic content to one specific .html... while doing so, I found an issue with adding data-* attribute to every option on a select dropdown... when the change function from JQuery executes, it returns undefined.
Here is my ajax function, (I know its not the best way to do it).
ajaxPost("link/x.php",{},function(result){
var json=JSON.parse(result);
var resultado=json.response;
if(json.error==0){
var estadosString='<option value=""></option>';
var cont=0;
for(estado in resultado){
estadosString+=('<option value="'+resultado[estado].nombre+'">'+resultado[estado].nombre+'</option>');
}
$('#estados').html(estadosString);
cont=0;
$('#estados option').each(function(){
$(this).attr('data-id',cont);
$(this).data('id',cont++);
});
}else{
alert("No hay estados");
}
});
The data-id attribute is sucefully added to each option, the issue starts when I use this code to get data-id on change select option.
$('#estados').on('change',function(){
alert($(this).data("id"));
});
It always return undefined, anyone can help me? Thanks..!
The value of this in that "change" handler will be the <select> element, not the <option> it's set to. You can find the option element via the select element's selectedIndex property, or via jQuery.
There's no reason to set the "data-id" attributes either; just set the value via .data().
I have a function in which I want the selector that I am passing to do the enclosed processes. The functions are listed below:
function menuselector (id){
$(id).css('background', 'url(../img/black_denim.png) repeat');
$(id).css('color', '#FFF');
}
function menudeselector (id){
$(id).css('background', 'none');
$(id).css('color', '#CE0101');
}
menuselector('mgi');
mgi is an ID of a div tag
Ids are targeted by using a hash before the id, the same as in CSS.
If you're passing
menuselector('mgi');
You will need to adjust it to make it a valid selector.
$('#' + id).css(...
or you can send the valid selector
menuselector('#mgi');
assuming you have an element with that id (you haven't shown that)
<div id="mgi">
Aside
You shouldn't keep selecting the element. You can either chain
$(id).css('background', 'none').css('color', '#CE0101');
// on new lines for readability if there are a lot of actions
$(id).css('background', 'none')
.css('color', '#CE0101');
or use an object
$(id).css({background: 'none', color: '#CE0101'});
mgi is not a valid selector. You should write:
menusector('#mgi');
or
menuselector('.mgi');
depending on whether you want to select an ID or a class.
You could use popnoodle's solution, if your function should only be applicable to IDs, although making it restrictive like that seems like poor generality.
Just pass '#mgi' if it is an ID:
menuselector('#mgi');