How to reach this element? - javascript

<div class="ptp-item-container">
<div class="plan">Text I want!</div>
<div class="price">200</div>
<div class="bullet-item">some other text</div>
<div class="cta"> <a class="button" href="javascript:getText()">Go!</a>
</div>
</div>
From the button I tried this:
function getText(){
alert($(this).parent().parent().children().text() );
}
This doesnt really work, I know there is a way! It's important to use $(this) for this time.
Edit: This is the whole Javascript:
<script>
jQuery(document).ready(function($) {
$(".ptp-button").attr("href", "javascript:getText()");
});
function getText(){
alert($(this).closest('.ptp-item-container').find('.plan').text());
}
</script>
But the console says "Uncaught TypeError: undefined is not a function VM4092:1(anonymous function)"
Dont I have to give $(this) as an argument on javascript:getText($(this)) or something like this?

You shouldn't be targeting it with javascript: href. Instead, use an .on() handler, that is the correct way to handle the click event on JQuery. Then you'll be able to use the this reference:
Then, as already answered, instead of navigation through the parents, use the .closest() function:
$('.ptp-item-container').on('click', '.button', function() {
alert($(this).closest(".ptp-item-container").find(".plan").text());
});

You can use a combination of .closest() and .find():
alert($(this).closest(".ptp-item-container").find(".plan").text());
It pays to spend some time browsing the jQuery API documentation.

Related

Copy and paste text from a div to another [jQuery]

I am trying to do a thing that seems easy to me but I'm not very familiar with javascript language and I can't find any documentation to do what I want.
Let's say I have a code like this:
<div id="sourceA">Text</div>
<div id="sourceB">Another</div>
<div id="destination"></div>
Let's say I click on the "sourceA" div, the text contained in it should go in the "destination" div.
Unfortunately, I have no idea how to do it. Can you help me? And maybe also suggest me somewhere I can go and learn something more about this code?
Read more about JavaScript and jQuery events. What you need here is a .click() event on sourceA to handle your behaviour as follows:
$("#sourceA").click(function() {
$("#destination").html($(this).html());
});
HTML:
<div id="sourceA" class="source">Text</div>
<div id="sourceB" class="source">Another</div>
<div id="destination"></div>
JS:
$('.source').click(function(e) {
$('#destination').text($(e.currentTarget).text())
});
Take a look at this example
var copyContentToDestinationClickHandler = function(event) {
$('#destination').empty();
$('#destination').append($(event.target).text());
}
$('#sourceA').click(copyContentToDestinationClickHandler);
$('#sourceB').click(copyContentToDestinationClickHandler);
https://jsfiddle.net/7v5a6bsu/

How to add onclick to an element using Javascript

I have an HTML button like so:
<div class="row text-center">
<button id="button1" type="submit" class="btn btn-primary">Submit</button>
</div>
I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:
$("#button1").addEventListener("click", showAlert());
However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?
With jQuery you can use .on():
$("#button1").on("click", showAlert);
or
$("#button1").click(showAlert);
addEventListener is a plain JavaScript method and you're trying to use it on a jQuery object. You could dereference the jQuery object using .get(0) and use it like:
$("#button1").get(0).addEventListener("click", showAlert);
or
$("#button1")[0].addEventListener("click", showAlert);
but there's really no reason.
try jquery function:
$("#button1").click(function() {
.. whatever you want to do on click, goes here...
}) ;
You could try the following:
$( "#button1" ).bind( "click", showAlert);

Can't fire click event on the elements with same id

