Dynamic selector in .on() method - javascript

I have some form that represents quiz creating page where I want to dynamically add questions and answers to those question. I want to respond on click event on newly created buttons.
Problem is that onClick event is executed only on first button which exists from the beginning.
Here is sample of my code. I have form with id myForm, div with id questioni that encapsulates all stuff regarding i-th question (also button with class new_answer for adding answers to that particular question), variable curr_q (current question I am creating).
$(function () {
$("#myForm").on('click', "#question" + curr_q + " .new_answer", function () {
alert("#question" + curr_q + " .new_answer");
});
});
Here is also fiddle - http://jsfiddle.net/sruzic/8yt9jcqh/ (it is little bit overwhelming but problem is that when you click on existing Create Question then newly created Create Answer button is not responing while 'old' Create Answer alerts that selector is question1 .new_answer which is exactly newly created Create Answer button?!
Thanks in advance.

update your code to this . check demo
$(function () {
var selector = "#question" + curr_q + " .new_question";
$(selector).click(function () {
curr_q++;
alert(curr_q);
total_q++;
$('#myForm').append(generateQuestionSubForm(total_q))
$("#myForm").on('click', "#question" + curr_q + " .new_answer", function () {
alert("#question" + curr_q + " .new_answer");
});
});
});

In addition to changing your event listener, just remove the new_answer class from previous inputs when a new item is created. Something like this should work:
$(function () {
var selector = "#question" + curr_q + " .new_question";
$(selector).click(function () {
curr_q++;
alert(curr_q);
total_q++;
$('.new_answer').removeClass('new_answer');
$('#myForm').append(generateQuestionSubForm(total_q))
});
});
$(function () {
$("#myForm").on('click', ".new_answer", function () {
alert("#question" + curr_q + " .new_answer");
});
});

Related

Select an element after appending it in jquery

