How to pass value of span to callback on click ?
<span class="test" onClick="testFunction(this);">Test</span>
function testFunction(e) {
alert(JSON.stringify(e));
}
But I always get in alert
{}
How to pass/extract text from span ?
I need to have onClick inside tag, not to attach on another way.
You are passing the element to the function correctly.
It's when you use JSON.stringify that you don't get any result. The element only has members defined in its prototype, it doesn't have any members added to the object instance itself. The stringify function only includes members of the object instance, not from its prototype, so you get the same as if you called it on an empty object.
If you get some property from the element and show that, you see that you actually have a reference to it:
function testFunction(e) {
alert(e.tagName); // shows "SPAN"
}
or:
function testFunction(e) {
alert(e.innerHTML); // shows "Test"
}
Demo: http://jsfiddle.net/F3S4T/
You could do something like:
<span class="test" onClick="testFunction(this);">Test</span>
function testFunction(elem) {
alert(elem.innerHTML);
}
To get the content inside the span tags (or any HTML tags) you can use the innerHTML property of the element. E.g,
function testFunction(e) {
alert(e.innerHTML);
}
Related
I'm trying to reference an object inside of a div, using plain JavaScript:
<div id="main">
<div id="search">
<input type="text" id="query" />
<button onclick="test()">OK</button>
</div>
</div>
<script>
function test() {
try {
var main = document.getElementById("main");
var search = main.getElementById("search");
alert(search);
} catch (e) {
alert(e);
}
}
</script>
But I keep getting this error:
TypeError: main.getElementById is not a function(…)
Referencing main works, but not what's inside of main.
I also set up a Fiddle.
To find an element inside of other use querySelector
document.querySelector('#main #search')
As ID is unique, you can directly use
document.getElementById('search')
The reason for the error is there is no method called getElemetnById() attached to the Element object.
Since ID of an element must be unique there is need to do that, just use document.getElementById().
But if you want to make sure the said element is a descendant of anotehr element you can use document.querSelector('#main #search')
DOM Elements don't have getElementById method. Only document object have this method.
Id attribute specifies a unique id for the element.
It means only one element can have id="search". So you can use document.getElementById("search");
I want to append this to my document:
$('#myDiv).append("<div id='myDiv2' onclick="+extElementConfig.onClickDo+">Do</div>");
The snippet above has it's onClick populated by a certain object with properties,
this:
var extElementConfig={onClickDo:sampleFunc()};
Unfortunately declaring a function into the object property also fires it, as was expected.
How can I achieve the above functionality without triggering the
sampleFunc()?
I just need to dynamically populate the onClick event through an object property.
Assuming you have control over the extElementConfig object, remove the parenthesis from sampleFunc
var extElementConfig={extElementPosition :10,extElementId:'mailOrderBtn',onClickDo:sampleFunc};
As Rob. M. pointed out the real problem with your code was the fact you were running the code when it was in the object instead of assigning a reference. And when you tried to assigning the onclick, that had issues too since you are trying to use a function reference when it was a string.
To get your code to run, it would be something like
function sampleFunc () {
alert("clicked");
}
var extElementConfig={onClickDo:"sampleFunc()"};
$('#myDiv').append("<div id='myDiv2' onclick='"+extElementConfig.onClickDo+"()'>Do</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv"></div>
To get rid of this, do not use the sting method to build up the element, instead leverage the power of jQuery. Below is an example where I build a div and pass in some arguments to change the element's text and css when clicked.
function sampleFunc(txt, css) {
$(this).text(txt).css(css);
}
var extElementConfig = {
onClickDo: sampleFunc,
onClickArgs : ["Clicked", {"background-color":"green"}]
};
$('<div/>', {
id: 'myDiv2',
text: 'Do!'
}
).on("click",
function() {
extElementConfig.onClickDo.apply(this, extElementConfig.onClickArgs);
}
).appendTo("#myDiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myDiv"></div>
I am overlooking something pretty fundamental here. I want to color a specific element in a group whenever a checkbox is clicked. So I need to make these elements observable.
This is what my html looks like
<p>
<label>
<i>bla2</i>
<input type="checkbox" />
</label>
</p>
<p>
<label>
<i>bla3</i>
<input type="checkbox" />
</label>
</p>
My JS looks like this
$(document).ready(function() {
function handleCheckbox () {
if ( $(this).closest(':checkbox').is(':checked') ) {
$('this').closest('i').css('color','green');
} else {
$('this').closest('i').css('color','red');
}
}
handleCheckbox();
$('label').on('click', handleCheckbox() );
});
.closest() looks at the current element and then up the hierarchy at ancestors, not at neighbors. In your case, this will point to the label object so you can look at children to find the <i> tag and <input> tag. You also have several other coding errors.
Also, your handleCheckbox() function needs the value of this set to a <label> object in order to work properly so you can't just call it direct and expect it to set all the colors appropriately. Instead, you will have to iterate over all the labels in the page and call handleCheckbox() for each one. I've done that in the code below with .each().
Here's a way to fix it:
$(document).ready(function() {
function handleCheckbox() {
// the this pointer here will point to the label object so you need
// can use .find() to find children of the label object
var newColor;
if ($(this).find("input").is(":checked")) {
newColor = "green";
} else {
newColor = "red";
}
$(this).find("i").css("color", newColor);
}
// hook up click handler and initialize the color for all labels
$('label').on('click', handleCheckbox).each(handleCheckbox);
});
See working demo: http://jsfiddle.net/jfriend00/tRQ99/ and also notice that the initial color is set based on the initial checkbox state too.
Your code had these issues:
.closest() goes up to ancestors. It doesn't find neighbors.
When passing a callback function, you don't use the () at the end because that causes it to execute immediately and pass the return value of executing the function. You just want to pass a reference to the function which is done without the parens.
You don't quote this. Treat it like a javascript variable, not a string.
The this pointer will point to the label object in your callback so you need to look at child elements to find the <i> and <input> objects. You can use either .children() or .find() to find them.
You initial call of handleCheckbox() was not working because it works only when this is set to a <label> object (the way it works in the event handler). So, to use the same function for initialization as the event handler, you need to iterate over all the labels and make sure this is set appropriately for that function. A simple way to do that is with .each() as I've shown in my code suggestion.
You're passing a function in rather than using an anonymous function, so remove the ()
$('label').on('click', handleCheckbox);
Else this will execute right away on page load. Also, unquote this:
$(this).closest('i').css('color','green');
Fiddle for what you probably want here:
http://jsfiddle.net/93CeR/2
$(document).ready(function() {
function handleCheckbox () {
if ( $(this).find(':checkbox').is(':checked') ) { // Use .find instead of closest because the element you want is a child
$(this).find('i').css('color','green'); // Remove qoutes from this and use .find for same reason as above
} else {
$(this).find('i').css('color','red'); // Ditto
}
}
$('label').each(function(){
handleCheckbox.apply(this); // We need to call the function initially using 'label' for this.
});
$('label').on('click', handleCheckbox ); // You want a reference to handleCheckbox not to invoke it so remove the parenthesis
});
Here's how I append the value:
$('<div>someText</div>').appendTo(self);
And here's how I want to remove it:
$(self).remove('<div>someText</div>');
The appending works, the removing doesnt. What am I doing wrong?
The .remove() function takes a selector to filter the already matched elements, not to match elements inside of them. What you want is something like this:
$(self).find('div:contains(someText)').remove();
That will find a <div> element containing the text someText inside of whatever element self is, then removes it.
The API http://api.jquery.com/remove/ sais that a selector is required.
Try $(self).remove('> div');
This will remove the first childs of div.
You can use $(self).filter('div:contains("someText")').remove(); to remove a div with a specific content or $(self).find('> div').remove(); to remove the first childs of div.
EDIT: removed first version I posted without testing.
It most likely has to do with the scope of self. Since you've named it self I am assuming that you are getting this variable using $(this) on the click event. If that's the case, and you want to call the remove method, you can only do so from within the same function. Otherwise you need to either store the element in a variable or provide another selector to access it.
Example:
<div class="div1"></div>
this will be the div with the click event
$(document).ready(function(){
var self = null;
$('.div1').click(function(e){
self = $(this);
var itemToAdd = '<div>SomeText</div>';
$(itemToAdd).appendTo(self);
});
// to remove it
// this will remove the text immediately after it's placed
// this call needs to be wrapped in a function called on another event
$('.div1').find('div:contains(someText)').remove();
});
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.