Access inner text using $(this) with jQuery - javascript

I have a button and I want to log the inner text using the jQuery when that button is clicked. I know how to use the id to get the text of the buttton ($("#testID").text()), but that's not an option for me. I would like to use the $(this) keyword instead of the id, but I'm not sure how to do that.
The html:
<button id="testID" onclick="getButtonText()">Button Text</button>
The javascript:
function getButtonText() {
console.log("this text = " + $(this).text()); //not working
}

Pass in this
The html:
<button id="testID" onclick="getButtonText(this)">Button Text</button>
The javascript:
function getButtonText(self) {
console.log("this text = " + $(self).text()); //not working
}
Otherwise, this will be the window object

You need to pass the caller element to the function...
function getButtonText(element) {
var $this = $(element);
console.log("this text = " + $this.text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="testID" onclick="getButtonText(this)">Button Text</button>
Though the proper jQuery way of doing it would be like this...
$('#testID').on('click',function() {
console.log("this text = " + $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="testID">Button Text</button>

You can give it a class on the button and then whenever a class is click, it will determine the DOM, which is $(this). Example:
In your html file:
<button id="testID" class="test-btn">Button Text</button>
In your script file:
$(document).ready(function () {
$(".test-btn").click(function(){
$("#message").text("The Text is: " + $(this).text() );
});
});
See my example on Plunker: http://plnkr.co/edit/e94QraQfCOzGlkirvTJj?p=preview

Related

Set javascript variable to the value of a button with different text

I have a button thats value is set based on a mysql query in php like so:
echo "<td><button class='jsontable' onclick='Copythat(this.value)' value='" . $row['json'] . "'> " . $row['name'] . "</button></td>";
the text of the button is the name row, which works currently.
and a function that i have basically in place to try and grab the string and send it to the load function. the load function needs to receive only text of that mysql row json
function Copythat(el.val) {
var jsontoload = $(el.val).html();
load(jsontoload);
}
If you pass this to your function, you get the context of the element where the event occurred. Once you've got that, you can pass it to jQuery and you can get the "value" attribute using the .val() shortcut method.
Note that function Copythat(el.val) { needs to be something simply like function Copythat(val) { - function parameters must be standalone variables, they cannot be written like object properties.
function Copythat(input) {
var attrValue = $(input).val();
alert(attrValue);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
You could also convert the whole thing to jQuery and ditch the inline event handler:
$(function() {
$(".jsontable").click(function(event) {
var attrValue = $(this).val();
alert(attrValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' value='Something'>A button</button>
Or it should also be noted that for something as simple as this you don't really need jQuery at all:
function Copythat(input) {
alert(input.value);
}
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
Another further simplification if you literally only need the value to go into your function:
function Copythat(input) {
alert(input);
}
<button class='jsontable' onclick='Copythat(this.value)' value='Something'>A button</button>

Javascript: Passing a function as argument which will be executed at onclick event

I would like to creat a confirm box based on the idea that when the button is clicked, a div is appended
to the body, and its OK button executes a function given as argument. I managed to do it if the function name is not a variable, but in this case I would need as many confirm boxes as many types of functions I have.
Here's the html button:
<button onclick=" executeAfterConfirmed( myFunc );">SHOW</button>
Here's the confirm box function:
function execAfterConfirmed( functionToExecute , arg ){
$("body").prepend("<div id='createdConfirmDiv' ><img id='closeImg' src='close.png' height=30 onclick='$(\"div#createdConfirmDiv\").remove()'>CONFIRM ?<br><button class='myConfirmButton' id='yesButton' onclick='$(\"div#createdConfirmDiv\").remove();" + functionToExecute + "("+arg+")'>YES</button><button class='myConfirmButton' onclick='$(\"div#createdConfirmDiv\").remove()'>NO</button></div>");
}
However, I got Unexpected token (
Just add the handler programmatically...
function myFunc() {
alert("myFunc!");
}
function executeAfterConfirmed(functionToExecute, arg) {
var $show = $("#show-button").hide();
$("body").prepend("<div id='createdConfirmDiv'>Test dialog<br><button>OK</button></div>");
$("#createdConfirmDiv button").one("click", function(e){
functionToExecute(arg);
$("#createdConfirmDiv").remove();
$show.show();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="show-button" onclick="executeAfterConfirmed(myFunc);">SHOW</button>
I hope I did understand your problem, as you are trying to describe. Here is a solution:
function confirmBox(button, message, func) {
button.addEventListener('click', function(){
var re = confirm(message);
if (re) func();
})
}
confirmBox( document.getElementById('button'),
"You clicked because you liked me.",
function(){
// do stuff
});
CSS
.createdConfirmDiv{display(none;}
HTML
<body>
<div id='createdConfirmDiv' >
<img id='closeImg' src='close.png'width="www" height="30" onclick="(remove(0)">CONFIRM?
<br>
<button class='myConfirmButton' id='yesButton' onclick=("remove(1)");>YES
</button>
<button class='myConfirmButton' onclick=("remove(2)";)>NO
</button>
</div>
SCRIPT
myFunc function(f,a){
document.getElementById('createdConfirmDiv').sytle.display='block');
}
remove function(r){
document.getElementById('createdConfirmDiv').sytle.display='none');
if (r==0){
}
if (r==1){
}

Add new classname for element onclick()

This is my code in jsfiddle:
http://jsfiddle.net/qn7JG/1/
function go_to(lat,lon,hinttext,balloontext,event){
var domElement =$(event.target);
domElement.addClass('selected');
console.log(domElement);
return false;
}
I'm want to add new classname, when I click by link.
How I can do it?
EDITED
I was in hurry on last post an I forget the most important addClass :)))
I hope you get the clue with jquery data params.
After a lot of testing I find a solution for you
html:
<div id="res">
<a href="" class="ff" data-lat="123 " data-long="321 " data-hinttext="some hit text !" data-ballon="balloontext" >textr123</a>
</div>
js:
$('.ff').live('click', function(e) {
e.preventDefault();
var lat = $('.ff').data('lat');
var long = $('.ff').data('long');
var hinttext = $('.ff').data('hinttext');
var balloontext = $('.ff').data('ballon');
alert(lat + long + hinttext + balloontext);
$(this).addClass('selected');
return false;
});
});
and the DEMO IS HERE
Try this
$(element_id).addClassName(newClassName);
It will simply Add the class name.It won't remove the previous class name.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).click(function(event) {
var text = $(event.target.nodeName).selector;
$(text).addClass("newclass");
});
</script>
<style>
.newclass{
color: #00ff00;
}
</style>
<p>hello</p>
<input type="text" id="amount"/>

How to define a method and attribute to my appended div?

I have DIVs dynamically appended to the DOM. I want each of them to have some method, like when I click a button inside the div, the div will be removed from the DOM; and some attributes that I can read from.
So I figure I need an object, but this is what confuses me:
var block = tmpl('added_video_thumb', data);
$('#wrapper').append(block);
I want the block to be the object, so I did this:
var blocks = function(id, data){
this.block = tmpl('added_video_thumb', data);
}
And I changed the code to this:
var block = new blocks('added_video_thumb', data);
$('#wrapper').append(block);
Then I don't know how to define the method, I don't want to call a function like:
$('#delete').click(function(){
block.remove();
})
What I want is when I do this:
var block = new blocks();
It takes care of everything. Please help me construct this blocks object.
If I understand your problem, it is that you want to dynamically create an element and assign methods to it's own children.
HTML
<button id="add">Add</button>
<div class="container">
</div>
JS
function addBlock() {
var div = $( '<div class="inner_div">
<button class="delete">Delete</button>
</div>' );
div.children('button.delete').on( 'click', function() {
$(this).parent().remove();
});
$('.container').append(div);
}
Example on fiddle : http://jsfiddle.net/wyXxn/1/
​
You can check the following fiddle
HTML Code
<input type="text" placeholder="ID" id="id-input" />
<input type="text" placeholder="data" id="data-input" />
<button id="add-div">Add Div</button>
<div id="wrapper">
</div>​
JS Code
$(function(){
var block = function(id, data) {
this.id = id;
this.data = data;
$("#wrapper").append('<div id="' + id + '">'+ data +'<br /> <button id="del-' + id + '">Delete Me!</button> </div>');
$("#del-"+id).click(function() {
$("#"+id).remove();
});
}
$("#add-div").click(function() {
var newBlock = new block($("#id-input").val(), $("#data-input").val());
});
});​

Replace HTML Using jQuery

function toText()
{
var convertHTML =$('#mainContent').html();
var ele = $(convertHTML + " > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
My aim is to replace the following content
<div id="mainContent">
test
<br>
1234
<br>
<span class="underline">test</span>
<br>
<span class="underline">1234</span>
</div>
And want my function to output test <br> 1234 <br> test <br> 1234
This is why i cant just use text() as it takes away the <br> aswell!
Try it like this:
function toText()
{
var ele = $("#mainContent > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
You where using an entire block of html as a jQuery selector :)
You were taking the html string returned from $("#mainContent").html() and trying to use it as part of the selector on the next line, when really the selector you need is "#mainContent > span".
Try this instead:
function toText()
{
$("#mainContent > span").replaceWith(function(){ return $(this).text(); });
}
You don't need an .each() loop: if you pass a function to .replaceWith() that function is called once for each element in your jQuery object and your return value is used as the replacement for the current element.
Demo: http://jsfiddle.net/7xKzP/
convertHTML from var convertHTML =$('#mainContent').html(); is not a jQuery object
You will have to write
var ele = $("#mainContent > span").each(function(){
$(this).replaceWith($(this).text());
});
Reason :
$('#mainContent').html(); will return you the string not a jQuery object for $.each to work.
var ele = $(convertHTML + " > span") would mean
var ele = $("test<br>1234<br><span class="underline">test</span><br><span class="underline">1234</span>" + " > span")

Categories