make javascript function form specific - javascript

I have some jquery/javascript code that alters some things on document ready and when a form input is changed. How do i make this form specific?
$(function() {
$('input[name="item_price[]"]').live('change', function () {
var tr = $(this).parent().parent();
CalculateData(tr);
});
If my form's id tag is "my_form", how do i make this little snippet occur only if item_price[] in the "my_form" is being changed and not all instances of the item_price[] input?

use the selector code like this $('#my_form input[name="item_price[]"]') instead

Simply add the id selector, #my_form, to your existing selector:
$('#my_form input[name="item_price[]"]').live('change', function () {
var tr = $(this).parent().parent();
CalculateData(tr);
});
Additional Information:
jQuery selector reference: http://api.jquery.com/category/selectors/

add #my_form to the jquery selector
$('#my_form input[name="item_price[]"]').live('change', function () {
var tr = $(this).parent().parent();
CalculateData(tr);
});

You can use delegate in the following way to attach the event handler to the form element. This has the added advantage of jQuery not having to process unrelated events (i.e. ones that originated from outside of the form).
$('form#my_form').delegate('input[name="item_price[]"]', 'click', function() {
...
});

Related

javascript events not working with dynamic content added with json

I'm stuck with a situation where my DOM elements are generated dynamically based on $.getJSON and Javascript functions for this elements are not working. I'll post some general idea on my code because I'm looking just an direction of what should I do in this situation.
site.js contains general features like
$(document).ready(function() {
$('.element').on('click', function() {
$(this).toggleClass('active');
});
$(".slider").slider({
// some slider UI code...
});
});
After that:
$.getJSON('json/questions.json', function (data) {
// generating some DOM elements...
});
I have also tried to wrap all site.js content into function refresh_scripts() and call it after $.getJSON() but nothing seems to be working.
Firstly you need to use a delegated event handler to catch events on dynamically appended elements. Then you can call the .slider() method again within the success handler function to instantiate the plugin on the newly appended content. Try this:
$(document).ready(function(){
$('#parentElement').on('click', '.element', function() {
$(this).toggleClass('active');
});
var sliderOptions = { /* slider options here */ };
$(".slider").slider(sliderOptions);
$.getJSON('json/questions.json', function(data) {
// generating some DOM elements...
$('#parentElement .slider').slider(sliderOptions);
});
});
Instead of calling on directly on the element, call it on a parent that isn't dynamically added and then use the optional selector parameter to narrow it to the element.
$('.parent').on('click', '.element', () => {
// do something
});
The difference between this and:
$('.element').on('click', () => {});
is with $('.element').on(), you're only applying the listener to the elements that are currently in that set. If it's added after, it won't be there.
Applying it to $(.parent), that parent is always there, and will then filter it to all of it's children, regardless when they're added.
the easiest way is to add this after you add/generate your DOM
$('script[src="site.js"]').remove();
$('head').append('<script src="site.js"></script>');
of course your js function that generates DOM needs to be on another file than your site.js

How can I show a DIV by it's attribute value using Jquery

I am working with a Jquery plugin and I would like to trigger the modal (div) by calling it's value instead of calling it's ID name.
So if the attribute value is "554" meaning attrId="554" I will display the modal with the matching "554" attribute. Please keep in mind that the attribute value could be a variable.
My JSFiddle Code Example is here
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('#my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup();
});
});
})(jQuery);
Any help is appreciated. Thanks so much
You can use an attribute equals selector: [attribute="value"]
If your popup div has an attribute like this:
<div id="element_to_pop_up" attrId="554">
<a class="b-close">x</a>
Content of popup
</div>
You can use the following:
var x = '554';
$('div[attrId="' + x + '"]').bPopup();
jsfiddle
Ultimately it needs a unique selector unless you are okay with triggering multiple modals. One way to do it is to use the jQuery each function, and check each div for the matching attribute.
$( "div" ).each(function() {
var criteria = 'example_criteria';
if ($( this ).attr( "attributename" ) == criteria)
{
$(this).bPopup();
}
});

click event not working on hyperlink ajax data

