Repeatable Blocks - javascript

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.

Related

on click fires outside of hyperlink

I am creating a dynamic delete link that as such:
<a id=\"removeAtt__" + i + "\" class=\"remove_button\" style=\"color:#aaa;\"><i class=\"fa fa-times-circle\"></i> remove</a>
I am using the following code once the link is clicked:
$(document).on("click", $('[id*=removeAtt__]'), function () {
var id = event.target.id;
var n = id.lastIndexOf('__');
var result = id.substring(n + 2);
$('#othAtt__' + result).remove();
});
What I am finding is that even when I click outside of the hyperlink at times, it fires the delete. Is there a better way to do this so it fires on click of the hyperlink all the time.
You need to pass a selector, like
$(document).on("click", '.remove-button', function () {
var id = this.id;
var n = id.lastIndexOf('__');
var result = id.substring(n + 2);
$('#othAtt__' + result).remove();
});
And oldschool solution is to define a function to be executed when the button is clicked and call it in the onclick attribute of the tag.
You're selector is not correct so it's actually executing on $(document). This is my preference on writing jQuery selectors:
$('[id*=removeAtt__]').on("click", function () {
var id = $(this).attr('id);
var n = id.lastIndexOf('__');
var result = id.substring(n + 2);
$('#othAtt__' + result).remove();
});
The reason is if my selector is off I don't get a false sense that code is actually working.

Dynamic selector in .on() method

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");
});
});

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
});

Guide Text Not working when text is entered using another control

I have a textbox used to enter the text by user, which guide-text which disappears when user starts to write. But when I use a dropdown & select a text from it, & this text is automatically entered in the textbox, the guide-text is not fading away.
Events I am using to fade the guide-text :
$('input, textarea').live('keydown', toggleLabel);
$('input, textarea').live('paste', toggleLabel);
On change of dropdown :
$('.ui-discussion-text').change(function () {
var oldText = $('.ui-discussion-input textarea').val();
$('.ui-discussion-input textarea').val(oldText + " " + $(this).val());
});
Please help.
It's a little hard to say without seeing the rest of the code, but because you are changing code dynamically there isn't an event that will fire (I thought change might, but looked into it and realized it won't). Since you already have an onchange event for the dropdown, why not just call the toggleFunction at that point?
http://jsfiddle.net/spacebean/SvNUw
$('.ui-discussion-text').change(function () {
var oldText = $('.ui-discussion-input textarea').val();
$('.ui-discussion-input textarea').val(oldText + " " + $(this).val());
toggleLabel();
});
Alternately, you can add a focus after you replace the text and set a listener for that:
http://jsfiddle.net/spacebean/SvNUw/2/
$('input, textarea').live('keydown paste focus', toggleLabel);
$('.ui-discussion-text').change(function () {
var oldText = $('.ui-discussion-input textarea').val();
$('.ui-discussion-input textarea').val(oldText + " " + $(this).val()).focus();
});
Or lastly, you can just add a trigger to the element after you copy the text, e.g.:
http://jsfiddle.net/spacebean/SvNUw/4/
$('input, textarea').live('keydown paste', toggleLabel);
$('.ui-discussion-text').change(function () {
var oldText = $('.ui-discussion-input textarea').val();
$('.ui-discussion-input textarea').val(oldText + " " + $(this).val()).trigger('paste');
});
And, as you can see, you don't need a separate line for each event type if they are all triggering the same function. Just add them separated by space like above.

Categories

Resources