Using an undeclared attribute for jquery event - javascript

This code is used to pop up a set of checkboxes that is generated when the radiobox with the value of Up is selected.
// Experiment
$("input[name='production-level']").on('change', function() {
var production = $(this).val();
var result = '';
if(production == 'Up') {
result = '<p class="question">Reasons why it is '+ production +'. Click as many as apply.</p>'
+ '<input type="checkbox" name="production-rsn[]" value="Increase in demand" required>Increase in demand <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="Expected increase in demand">Expected increase in demand <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="Fullfillment of past orders">Fulfillment of past orders <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="Increased marketing activity">Increased marketing activity <br/>'
+ '<input type="checkbox" name="production-rsn[]" value="other" />Other';
}
$('#production').html(result);
});
And this code is used to pop up a textbox when the checkbox included in the generated code by the above function with value="other" is checked/ticked. The problem is it won't append!
$("input[name='production-rsn[]']").on('change', function () {
var result = '';
//check if the selected option is others
if (this.value === "other") {
result = '<input id="productionOther" maxlength="30" minlength="3" name="production-other" type="text"/>';
}
$('#production').append(result);
});
The problem is the textbox won't append! Any ideas?

As you are creating elements dynamically you need to use Event Delegation. You have to use .on() using delegated-events approach.
i.e.
$(document).on(event, selector, callback_function)
Example
$('#production').on('change', "input[name='production-rsn[]']", function(){
//Your code
});
In place of document you should use closest static container. In your case its '#production'
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Since your input elements have been added dynamically to the DOM, all the events will not be available for these newly created input until you attach those events to them, you can achieve it using event delegation:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all children matching a selector,
whether those children exist now or are added in the future.
$('#production').on('change', "input[name='production-rsn[]']", function () {
var result = '';
//check if the selected option is others
if (this.value === "other") {
result = '<input id="productionOther" maxlength="30" minlength="3" name="production-other" type="text"/>';
}
$('#production').append(result);
});

Related

How to apply validation to cloned elements in Jquery?

There is a textbox with label; having validation of isnumeric.
Money: <input type="text" id="dollar" name="dollar" data-require-numeric="true" value="">
//Textbox with id dollar0
At run time, I have created clone of above; by clicking on button named add; and this created another textbox with different id and other attributes same; say.
Money: <input type="text" id="dollar1" name="dollar1" data-require-numeric="true" value="">
//Cloned textbox; cloned by clicking on a button named clone
On both textboxes data-require-numeric is true.
Issue: For default textbox the JQuery validation is getting executed. But for new clone; JQuery is not running.
Following is jquery:
var economy= {
init: function () {
$('input[type="text"][data-require-numeric]').on("change keyup paste", function () {
check isnumeric; if yes then border red
});
}};
$(economy.init);
How to resolve this?
Try this : You need to register click event handler using .on() in following way where registering the click handler for document which will delegate the event to 'input[type="text"][data-require-numeric]'. This way you can handle events for dynamically added elements.
var economy= {
init: function () {
$(document).on("change keyup paste",'input[type="text"][data-require-numeric]',
function () {
check isnumeric; if yes then border red
});
}};
$(economy.init);
to bind change event on dynamic dom elements . use class reference instead of id . And bind the event to its parent like,
$(document).ready(function(){
$(".parent").on("keyup",".dynamicdom",function(e){
value = $(e.target).val()
//then do your validation here. and you can attach multiple events to it
})
})
<div class="parent">
<input type="text" class="dynamicdom" >
<input type="text" class="dynamicdom" >
</div>

Document not detecting input value

