jquery for regexp doesnt work - javascript

i use a jquery for a input box to validate content of that
i person who has worked before me make a file that name is comoon.js and that file support all another files.but when i write this code on (document).ready(function() like this
$(document).ready(function()
{
$('#validate').keyup(function(){
var i = $('input');
(/http:\/\//).test(i.val()) && i.val(i.val().replace('http://',''));
});
});
and i have input box like this
<input type="text" id="validate" class="right" name="linkurl" maxlength="150" size="130"/>
but it doesnt work on this button what should i do and what is the problem and i know that js file loaded of all pages ...

Assuming you have more than one input on your page the problem is this line:
var i = $('input');
...which sets i to a jQuery object containing all inputs on the page. Try instead:
var i = $(this);
...which will set i to a jQuery object containing just the element the event occurred on.
(Your code works when there is only one input.)
If the input in question is created dynamically after page load you'll have a second issue: you can't bind an event handler to an element that doesn't exist yet, but you can use a delegated event handler:
$(document).ready(function()
{
$(document).on("keyup", '#validate', function(){
var i = $(this);
(/http:\/\//).test(i.val()) && i.val(i.val().replace('http://',''));
});
});
Where ideally you'd replace document in $(document).on("keyup", '#validate', ... with the closest ancestor of "#validate" that exists on page load. If you're using a version of jQuery less than 1.7 use .delegate() instead of .on() (see the jQuery API doco for more info).

Related

How do I connect a textbox to jquery events dynamically?

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.

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.

Passing 'this' as parameter in JavaScript

I have the following code:
HTML:
<label id="copyAddress" class="copyAddress" onclick="CopyAddress(this);">
Copy Address
</label>
JS:
function CopyAddress(copyAddressLink) {
PopulateTarget(copyAddressLink);
}
function PopulateTarget(link) {
var targetGroup = $(link).closest('someClass');
}
In PopulateTarget function 'link' variable is undefined, while in CopyAddress it has values as is should.
What can cause this problem? Is there some restriction for passing parameters in Java Script? How this should behave? If you need more code to post please tell me.
Since you are anyhow using jQuery, why are you using obtrusive Javascript?
Use this instead:
HTML:
<label id="copyAddress" class="copyAddress">Copy Address</label>
Javascript:
$(document).ready(function(){
$('#copyAddress').click(function(){
var targetGroup = $(this).closest('.someClass');
});
});
You're missing a dot on "someClass", it should be ".someClass".
Maybe your code will work after you fix that. However: since you're using jQuery (it seems you are), you should attach the click handler the jQuery way, instead of inline on the HTML. This means:
$(document).ready(function(){
$('#copyAddress').click(CopyAddress);
})
function CopyAddress() {
PopulateTarget(this);
}
function PopulateTarget(link) {
var targetGroup = $(link).closest('someClass');
}
You should not intermix your HTML and JS. You should instead attach your JS handlers programmatically in your JS code:
<!-- note: no onclick in this html -->
<label id="copyAddress" class="copyAddress">Copy Address</label>
// Wait until the page is loaded before starting to look for elements
$(function(){
// Assuming jQuery 1.7
$('#copyAddress').on('click',copyAddress);
// …alternatively, for older jQuery
$('#copyAddress').click(copyAddress);
function copyAddress(evt){
// The 'target' property of the event object passed in is the object
// upon which the event was first triggered.
PopulateTarget(evt.target);
}
});
In the case of the above, you could just use this instead of evt.target, since you bound the event directly on that object. However, this becomes more powerful if you have a variety of items on the page that perform this function. You can attach the event handler once to some parent object, and then ask—during the callback—which element was clicked on. That would look like:
// Watch for any element with a copyAddress class to be clicked on,
// even if they are added after this code has run
$(document.body).on('click','.copyAddress',function(evt){
var target = evt.target;
console.log("You clicked on",target);
});
As it seems you are using jQuery:
You can use jQuery.proxy to bind this to a specific value. It is used like this:
jQuery.proxy(function () { console.log(this); }, this);

Javascript doesn't work on elements added by jquery's load(), prepend(), or append() functions

I have a comment system where a user submits a comment, the comment is processed, then the HTML for the comment is returned. jquery then adds that retrieved HTML to the comment system. that whole system works, but the comment buttons that requir javascript do not work unless I refresh the page. How do make my javascript work on elements added through load, prepend, or append?
Not sure if my question is clear, but here's the javascript I have:
$(function () {
$(".replyform").submit( function (event) {
event.preventDefault();
id = $(this).attr("id").split('_')[1];
text = $('textarea#text_'+id).val();
$.post( "/api/add/comment/", {_csrf: _csrf, id: id, text: text, a: a},
function (data) {
$('#commentreplies_'+id).prepend(data);
$('#replyform_' + id).hide();
});
});
});
I then have elements such as "reply" for each comment that have functions in an external javascript that do not work unless I refresh the page. Hopefully that made sense.
Use jQuery live() (it is deprecated, see on()) function
jQuery has a live method to allow elements that are added on the page after loading to be able to have events already bound by jQuery. You can bind your events using live method as described here.
A second solution, and probably a more efficient one, would be using delegate method to handle events by existing containers and delegating them to the elements inside that container. You can read more about delegate here.
An example solution using live method is as follows assuming you have buttons with class 'reply' in your response data:
$(".reply").live('click', function(event) {
event.preventDefault();
id = $(this).attr("id").split('_')[1];
text = $('textarea#text_'+id).val();
// post won't work since url is missing, but that code remains the same.
// Assuming you get a response like this
// <div><input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" /></div>
// And if you append this to your document
var data = $('<div></div>').html('<input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" />');
$('#commentreplies_'+id).prepend();
$('#reply_' + id).hide();
});
There are few different approaches to this
1) Explicitly init the button inside returned HTML on AJAX success
2) Setup global handler for your button type using jQuery live() function (replaced by on() in 1.7)
3) define button handler right in the markup
Which one do you pick is really up to your specific task.

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