Could you help me to understand - where I made the mistake. I have the following html code:
<div id="container">
Info mail.ru
</div>
<div id="container">
Info mail.com
</div>
<div id="container">
Info mail.net
</div>
and the following js code (using jQuery):
$('#getInfo').click(function(){
alert('test!');
});
example here
"Click" event fired only on first link element. But not on others.
I know that each ID in html page should be used only one time (but CLASS can be used a lot of times) - but it only should (not must) as I know. Is it the root of my problem?
TIA!
upd: Big thx to all for explanation!:)
Use a class for this (and return false in your handler, not inline):
<div id="container">
Info mail.ru
</div>
<div id="container">
Info mail.com
</div>
<div id="container">
Info mail.net
</div>
$('.getInfo').click(function(){
alert('test!');
return false;
});
http://jsfiddle.net/Xde7K/2/
The reason you're having this problem is that elements are retrieved by ID using document.getElementById(), which can only return one element. So you only get one, whichever the browser decides to give you.
While you must, according to the W3 specifications, have only one element with a given id within any document, you can bypass this rule, and the issues arising from the consequences if document.getElementById(), if you're using jQuery, by using:
$('a[id="getInfo"]').click(function() {
alert('test!');
return false;
});
JS Fiddle demo.
But, please, don't. Respect the specs, they make everybody's life easier when they're followed. The above is a possibility, but using html correctly is much, much better for us all. And reduces the impact of any future changes within the browser engines, jQuery or JavaScript itself.
It must only be used once or it will be invalid so use a class instead, return false can also be added to your jQuery code as so: -
$('.getInfo').click(function(){
alert('test!');
return false;
});
<a href="#info-mail.net" **class**="getInfo" ....
First id's are for one element only, you should have same id for several divs.
you can make it class instead.
your example changed:
<div class="container">
<a href="#info-mail.ru" class="getInfo" >Info mail.ru</a>
</div>
<div class="container">
<a href="#info-mail.com" class="getInfo" >Info mail.com</a>
</div>
<div class="container">
<a href="#info-mail.net" class="getInfo" >Info mail.net</a>
</div>
$('.getInfo').click(function(ev){
ev.preventDefault(); //this is for canceling your code : onClick="return false;"
alert('test!');
});
You can use the same id for several element (although the page won't validate), but then you can't use the id to find the elements.
The document.getElementById method only returns a single element for the given id, so if you would want to find the other elements you would have to loop through all elements and check their id.
The Sizzle engine that jQuery uses to find the elements for a selector uses the getElementById method to find the element when given a selector like #getInfo.
I know this is an old question and as everyone suggested, there should not be elements with duplicate IDs. But sometimes it cannot be helped as someone else may have written the HTML code.
For those cases, you can just expand the selector used to force jQuery to use querySelectorAll internally instead of getElementById. Here is a sample code to do so:
$('body #getInfo').click(function(){
alert('test!');
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id="container">
Info mail.ru
</div>
<div id="container">
Info mail.com
</div>
<div id="container">
Info mail.net
</div>
</body>
However as David Thomas said in his answer
But, please, don't. Respect the specs, they make everybody's life easier when they're followed. The above is a possibility, but using html correctly is much, much better for us all. And reduces the impact of any future changes within the browser engines, jQuery or JavaScript itself.

How to select an object in JQuery?

I'm beginner in JQuery, how could I select an object using JQuery ?
This is the code:
<script type="text/javascript" language="javascript">
function Hide(senderID) {
$("#" + senderID).hide(200);
// this exception is thrown // Microsoft JScript runtime error: Object expected
}
</script>
<div id="div1" onclick="javascript:Hide(this.id)"
Any help!
Don't:
get an id from an element
pass that id to a function
use the id to get the element.
Do: Just pass the element.
Don't stick javascript: at the front of an intrinsic event attribute, it doesn't mean what you think it means.
Don't use intrinsic event attributes for that matter (although I didn't fix this in this example). Use unobtrusive JS.
Avoid triggering events based on clicks on a div. This can't be targeted with a focus based navigation device (such as using the tab key on the keyboard and numerous devices used by people with disabilities) without using new features introduced in HTML 5 that don't see widespread support yet. Use an element that is designed as an interaction control (such as a button). (Also not fixed in the example below)
Example:
function Hide(sender) {
$(sender).hide(200);
}
<div id="div1" onclick="Hide(this)"
Code is exactly the same as yours, I added the correct tags, and the call to include the jquery library:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
function Hide(senderID) {
$("#" + senderID).hide();
}
</script>
<div id="div1" onclick="javascript:Hide(this.id)">Click Me</div>
function Hide(sender) {
$(sender).hide(200);
}
<div id="div1" onclick="javascript:Hide(this)"></div>
hope it helps
I can't resist. Why not use jQuery's full power?
HTML:
<div class="hideable-div">Click me and get rid of me.</div>
jQuery:
$('.hideable-div').click(function () {
$(this).hide(200);
});
you misplaced those "" in
<div id="div1" class=""hideable-div>Click me and get rid of me.</div>
Should be like
<div id="div1" class="hideable-div">Click me and get rid of me.</div>

Very basic question about parent() and prev() in jQuery

I am handling a hyperlink's click event with a JavaScript function. I want to retrieve data from the hyperlink.
The page looks like this:
<div class="div1">
<div title="Title 1" class="div2">
<p class="p1"><a class="linkJs">The link in question</a></p>
</div>
</div>
<div class="div1">
<div title="Title 2" class="div2">
<p class="p1"><a class="linkJs">The link in question</a></p>
</div>
</div>
And the JavaScript something like this:
$(function() {
$('a.linkJs').click(function(){
value=$(this).parent().prev().text();
alert(value);
});
});
What I want to have is the value of the TITLE in the div2. By clicking the first link I get : Title 1. And by clicking on the 2nd: Title 2.
This must be very very basic but I just can't find my answer anywhere.
Thanks.
You want to use closest
var value = $(this).closest('div').attr('title');
Your problem is that the <p> tag is not a sibling to the <div> but a child, so you would have to do parent() twice - there's no need, though, as the closest function is a handy shortcut. Also, the text() function returns the pure text contents inside the tag, if you want the title attribute of the tag you need to use the attr function.
You can find it with the closest method:
$('a.linkJs').click(function(){
value=$(this).closest('div').attr('title');
alert(value);
});
try using the closest() method: http://api.jquery.com/closest/
Get the first ancestor element that
matches the selector, beginning at the
current element and progressing up
through the DOM tree.
$(function() {
$('a.linkJs').click(function(){
value=$(this).closest(".div2").attr("title");
alert(value);
});
});
var value = $(this).closest('.div2').attr('title');
Instead of using div, .div2 may be a more appropriate selector because there may be other div elements inside div.div2.
Not very pretty, but this should work too.
$(function() {
$('a.linkJs').click(function(){
value=$(this).parents()[1];
alert($(value).attr('title'));
});
});

Categories