I've had this problem for awhile now and I can't seem to fix it no matter what I do.
Basically, my input is not retrieving the value that the user types in the input for some reason..
Here is my code:
$('#aid').one('click', function () {
$('.prompt').prepend('<tr class="task"><td class="cell-icon"></td>' +
'<td class="cell-title"><div>User\'s Object: <input id="inputObject" type="text" style="margin-top: 2px;margin-left:2px"></input> Amount: <input id="inputAmount"' +
'type="text" style="margin-top:2px;margin-left:2px; padding-right: 0px"></input></div></td>' +
'<td class="cell-status hidden-phone hidden-tablet"><a class="btn btn-success" style="margin-top:3px">Submit</a></td>' +
'<td class="cell-time align-right">Just Now</td></div>' +
'</tr>');
});
$('.btn').click(function () {
console.log("click");
var input = document.getElementById('inputObject').value;
console.log(input);
});
Everything works fine including both clicks, but for some reason it just won't display the input value to the console.
I've also tried: $('#inputObject').val(); but that didn't work either.
I really hope that someone can help me here!
Another method: use delegate.
$('body').delegate('.btn', "click", function() {
var inp = document.getElementById("inputObject").value;
console.log(inp);
});
Explanation from http://www.w3schools.com/jquery/event_delegate.asp:
The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur.
Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).
You are creating your HTML code dynamically so try using:
$(document).on("click",".btn", function(){
do stuff here...
});

jQuery not working on a jQuery generated HTML tag