I appended an element:
$("#usernames_list").append("<li class='username_item'>" + item.username + "</li>")
Then I tried to select the newly appended element:
$(".username_item").bind('click', function(){
alert("asdas");
})
tried this also:
$(".username_item").click(function(){
alert("asdas);
})
alert function is not working.
How to fix this? All those other answers did not help
Your code should work as is but is not very effective.
Simplest and most effective way would be to keep reference of your created element so you won't have to research it again:
var $container = $("<li class='username_item'>" + item.username + "</li>");
$container.appendTo($("#usernames_list"));
this way you can register your listener easily :
$container.click(function(){
alert("asdas");
})
You can add it this way:
var $container = $("#usernames_list");
var liClick = function() {
alert("ok");
}
$container.on('click', '.username_item', liClick);
And here is example: http://fiddle.jshell.net/scg32rzh/3/

bootstrap accordion how to check which panel is active

I am using Bootstrap's accordion widget to contain several forms i.e. each panel contains one form. When the last panel is selected, the data from the other panels is meant to be posted which will be used to graph the data. However, I am unable to get to the posting part as I cannot figure out which panel is currently selected. I know that this has to do with a class of active or inactive, but I don't think bootstrap's accordion supports that functionality unlike jquery accordion.
I am trying to figure out the first part i.e. check if the user has clicked on the last panel. In my HTML code it has an id of #results. Here's a jsfiddle that demonstrates the issue I am facing. It does not seem to trigger the second alert function when the user clicks on the #results tag, not sure why.
Sample javascript code:
$('#accordion').on('show.bs.collapse', function () {
$('#results').click(function () {
alert("works"); //testing purposes
});
});
Why don't you do?
$('#results').click(function (){
alert("clicked");
});
Just remove the accordion function and you'll get the on click event directly
Is this what you want?
Fiddle: Demo
take this outside the on function
$('#results').click(function (){
alert("clicked");
});
This is an old thread but I wanted to post an answer as the expected result is not suggested.
What you need to do here is to handle the currently selected collapse items with the event handler. If you use the this keyword for this, you can access the values of the selected object (For example only one item in the form).
Here you can get the $(".collapse") element.
You can get the index number of the active item with $(this).parent().index().
Likewise, you can get the id of the active item with $(this).attr('id').
Your jQuery structure would be:
$(".collapse").on('show.bs.collapse', function(){
//0,1,2,etc..
var index = $(this).parent().index();
//collapseOne, collapseTwo, etc..
var id = $(this).attr('id')
//alert('Index: ' + index + '\nItem Id: ' + id );
console.log('Index: ' + index)
console.log('Item Id: ' + id)
if(id === 'collapseFour')
{
var username = $('#username').val();
var email = $('#email').val();
var age = $('#age').val();
//here you can check the data from the form
$("#result").html("<p> UserName: " + username + "</p> <p> EMail: " + email + "</p> <p> Age: " + age + "</p>");
}
});
I've included a working example here for you (jsfiddle).
$('#accordion').on('show.bs.collapse', function (accordion) {
var $activeCard = $(accordion.delegateTarget.children);
});
or
$('#accordion').on('show.bs.collapse', function () {
var $activeCard = $(this.children);
});

Repeatable Blocks

I currently have a bit of JS which will generate buttons based on the data attribute stored in the HTML, which will generate 2 buttons:
Plus Button to add a repeatable block(Will/should only display a plus button if there is only one block)
A minus button to remove the repeatable field(will/should show when there is more than one blocks)
Thing is, I have the buttons working fine, but when I added the event handlers for them to do as I ask, and click on them nothing happens, am not sure why and hopefully you can point me in the right direction.
Regards!
P.S jQuery Code
$('.glyphicon-plus-sign').on("click", function () {
prevInput = $(this).prev('input');
count = $(prevInput).attr('data-count');
countIncremented = count++;
br = '<br/><br/>';
inputElement = '<input type="' + $(prevInput).attr("type") + '" name="' + $(prevInput).attr("name") + countIncremented + '" data-count="' + countIncremented + '"/>';
$(br + inputElement + plusMinusButtons).insertAfter('.' + $(prevInput).attr("name") + ':last');
});
$('.glyphicon-minus-sign').on("click", function () {
prevInput = $(this).prev('input');
$(this).remove(prevInput).remove(this);
});
$("button").click(function () {
console.log("here");
x = $('#form').serializeArray();
$.each(x, function (i, field) {
console.log(field.name + ":" + field.value + " ");
});
I currently have a bit of JS which will generate buttons
Dynamically adding buttons means you have to approach events a little differently. You need to do the following:
$('body').on("click", '.glyphicon-minus-sign', function () {
...
}
$('body').on("click", '.glyphicon-plus-sign', function () {
...
}
Essentially, you are now listening to clicks on the body element, instead of the actual buttons (which might not actually exist yet). Any other statically created buttons aren't affected.

Attempting to loop and print an element in jQuery

I am attempting to loop through a dynamic element and then print it with jquery,
Heres the code i use
$('.recipe-steps #addNewStep').on('click', function () {
var s = $('.recipe-steps .step').size() + 1;
$('<div class="step pure-u-1-1"><textarea id="step" name="step_detail[]" class="pure-u-1" placeholder="Step ' + s + '"></textarea>×</div>').appendTo($('.recipe-steps .steps'));
return false;
});
$(document).on('click', '.step .remove', function () {
$(this).parents('.step').remove();
return false;
});
however its only printing out the first element and not the preceding ones. I have created a fiddle can anyone see why?
http://jsfiddle.net/drk8X/
I wasn't able to come up with the perfect solution (will have a look later) but I have redesigned the function to work to an extent.
$("body").on('input propertychange', function () {
var outputme="";
$('textarea').each(function (index) {
outputme+='<br>'+(index+1) + '. ' + $(this).val();
});
$('#lp-step').html('<h3>Method</h3>'+outputme);
});
This will update the "preview" on change of the text area, use CSS Selectors to narrow down the scope, but id reccomend you looking at your HTML and try and simplify it a bit more.
http://jsfiddle.net/drk8X/2/

Why is my JQuery function not triggered on a cloned element when the event becomes "true"?

I have been making this form that must enable the back-end user to create new questions for users to answer. The form is cloned and appended to a div (selector #content) successfully after the first .on(click) event, but it won't duplicate the form again if the cloned button is pressed. The .on(change) event applied to my drop-down selection does change the content of respective divs like it is supposed to, but only on the original form.
Here's the JQuery code:
$(document).ready(function () {
$('.addAnswer').on("click", function () {
var idx = $('#mp div[name^="antwoord"]:last').index() + 1;
$clone = $('#mp div[name^="antwoord"]:first').clone(true, true).attr('class', 'answer content_' + idx);
$('.removeAnswer').show;
$('#mp').append($clone);
$('.answer:last').each(function () {
$('b:last').empty();
$('b:last').prepend(String.fromCharCode(64 + idx) + ". ")
$('.addAnswer').on("click", function () {
idx++;
});
});
if (idx == 2) {
$('.removeAnswer').show();
}
});
$('.nextq').click(function () {
var newqid = $('#content form:last').index() + 1;
$('.done, .nextq, .remove').hide();
$('#content').append('<hr>');
$('#content').append($('form').html()).attr('class', 'q_' + newqid);
$('.nextq').on("click", function () {
newqid++;
});
$('.done:last, .nextq:last, .remove:last').show();
return false;
});
$('.group').hide();
$('#text:last').show();
$('.select:last').on("change", function () {
$('.group').hide();
$('#' + $(this).val() + ':last').fadeIn();
$('button.' + $(this).val() + ':last').fadeIn();
});
});
Because I thought posting the whole HTML template would be a tad bit too much, I provided a JSFiddle for you people.
One extra question for the ones that are feeling kind: In the JQuery code it is seen that the contents of the HTML are being parsed using .html() and appended with .append.(Line 33 on the JSFiddle) As the .on(change) function switches the contents of the divisions it should change, .html() sees those changes and takes those along with it. I'd like the .on(click) function to append the div's content in its original state, unchanged by the changes made beforehand by the back-end user. Any help with this would be much obliged.
In order to have jQuery trigger on new elements you would do something like
$( document ).on( "click", "<your id or class>", function() {
//Do stuff
});

Categories

Resources