How do I connect a textbox to jquery events dynamically? - javascript

I have an application that uses jquery when editing date fields. It works on all fields that have the css class "date". I am reading some HTML code from the server into a DIV that functions as a pop up window. The HTML code includes several date fields and I want to have jquery manage those fields, too. The page has code pasted below in the head element and jquery automatically attaches to the appropriate fields. I need to add fields to jquery when the pop up appears and remove them when the pop up closes. When searching for an answer I could only find where jquery creates a textbox, but not attach to an existent textbox.
<script src="Include/jquery-latest.js" type="text/javascript"></script>
<script src="Include/jquery.maskedinput.js" type="text/javascript"></script>
<script type='text/javascript'>
$(function () {
// Define your mask (using 9 to denote any digit)
$('.phone').mask('(999)999-9999');
});
$(document).ready(function () {
$('.phone').change(function () {
var validnum = $(this).val().match(/^([01]?[0-9]|[0-9]|[0-9])[0-9]|[0-9]|[0-9]-[0-9]|[0-9]|[0-9]|[0-9]$/);
if (!validnum) {
$(this).val('').focus().css('background', '#fdd');
alert('Please enter a valid Phone Number (999)999-9999.');
} else {
$(this).css('background', 'transparent');
}
});
});
$(function () {
// Define your mask (using 9 to denote any digit)
$('.date').mask('99/99/9999');
});
$(document).ready(function () {
$('.date').change(function () {
var validnum = $(this).val().match(/^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/);
if (!validnum) {
$(this).val('').focus().css('background', '#fdd');
alert('Please enter a valid Date mm/dd/yyyy.');
} else {
$(this).css('background', 'transparent');
}
});
});
</script>