I generated multiple li in a string to have a dynamic display of a user list (connected or not).
At the end of the list, I added a li that's the button to disconnect.
Problem is, if I add it in my original code by default, without generating it, the Ajax function works fine.
If I generate it, it doesn't even apply the preventDefault().
Why is that, and how to fix this issue ?
function displayUsers() {
$.ajax({
url: 'getUsers.php',
dataType: 'json'
}).done(function (aUsers) {
if (aUsers != null) {
var sUserList = '';
$.each(aUsers, function (key, oUser) {
sUserList += '<li><span class="glyphicon glyphicon-ok" style="color: springgreen;"></span>' + oUser.nickname + '</li>';
});
sUserList += '<li class="divider"></li>';
sUserList += '<li class="disconnect"><span class="glyphicon glyphicon-off"></span>Sign Out</li>';
$('ul.dropdown-menu').html(sUserList);
} else {
var sNoConnectionMessage = '<li><span class="glyphicon glyphicon-remove-sign" style="color: crimson;"></span>Aucune connexion en cours.</li>';
sNoConnectionMessage += '<li class="divider"></li>';
sNoConnectionMessage += '<li class="disconnect"><span class="glyphicon glyphicon-off"></span>Sign Out</li>';
$('ul.dropdown-menu').html(sNoConnectionMessage);
}
});
}
setInterval(displayUsers, 1000);
$('li.disconnect a').on('click', function (event) {
event.preventDefault();
$.ajax({
url: 'logoff.php'
}).done(function () {
$('div.LoginChat').removeClass('hide');
$('div.WriteMessage').addClass('hide');
})
});
Please guide me the correct way to achieve my objective.
Event handlers are attached to elements, not to selectors.
When you do this:
$('li.disconnect a').on('click', function (event) {
jQuery will identify matching elements for 'li.disconnect a' once, and only once, at the time this line of code executes. Any matching elements added to the DOM afterward will not have been identified. In order to do that, you need to attach the click handler to a common parent element (which doesn't change during the life of the DOM) and use the overload of .on() which filters events from child elements. Something like this:
$(document).on('click', 'li.disconnect a', function (event) {
This will attach the handler to the document element (though any common parent element will work) instead of the identified elements. As events "bubble up" through the DOM they will eventually reach that parent element. The second selector in the .on() function then filters those child elements to respond only to click events which originated from an identified element.
I've written more on the subject here.
Use Event Delegation and delegate the click handler to something that doesn't get regenerated, such as the document:
$(document).on('click', 'li.disconnect a' function (event) {
...
});
The issue is if you don't delegate to something higher, the event handler is lost when you destroy the element.

preventDefault not working on anchor

I'm trying to log the click on an anchor that's being generated asynchronously.
The asynchronous call - which works perfectly fine - looks like this:
$("#txt_search").keyup(function() {
var search = $("#txt_search").val();
if (search.length > 0)
{
$.ajax({
type: "post",
url: "<?php echo site_url ('members/searchmember') ;?>",
data:'search=' + search,
success: function(msg){
$('#search_results').html("");
var obj = JSON.parse(msg);
if (obj.length > 0)
{
try
{
var items=[];
$.each(obj, function(i,val){
items.push($('<li class="search_result" />').html(
'<img src="<?php echo base_url(); ?>' + val.userImage + ' " /><a class="user_name" href="" rel="' + val.userId + '">'
+ val.userFirstName + ' ' + val.userLastName
+ ' (' + val.userEmail + ')</a>'
)
);
});
$('#search_results').append.apply($('#search_results'), items);
}
catch(e)
{
alert(e);
}
}
else
{
$('#search_results').html($('<li/>').text('This user does not have an account yet'));
}
},
error: function(){
alert('The connection is lost');
}
});
}
});
The anchor I want to get to is <a class="user_name" href="" rel="' + val.userId + '">' + val.userFirstName + ' ' + val.userLastName + ' (' + val.userEmail + ')</a>'
I detect the click on these anchors with this function:
// click op search results
$("a.user_name").on('click', function(e) {
e.preventDefault();
});
The problem seems to be that the preventDefault is not doing anything... I've looked at most of the questions involving this problem on Stackoverflow and checked jQuery's own documentation on the topic, but I can't seem to find what's wrong. I've tried adding a async: false statement to the AJAX-call, because perhaps the asynchronous call might be the problem, but that didn't fix it.
Event does not bind with dynamically added element unless you delegate it to parent element or document using on(). You have to use different form of on for event delegation.
$(document).on('click', 'a.user_name', function(e) {
e.preventDefault();
});
delegated events
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page. Or, use delegated events to attach an event
handler, as described next.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to avoid the need to
frequently attach and remove event handlers, Reference
The .on() syntax you showed will only bind handlers to elements that match the selector at that moment - not to elements added in the future. Try this instead:
$("#search_results").on("click", "a.user_name", function(e) {
e.preventDefault();
});
This binds a handler to the parent element, and then when a click occurs jQuery only calls your callback function if the actual target element matches the selector in .on()'s second parameter at the time of the click. So it works for dynamically added elements (as long as the parent exists at the time the above runs).
This should work for you -
$('.search_result').on('click', 'a.user_name', function(){
// your code here
// code
return false;
});
try this
$("a.user_name").on('click', function(e) {
return false;
});
or
$(document).on('click', 'a.user_name', function(e) {
e.preventDefault();
});
Difference between .on() functions calls
May be your a href linked with other listeners too. Check with event.preventDefault
event.stopImmediatePropagation();
together.
You can check this site for more info
https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/
I had this problem too, and it turned out my selector was wrong.

jquery class selector only registering events on first element of class

im currently working on a form field highlighter in jquery and so far it works except it only works on the first line of the form and the rest of the fields do not register my focus events so that i may apply focus formatting
i am currently using the following jquery code
var debug = false;
$(function(){
$(".email-form tbody:last").AddFormLineToTable();
$("#do-add-row").click(function () {
if(debug)
{
alert("serialize click eventhandler fired");
}
$(".email-form tbody:last").AddFormLineToTable();
});
$(".does-focus-highlight").focusin(function(e){
$(e.target).addClass("focus-highlight");
if(debug){alert('field did focus');}
});
$(".does-focus-highlight").focusout(function(e){
$(e.target).removeClass("focus-highlight");
if(debug){alert('field did blur');}
});
$("#do-serialize").click(function(){
if(debug)
{
alert("serialize click eventhandler fired");
}
var jsn = $("#contact-form").serializeArray();
$("#serialize-target").val(JSON.stringify(jsn,null,2));
});
});
is there something im missing to catch these additional events
the form fields that are not firing are being generated dunamically as well if that makes a difference as well
which are being generated as follows
var lineCount = 0;
jQuery.fn.AddFormLineToTable = function() {
var o = $(this[0]);
o.append('<tr id="contact-'+lineCount+'">' +
'<td>Name: <input class="does-focus-highlight" id="contact-name-'+lineCount+'" name="contact-name-'+lineCount+'" type="text" required="required" /></td>' +
'<td>Email: <input class="does-focus-highlight" id="contact-email-'+lineCount+'" name="contact-email-'+lineCount+'" type="email" required="required" /></td>' +
'</tr>');
lineCount++;
};
.click() binds events only to elements that are existing at the time of calling .click(). If you want the events to be handled for elements that are created later on, use .on() or .live(), depending on the version of jQuery you are using. Read the very helpful info here.

Categories

Resources