jQuery does not recognize cloned inputs - javascript

JQuery does not recognize cloned objects, I have a Jquery code which clones a div and changes the name of the inputs inside it, the thing is that I need to perform certain functions with those cloned inputs and I am checking that jQuery does not recognize them, like If they did not exist, I leave you here the code, thanks in advance.
Jquery code cloning and ID renaming (work perfect code)
$('#div-materiales-{{$num}}').clone().appendTo('#material-form').prop('id', 'div-materiales-' + i);
$('#div-materiales-' + i).find('input.total').attr('id', "total-" + i);
$('#div-materiales-' + i).find('input.total').attr('name', "total-" + i);
i++;
Code that should show an alert when clicking the total input-1
$(document).ready(function () {
$("#total-1").click(function() {
alert('funciona');
});
});
PS: I understand that it is the cloning that gives me problems because the initial total is total-0 and the code above but with total-0 the alert jumps but as I have commented here the total-1 (which would be the cloning) does not I get the alert to jump.

Use "on" for dynamic bindings
$("body").on('click','#total-1',function(){ // Previously i had issue here for dynamic bindings
console.log('clicked')
});
$("body").on('keyup','#total-1',function(){
console.log('key up')
});

You need to use on, and attach the event to an element that always exists:
$('body').on('click', '#total-1', function() {

Related

Checkbox and click event handling

I'm trying to set a textbox to 'readonly', add a class, and put a text into the textbox at that moment when I check the checkbox. Moreover, I'm also trying to remove 'readonly' attribute from the textbox, add a class, and delete text in the textbox.
I have
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
This code doesn't work for me.
Thanks,
Phillip
Thanks everyone for answers.
According to your comments and answers, I've changed my code but it's still not working.
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').prop('readonly', true);
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text('disabled');
}
else {
$('#TextBoxSectionCode').prop('readonly', false);
$('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
$('#TextBoxSectionCode').text('');
}
});
I'm using chrome browser to run this code, and using developer tools in chrome and put a break point at the code above to see what's happening in the jquery. However, when I click the check box to check/uncheck, nothing happens there.
document.getElementById('TextBoxSectionName').val this is wrong. You really should cache your jQuery object so it's not navigating the DOM over and over. Then you mix in native JS and .val is not a DOM property or method, nor is it a jQuery property, it should be .value for a DOM object or .val() for a jQuery object.
Obligatory explanation by #Archy Wilhes:
"Just to clarify; when #SterlingArcher says caching the jQuery object,
she/he means doing something like var obj = $('#TextBoxSectionCode')
then calling the functions using the variable like this:
obj.attr(...); obj.addClass(...). Every time you do a $(something) you
are calling a function in jQuery that looks for the DOM."
since everytime you are adding the class the element is going to end up having both the two classes. Consider removing the other class before adding one. For example,
$(selector).removeClass('disabled').addClass('enabled')
Try with change event instead of click:
$('#CheckBoxSectionCode').change(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
You could do the following way.
//Cache reference to DOM as DOM scan is expensive!
var textBox = $('#TextBoxSectionCode');
$('#CheckBoxSectionCode').click(function () {
//Use prop as opposed to attr
textBox.prop("readOnly", false).removeClass('disabled').addClass('abled').text("");
if ($(this).is(':checked')) {
textBox.prop("readOnly", true).removeClass('abled').addClass('disabled').text($("#TextBoxSectionName").val());
}
});

Dojo delegate to DOM Element's ID

I am working with a JSP that dynamically includes DOM elements such as a buttons based on a user's privilege or other factors.
Now, in my JS, I was using:
dojo.connect(dojo.byId('dispatchBtn'), 'onclick', function() { //logic }
The problem is, if the 'dispatchBtn' doesn't exist because it was stripped based on the user's privilege, the JS just calls all the contents of the "//logic" anyway.
I tried to change this call to:
eventView.delegate(dojo.byId('dispatchBtn'), 'onclick', function() { //logic }
But that doesn't seem to work at all, even for buttons that DO exist. What's the best way to do this without explicitly testing if the button exists. I do not want to change the markup on any of these button elements, no additional classes, just want to reference them by ID.
You can do like jquery live does and bind on the document level.
require(["dojo/on", "dojo/query"], function(on){
on(document, "#dispatchBtn:click", function(evt){
alert("Clicked on node " + this.id);
});
});
Fiddle:http://jsfiddle.net/theinnkeeper/NTn6g/
Why are you adverse to checking if the button exists? That makes the most sense
var btn = dojo.byId("dispatchBtn");
if(btn) {
on(btn, 'onclick', function() {});
}

Bind different events to multiple HTML elements, but perform one function

I have a button, a div and a select combo-box
I want to execute a particular function on click of the button, on mouseenter in div and onchange and blur of the combobox
I do this right now
$("#divID").bind('mouseenter',function(){
// do my stuff
})
$("#comboID").bind('blur change',function(){
// do my stuff
})
$("#buttonID").bind('click',function(){
// do my stuff
})
I do the same stuff everytime. I want to combine all the events together to avoid duplication is there a way to bind each one of the elements with specific events in one statement
I know I can write the code in a separate function and call it each time(solves duplication).
But I want to know can this be done without a separate function and only jQuery
You have seprate event with seprate selectors so one selector or event is not enough, you can map ids and events. I think jquery could not help much to make it single statment.
Live Demo
arrIDs = ['divID','comboID','buttonID'];
arrEvents = ['mouseenter','blur change','click'];
for(idx=0; idx < arrIDs.length; idx++)
$("#" + arrIDs[idx] ).bind(arrEvents[idx], yourFunction);
function yourFunction(event)
{
alert("yourFunction call by " + event.target.id);
}
Not in one statement, since you want to attach different events to different elements. But you can declare a single callback-function that you call for all events.
var callback = function () {
// do my stuff
};
$("#divID").bind('mouseenter', callback);
$("#comboID").bind('blur change', callback);
$("#buttonID").bind('click', callback);
If you don't use jquery you can always set set the other events to be equal to the first.. but good practice will be creating a separate function

JQuery - What can I do to make this work?

http://jsfiddle.net/piezack/X8D4M/5/
I need the change created by clicking the button to be detected. At the moment you have to click inside the field and then outside for it to detect any change.
Thanks guys.
The code for the button CANNOT be altered. Good tries so far though.
Was overcomplicating things. Answer http://jsfiddle.net/piezack/X8D4M/56/
Example using trigger:
//waits till the document is ready
$(document).ready(function() {
$('button.butter').click(function() {
var $form6 = $('#FormCustomObject6Name');
$form6.val('Text has changed');
$form6.trigger('change')
});
$('#FormCustomObject6Name').change(function() {
var x = $('#FormCustomObject6Id').val();
$("a").filter(function() {
return this.href = 'http://www.msn.com'
}).attr('href', 'http://www.google.com/search?q=' + x);
alert(x);
});
});
i think that jmar has the right idea...if i understand correctly you want to be able to type whatever in the box and without clicking out of it to have the button change it to the text has changed.
i dont know if that alert is really necessary, but you can do this if the alert is not needed:
http://jsfiddle.net/X8D4M/24/
To trigger the change event simply add a .trigger after setting the value.
Also, you're selector for the link wasn't working so I just changed it to #link.
http://jsfiddle.net/X8D4M/22/

Problem passing integer variable into click event in javascript and jquery

This is probably something simple but it's driving me nuts.
I'm making some pagination using jquery and a while loop which has a variable called "pageNum" that updates at the end of the loop and represents the page being written out. Obviously pageNum is added to at the end of each iteration. Fine.
Here's the code that's giving me a hard time:
$('#page' + pageNum).click(function(){
alert(pageNum);
});
So that id works properly and will assign a click even to (for example) a span with an id of page3 if 3 is the current pageNum. The problem is, when I click on that span, the pageNum that is alerted is always the last value of pageNum that was set in the loop. So if there's 8 pages, it will always alert 8. So, I figured it must be always pulling in the current value, so I tried passing pageNum in like this:
$('#page' + pageNum).click(function(pageNum){
alert(pageNum);
});
But now the alert shows [Object object].
I've tried creating variables inside and out of the click event and assigning them the value of pageNum and nothing seems to work.
This must be something really stupid, can someone please help me out? I need to have the current pageNum usable within that click event.
Thanks in advance for your help!.
Instead of referencing the pageNum variable directly, just get it dynamically from each link, for example:
$('#page' + pageNum).click(function(){
alert(this.id.replace('page',''));
});
Or give them a class, say .pageLink and bind them all at once, like this:
$('.pageLink').click(function(){
alert(this.id.replace('page',''));
});
Currently you're referencing a single pageNum variable from your loop which changes and ends up whatever it was at the end of the loop. You either need to pass it in a closure or ignore it altogether, like above, or use event data passed to .bind(), like this:
$('#page' + pageNum).bind({id: pageNum}, 'click', function(e) {
alert(e.data.id);
});
The third option actually works great, Nick just had the parameters mixed around - I recently needed to use bind in this fashion for a plugin im creating and it works awesome! See below for fix:
$('#page' + pageNum).bind('click', {id: pageNum}, function(e) {
alert(e.data.id);
});
jQuery documentation cleared it up for me; http://api.jquery.com/bind/
.bind( eventType, [ eventData ], handler(eventObject) )
$('#page' + pageNum).click(function()
{
var pageNum = $( this ).attr( 'id' ).match(/page([0-9]*)/)[1];
alert( pageNum );
});

Categories