Why doesn't your solution work?
By using $('.date').change(... jQuery attaches event listeners to all elements present in the DOM the moment you execute this function. As your modal gets added in later, it won't have received a listener.
Solution: $(document).on('change', '.date', function () { ...
By using this, you attach the event listener to the document root, so every time anything in the document changes, jQuery checks, if the changed element matches the selector you've provided as the second param (in this case .date). So all elements, even those added later to the page will react to changes.
BUT: As I said, you attach a listener to the document. As jQuery uses a shadow-DOM in the background it won't cost you much performance, but if you build a big application with many of these listeners, you might run into performance issues at some point. In this case you'd better add the listeners specifically to the element you just added.

Since the mask and event functions are enclosed, I moved them to the routine that creates the pop up and that resolves the issue, causing them to be called again each time. I placed a date test textbox on the form and displayed properties. Each time there was only one jquery property present, so it appears everything was removed and rewritten each time.

Related

Running script after div added

Im using a plugin (Event Organiser Pro) that dynamically creates a div based on the input of a number field - basically it creates a duplicates the form fields depending on the number you enter in the input field.
I need to run some jQuery which is based on those form fields, but obviously cant run it until the div has been created.
How can i run the script once the div has been created? Is it possible to run script when div id has been created? Or something similar?
Yes, you can delegate the DOMNodeInserted event to the body.
function createDiv() {
$('<div />').addClass('test').appendTo($('body'));
}
$('body').on('DOMNodeInserted', '.test',function() {
alert('Created element .test');
})
$("button").on('click', function() {
createDiv();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create</button>
In the example above the click on the button simulates your other script creating the div.
To rewrite the code to work with your setup you can strip the click part out and delegate the event listener to your id:
$('body').on('DOMNodeInserted', '#your_element',function() {
yourFunction();
// call a function here or add your code here directly
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: This example won't work here because the element with that ID does not exist and neither does the yourFunction() function.

Simple javascript to update a textbox when a button is hit?

I have a simple form that I'm playing around with and I'm trying to update a textbox value when a command button is clicked. The command button is called btnVerifyLocation and the textbox is called txtGeoLocation. I've attempted to do this in Javascript with the following:
The code I have is as follows:
<script type="text/javascript" id="testing">
$("btnVerifyLocation").click(function ()
{
$("input[name*='txtGeoLocation']").val("testing");
});
</script>
However when I click the button nothing happens.
A) You're missing a # in 'btnVerifyLocation' (I'm assuming that's its ID, otherwise if it's a class then use '.btnVerifyLocation'
B) Second, this should be in a $(document).ready(), otherwise you are trying to bind a click handler to a DOM element that hasn't yet been rendered.
Code should be as follows:
$(document).ready(function() {
$('#btnVerifyLocation').click(function(e) {
e.preventDefault(); // In case this is in a form, don't submit the form
// The * says "look for an input with a name LIKE txtGeoLocation,
// not sure if you want that or not
$('input[name*="txtGeoLocation"]').val('testing');
});
});
jQuery’s selector function uses CSS selector syntax, so to identify an object with an ID, you need to prefix the ID with a #:
$("#btnVerifyLocation").click(function () {
$("input[name*='txtGeoLocation']").val("testing");
});
Also just in case: You do have jQuery included, right?

JQuery Event repeating in dynamic content

In a page of a website I'm making, the press of a button imports the contents of a another php page and appends it onto the page. However, that other page contains JQuery, and the click event($( ".ExpandRoleButton").click) repeats itself on previous elements every time I import the content. So if I add 3 elements;
Element 1: Repeats the click event 3 times
Element 2: Repeats the click event 2 times
Element 3: Runs the click event once
$("#AjouterPiece").click(function()
{
$.blockUI({ message: '<img src="images/ChargementGeant.gif"/><br/><h1>Un moment svp.</h1>' });
$.post("wizardincl/piste.php", {newPiste: newPiste}, function(data)
{
$("#wizardPistes").append(data);
$.unblockUI();
$(".divNewPiste").fadeTo(300, 1);
$("#nbExemplaires").attr("max", newPiste);
newPiste++
$( ".ExpandRoleButton").click(function()
{
if ($(this).hasClass('RetractRoleButton'))
{
$(this).find('img').attr('src', 'images/ExpandPetitNoir.png');
var that = $(this);
$(this).parent().parent().parent().parent().next().slideUp(500, function() {
that.parent().parent().parent().parent().css('border-bottom', '1px solid #FF790B');
});
$(this).removeClass('RetractRoleButton');
}
else
{
$(this).parent().parent().parent().parent().css('border-bottom', 'none');
$(this).find('img').attr('src', 'images/ExpandPetitNoirRetour.png');
$(this).parent().parent().parent().parent().next().slideDown(500);
$(this).addClass('RetractRoleButton');
}
});
});
});
Currently, part of the JQuery website seems down and after some search, I can't find anything to solve the problem. Is there any way to keep the code from repeating itself like this?
This is because you are binding the event to multiple event handlers. The first time #AjouterPiece is clicked, all .ExpandRoleButton buttons get binded to an onclick handler.
The next time #AjouterPiece is clicked, it gets binded again.
To prevent this, you must unbind the click handlers using the following code before binding it
$( ".ExpandRoleButton").unbind('click')
You can pass in the event with .click(function(e) {...}) and then call e.stopImmediatePropagation() to fire only the current handler, but that only addresses the symptom, not the real problem.
Edit: make sure you are only binding the new instance of the button by adding a context to your selector, like $('.ExpandRoleButton', data). Since you are matching on a class, that selector will grab all the buttons on the page; the context allows you to select only the one inside your result.
A good practice ( solely to prevent issues like this from occurring, unintended multiple click handlers added ) is to..
$(".selector").off('click').on('click', function...
or
$(".selector").unbind('click')...
$(".selector").bind('click')...

Unable to attach a live event to anchor within div in asp.net

I'm trying to use a simple modification for XOXCO's tagging input jquery plugin that allows you to limit the number of tags entered.
Everything is working correctly except for this part
$('.tag a').live('click', function () {
if ($('.tag').length == 4) {
$('#MainContent_postcontrol_step2_txtKeywords_tag').attr('disabled','false').show();
$('#MainContent_postcontrol_step2_txtKeywords_tag').focus();
$('.warning').remove();
}
});
No matter what I do, the click event is never assigned to a .tag's anchor. If I change it to simply .tag, the event fires when clicking on the div itself. Am I doing this part wrong?
EDIT:
Here is the plugin im using: http://xoxco.com/clickable/jquery-tags-input
And the modification: http://jsfiddle.net/bozdoz/mJdvu/1/
It looks like (= sign typo aside) that
$('#tags_tag').attr('disabled','false').show();
needs to be
$('#tags_tag').show()[0].removeAttribute("disabled");
in the fiddle

Listen for change events in forms: JQuery

I have a form with an id of "wizard" - I only have select elements in this form. This form is in a lightbox using the JQuery plugin fancybox:
I want to know when any of these have been changed using JQuery. How can I do this? I currently have:
$('form#wizard select[name=servers], form#wizard select[name=cores]').change(function() {
var channels = parseInt($('form#wizard select[name=servers]').val(), 10) * parseInt($('form#wizard select[name=cores]').val(), 10);
$('#yellow').val(channels);
});
EDIT - I have the above wrapped in $(document).ready(function() {...}
However, it does not work, it does not even get run. I have put alerts in there and they never show up. The above only works when the above is a div that I have removed the display:none from, strange! So I am looking for a different implementation to get around this as I need that lightbox as it is.
I really need help on this.
Thanks all
The jQuery change function only binds those elements that are present when the domready event fires. If the lightbox plugin you are using is dynamically creating elements, you should be using jQuery's live function to "bind your handler to all current - and future matched elements".
Change this:
$('your selector').change(function() { /* code ... */ });
with this:
$('your selector').live('change', function() { /* code ... */ });

Categories

Resources