Getting the source of this click event in JQuery - javascript

I have multiple dynamically created buttons with the same class on my page and when I try to call a function on the click of the button, the function gets called for all of the buttons with the same class.
I want the function to be called for this click event only.
Here is my function:-
$(".js-btn-plus").click(function (e) {
var link = $(e.target);
var val = link.next('.value').text();
val++
link.next('.value').text(val);
});

Maybe generate unique ID for the button and use that as an event reference instead of the class?

.text() returns a string. Convert the string val to a number
val = Number(val) + 1
or
val = +val++

Please could you provide some sample HTML to alongside the JQuery?
From what I can see you may want to have a look at using $(this) instead of e.target
$(document).on('click', '.js-btn-plus', function() {
var val = parseInt( $(this).find('.value').text() );
val++;
$(this).find('.value').text(val);
});
Not 100% sure what it is that you're trying to achieve, there may be a better way of doing it if you could explain a little bit more and provide some HTML to go alongside your question.
Edit: Using the 'on' function allows you to dynamically bind the function events instead of having them have a listener fire when the script is loaded and executed.

My solution:
$(".js-btn-plus").click(function (e) {
var val = parseInt($(this).next('.value').text());
val++;
$(this).next('.value').text(val);
});

Related

jquery not changing src of element

I have a select element in my HTML, i then have an iframe that displays PDFs. i have some jquery code that should change the "src" attribute of the iframe when a user selects an option but so far i cant seem to get it to trigger. when i click an option from the select nothing happens. i have tried using .change() and .on("change") but they do not work. i have console.log within the function but it does not log anything into the console.
The jquery
$(document).ready(function(){
var x = $("#demo-category").val();
$("#demo-category").on("change", "#demo-category", function(){
$("#readframe").attr("src", x);
console.log(x);
console.log("test");
});
});
should you need any more information i will provide it if i can.
Event delegation (that is, your
.on("change", "#demo-category", function(){
) is for when the element that triggers the event is different from the element that the listener is added to. When you want to add a plain listener to a single element, don't pass another selector - if you do that, the listener won't fire. Instead just call .on('change', fn....
Also, you're retrieving x on document load. Retrieve the new value after #demo-category changes instead:
$(document).ready(function() {
$("#demo-category").on("change", function() {
var x = $(this).val();
$("#readframe").attr("src", x);
console.log(x);
console.log("test");
});
});
I think this will work
$(document).ready(function(){
$("#demo-category").on("change", function(){
$("#readframe").attr("src", $(this).val());
});
});

Two Html select drop down apply class for span element using Javascript

I am working on HTML select Dropdown. I have two dropdowns one is for font size adjust and other is for text alignment.
When I select the fontsize from the dropdown it has to apply along with text-capitalize (bootstrap css) and If I select the font alignment all three should apply for the span element. For Example.
<div>
<span id="Title"class="text-capitalize">check</span>
</div>
Right now the code was like this
function changeFont_size () {
var select = document.getElementById('font_size');
// Bind onchange event
select.onchange = function() {
document.querySelector("#Title").className = this.value += " text-
capitalize";
};
}
function changeAlignment () {
var select = document.getElementById('text_align');
// Bind onchange event
select.onchange = function() {
document.querySelector("#Title").className = this.value;
};
}
Actually I am newbe on Javascript. Some how I am not getting.
The output result would be the combination of :
<span class="h1 left text-capitalize">Text</span>
Everything should be in pure javascript.
Thanks in advance. Kindly help me.
Here is the Link
This jsfiddle makes your code work. You need to run the code when the document is loaded, so that your onchange functions are being hooked in time.
It does not work exactly like you intended though. Your alignment classes need to be on the parent element and when you select your alignment, you disregard the previously set h1 or h2 class.
window.onload = function() {
var font_size = document.querySelector('#font_size');
// Bind onchange event
font_size.onchange = function() {
document.querySelector("#Title").className = this.options[this.selectedIndex].value += " text-capitalize";
};
var text_align = document.querySelector('#text_align');
// Bind onchange event
text_align.onchange = function() {
document.querySelector("#Title").className = this.options[this.selectedIndex].value;
};
};
You are mixing things up. There are two ways to bind events (well, two ways which are still common even with recent browsers).
The first one is to put a function call in the onsomething property of an element in the html code. Whatever is put there will be executed when the event happens.
<button onclick="alert('hi');">Click me</button>
You should pass the event object to an event handler instead of writing inline code.
<button id="helloworld" onclick="helloworld_onclick(event)">Run</button>
...
function helloworld_onclick(e) {
alert("Hello world!");
}
If you want to be able to bind events dynamically, if you want to bind multiple events to an object and if you want to keep the JavaScript outside of your HTML, the modern way to to so is with addEventListener.
document.querySelector("#helloworld").addEventListener("click", function(e) {
alert("Hello world!");
});
The event object passed (called e in my functions) contains information about what triggered the event and can be used to prevent default behavior and to control event propagation. You can't use "this" in event handlers, but the element which called the handler will be stored in e.target.
In your code, you created functions which, when called, bind events to the elements. Then you bound those functions to the elements with the html attributes.
Finally, you seem to be stuck between querySelector and getElementById. Note that querySelector(All) returns a static node/nodelist while getElement(s)By(...) returns a live node/nodelist. A static node is a copy of all the information about the element. A live node is a reference to the real element. If you modify the element, it modifies the live node, but the static node will keep the old information. You should use getElementById over querySelector for that, and because it runs faster. For code simplicity however, you might prefer always using querySelector. Just don't mix using querySelector("#something") on a line and getElementById("something") on another one, it's the best way to get confused and end up wasting time on a bug because you wrote querySelector("something") or getElementById("#something") instead.
function changeFont_size (element) {
if(element.options[element.selectedIndex].value != 'select'){
document.getElementById('Title').className = element.options[element.selectedIndex].value;
} else{
document.getElementById('Title').className = '' }
}
function changeAlignment (element) {
if(element.options[element.selectedIndex].value != 'select'){
document.getElementById('container').className = element.options[element.selectedIndex].value;
} else{
document.getElementById('container').className = '' }
}
Try this, Hope it will work

If any textbox on page is changed, call function

I know how to check if one textbox is changed, but what about if any textbox is changed?
Any ideas?
the following code will append onchange event listeners to all input tags on the page with type equal to "text".
var textboxes = document.getElementsByTagName("input");
for(var i = 0; i < textboxes.length; i++) {
if(textboxes[i].type == "text") {
textboxes[i].onchange = function() {alert("changed");};
}
}
With jQuery:
$("input[type=text]").change(function() {
// put your code here
});
EDIT:
If you are new to jQuery or don't know about it, it's a JavaScript framework. Click here to learn about it's change() function.
Generally, you have all your textboxes in one div. Use event bubbling:
// Add an event handler on your whole div
document.getElementById('div-with-your-checkboxes').onchange = function(e) {
// Cross browser check
var evt = e || window.event
// Get the element that triggered the event
var target = evt.target || evt.srcElement
// Check if it is an INPUT element
if (target.tagName === 'INPUT') {
// Your code in here.
}
}
This way, you add only one event which will check every onchange events in your div. Just a simple check and you're done.
This is way more efficient than adding an event handler for every input element.
PS: the jQuery way would be like this:
$('#div-with-your-checkboxes').change(function(e) {
if ($(e.target).tagName === 'INPUT') {
// Your code in here.
}
})
As you can see, jQuery is not really needed for this simple task :-).
You could use some jQuery.
Give the textbox's a class, e.g. class="onchange" then add some jQuery
$(function(){
$('.onchange').change(function(){
// your code in here.
});
});
That way, any textbox with the class onchange will raise the jQuery change event.
Loop over document.getElemenetsByTagName("input"). For each element, verify that type == "text" and, if so, attach an event listener.
JQuery does this in a line: $("input[type=text]").on("change", function() { ... })
If you want to do this for text boxes created dynamically after load time, use $("input[type=text]").live("change", function() { ... })

jQuery, discover what a dom object's class are

I have a .click() on several buttons. Each .click() calls a function. The function needs to know which button called it so that it can show or hide different content and change the styles of the other buttons. The function has an event object passed to it.
Is there a way I can get the current class that the event object has?
$('myButton').click(function() {
var className = this.className; // This will give you the whole class string of the clicked element
var hasClass = $(this).hasClass('myClass'); // This will tell you (true or false) whether the clicked element has class 'myClass'
});
You can get the class with .className or .attr("class"), though what you probably want is to have this refer to the button, for example:
$(".selector").click(myFunction);
function myFunction() {
//this == button that was clicked
var c = this.className;
}
Or an inline function:
$(".selector").click(function () {
var c = this.className;
});
As long as you are passing this to a function (though depending how you are doing this, some code would be nice!), if you pass e as the first parameter in the function then you can use e.target.className to get the class, or, with jQuery $(e.target).attr('class');
Couldn't you make different functions for the different .click() calls?

Javascript + jQuery, click handler returning false to stop browser from following link

I'm trying to stop the browser from following certain links, rather I want to unhide some Divs when they are clicked.
I'm having trouble just getting the links to not be followed though.
Here's what I have:
var titles = $('a.highlight');
jquery.each(titles, function(){
this.click(function(){
return false;
});
});
It seems like the click handler is not being assigned. What am I missing?
Try
this.click(function(e){ e.preventDefault(); }
Actually, it looks like you might need to use the jQuery constructor on this:
$(this).click(function(){ return false; }
You could also try using parameters on the each function instead of using this:
jQuery.each( titles, function(index, elem) { $(elem).click( function() { return false; } ) } );
Personally, I would just do titles.each( ... though. In that instance you can use this to bind the click handler. I am not sure off the top of my head what this binds to with jQuery.each
Or just calling click on titles:
titles.click( function() { return false; } )
That will bind click to every element in titles. You don't need to loop through them.
You can compress that jquery a bit:
$('a.highlight').click(function() { return false; });
You should also make sure that:
There are no other click handlers registered for those elements later on.
The code you have is attaching after the elements have loaded. If they're not completely loaded, they won't be found in the $('a.highlight') selector. The easiest way to do this is to put your code in a $(document).ready(function() { *** code here *** }); block.
Edit: As per other responses - the problem was that this represents a DOM object, while $(this) is a jquery object. To use the .click function to attach a handler, you need a jquery object.
In short, using this inside the each loop won't work with what you're trying to do. You'll need to get a jquery representation by using $(this) instead.

Categories

Resources