Jquery Click event on table hyperlink does not work for table data that comes from ajax call, yet it works for static data entered.
Fiddle
$("a").click(function (e) {
var txt = $(e.target).text().replace(/\s/g, "%20");
alert(txt);
});
It is not working because you are adding data dynamically.
Use event delegation.
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
Write:
$(".table").on("click","a",function (e) {
var txt = $(e.target).text().replace(/\s/g, "%20");
alert(txt);
});
Updated fiddle here.
Refer this document.
use $(document).on("click", "a", function (e) { instead of $("a").click(function (e) {
use on by jquery framework
it will work nice, if you do in such a way
$(document).on("click","selector",function(ev){
$(this)// your stuff..
});
as jquery doesn't bind events to dynamic content, so you need to parse the DOM again to find your element.

Using .on() and targeting elements with a specific attribute

I understand you can use .on() to attach a single click event to an element and then specify which child elements receive the click. So, for example:
$(this.el).on("click", "span", function () {
alert("Bloop!");
});
I need to be a bit more specific and target selectors with a particular attribute, like this:
$(this.el).on("click", "span[data-placeholder]", function () {
alert("Bloop!");
});
That doesn't seem to work, though. As soon as I add the attribute it stops working. No errors, just doesn't seem to find the elements.
Is that the expected behavior? Is there a way around it?
CLARITY
$(this.el) is just a div that contains a number of elements, some of which are <span data-placeholder="First Name"></span> tags. There could be dozens of those <span> tags and I didn't want that many event listeners, so I thought I'd use .on() to add the click to the parent container.
Here's JSFiddle showing your example working, with both existing <span>s and with newly created ones.
Just to be clear, this will work with your event delegation:
var span = $('<span>Test</span>');
span.attr('data-placeholder', 'test'); // declare as an attribute
$(this.el).append(span);
span.click();
This will not:
var span = $('<span>Test</span>');
span.data('placeholder', 'test'); // declare with .data()
$(this.el).append(span);
span.click();
jQuery's .data() method will read properties from data attributes if declared, but does not store them as attributes on the element when adding data.
Here's another JSFiddle.
try
$("span[data-placeholder]", this.el).on("click", function () {
alert("Bloop!");
});
You can choose to filter your spans
$('span', this.el).filter(function() {
return $(this).hasAttr('data-placeholder');
}).on('click', function() {
//This is for all the spans having data-placeholder
//...
});
Or if the placeholder is set via data api:
$(this.el).filter(function() {
return $(this).data('placeholder') != 'undefined';
}).on('click', function() {
//This is for all the spans having data-placeholder
//...
});
This functions above select those elements specifically, if event delegation on the OP is needed, then you can do the following:
$('span', this.el).on('click', 'span', function() {
if($(this).data('placeholder') != 'undefined') {
alert('bloop');
}
});
add a id to your span and pin point it using # tag

Issue with selectors & .html() in jquery?

The function associated with the selector stops working when I replace it's contents using .html(). Since I cannot post my original code I've created an example to show what I mean...
Jquery
$(document).ready(function () {
$("#pg_display span").click(function () {
var pageno = $(this).attr("id");
alert(pageno);
var data = "<span id='page1'>1</span><span id='page2'> 2</span><span id='page3'> 3</span>";
$("#pg_display").html(data);
});
});
HTML
<div id="pg_display">
<span id="page1">1</span>
<span id="page2">2</span>
<span id="page3">3</span>
</div>
Is there any way to fix this??...Thanks
Not sure I understand you completely, but if you're asking why .click() functions aren't working on spans that are added later, you'll need to use .live(),
$("#someSelector span").live("click", function(){
# do stuff to spans currently existing
# and those that will exist in the future
});
This will add functionality to any element currently on the page, and any element that is later created. It keeps you have having to re-attach handlers when new elements are created.
You have to re-bind the event after you replace the HTML, because the original DOM element will have disappeared. To allow this, you have to create a named function instead of an anonymous function:
function pgClick() {
var pageno = $(this).attr("id");
alert(pageno);
var data="<span id='page1'>1</span><span id='page2'> 2</span><span id='page3'> 3</span>";
$("#pg_display").html(data);
$("#pg_display span").click(pgClick);
}
$(document).ready(function(){
$("#pg_display span").click(pgClick);
});
That's to be expected, since the DOM elements that had your click handler attached have been replaced with new ones.
The easiest remedy is to use 1.3's new "live" events.
In your situation, you can use 'Event delegation' concept and get it to work.
Event delegation uses the fact that an event generated on a element will keep bubbling up to its parent unless there are no more parents. So instead of binding click event to span, you will find the click event on your #pg_display div.
$(document).ready(
function()
{
$("#pg_display").click(
function(ev)
{
//As we are binding click event to the DIV, we need to find out the
//'target' which was clicked.
var target = $(ev.target);
//If it's not span, don't do anything.
if(!target.is('span'))
return;
alert('page #' + ev.target.id);
var data="<span id='page1'>1</span><span id='page2'>2</span><span id='page3'>3</span>";
$("#pg_display").html(data);
}
);
}
);
Working demo: http://jsbin.com/imuye
Code: http://jsbin.com/imuye/edit
The above code has additional advantage that instead of binding 3 event handlers, it only binds one.
Use the $("#pg_display span").live('click', function....) method instead of .click. Live (available in JQuery 1.3.2) will bind to existing and FUTURE matches whereas the click (as well as .bind) function is only being bound to existing objects and not any new ones. You'll also need (maybe?) to separate the data from the function or you will always add new span tags on each click.
http://docs.jquery.com/Events/live#typefn

Categories

Resources