Attempting to loop and print an element in jQuery - javascript

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/

Related

onclick generates invalid function

I have a variable that is attached to a function. I am trying to use that variable in an onclick event.
This is what I am doing
var show = function() {
console.log("hello");
};
$(container).append(
"<div class='info' onclick=" + show + ">Show</div>"
);
However the generated html comes out like this
<div class="info" onclick="function()" {="" console.log("hello");="" }="">
Show
</div>
Any idea how I can fix this so that when I click the div my function gets called ?
You can simply do like this, Just make show a function and call it on click.
This will work
<script>
function show() {
console.log("hello");
}
$(container).append(
'<div class="info" onclick="show()">Show</div>'
);
</script>
This is kind of an unusual approach to what you're trying to do. I think it would be more idiomatic in jQuery to either
a) define the element first, with event handler, and then append it,
$("<div>Show</div>", {
"class": "info",
on: {
click: function(e) {
console.log("Hello");
}
}
}).appendTo($(container));
or
b) append a new element and then add an event handler to it after appending it.
$(container).append("<div class='info'>Show</div>");
$(container).children('.info').last().on('click', function(e) { console.log("Hello"); });
Between those two, I'd recommend the first in this case.
The variable show is a function, Then how can you bind it with string?
The code should be like,
$(container).append("<div class='info' onClick='show()'>Show</div>");
try using :
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick="+'show()'+">Show</div>");
This will work.
The reason why your code
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick=" + show + ">Show</div>");
was not working as required as show is an object of type function, so when one uses the function name without the () the variable is replaced bu the code that it consists.
Hope it helps.

Is there a way to apply jQuery to dynamically created elements? (not event listeners)

I have dynamically created an element with the following class:
<span class="text">Hello</span>
and jQuery:
function changeText() {
var oldText = $(this).text();
$(this).text(oldText + " There");
}
$(function() {
$(".text").each(function(){
changeText.apply(this);
})
})
Obviously, this is a simplified version of what is actually happening but the basics are there. Is it possible to apply this rule to dynamically created elements even though we are not using event listeners?
The problem here is that there is no specific location for these ".text" elements. The only place we know these will show up is in the body. I we use a mutationObserver on the body... wouldn't that be taxing performance?
Do this instead:
function changeText() {
var oldText = $(this).text();
$(this).text(oldText + ' There');
}
$(function(){
$('.text').each(function(i, e){
changeText.call(e);
});
});
Like this
$dynamicElement.find(".text").each(function(){
changeText.apply(this);
})

is(':visible') not working

hey guys i am new to jquery and i was going throught the modal.js code and found the below code:
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
i tried to understand the above code , so i made a fiddle.
now if you see the if conditional in the code :
if ($this.is(':visible')) {
$('input').trigger('focus');
console.log($this + ' ' + 'is visible');
} else {
console.log($this + ' ' + 'invisible');
}
now even if i have the following display rule I.E.
input {
display:none;
}
The if condition still passes , well thats my 1st difficulty . why does the if condition pass ??
my secound difficulty is the line inside the if condition I.E.
$this.trigger('focus');
now even though the if condition passes the input does't get the focus . why ??
Thank you .
I've made some minor chances to your code, and now it all seems to work for me:
$(document).ready(function () {
$target = $('input');
$target.trigger('focus');
$target.one('show.bs.modal', function (showEvent) {
$this = $(this);
console.log($this);
if ($this.is(':visible')) {
$this.focus();
} else {
console.log($this + ' ' + 'invisible');
}
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
});
});
$target.trigger('show.bs.modal');
});
http://jsfiddle.net/v36zoy1g/2/
To focus an element, you don't need fancy code. the .focus() function does the job for you!
And actually, I think that's about it, can't remember anything else I changed to be honest. :p
You haven't cached $(this) on $this.
You can use:
$this = $(this) before you use $this in your code.

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

How to append some extra text in the div tag

I am trying to take the label text of the checkbox which are checked and I trying to append in the span tag,
When user click the the ok button in the popUp
Here it is not working. Here is my jsfiddle
My script is:
$('.modal-footer .preSuccess').click(function(){
var parentElement=$(this).parent().parent().attr('id');
$('#'+parentElement+ '.modal-body input[type="checkbox"]').each(function(){
var pre =$(this).next('label').text();
if($(this).is(':checked')){
$('.'+parentElement+'Pre').append('<span>'+pre+'</span>');
}
});
});
Try
$('.modal-footer .preSuccess').click(function () {
var modal = $(this).closest('.modal');
var parentElement = modal.attr('id'); // issue here, use closest to get a parent matching the selector
//again issue with the selector
modal.find('.modal-body input[type="checkbox"]').each(function () {
var pre = $(this).next('label').text();
if ($(this).is(':checked')) {
$('.' + parentElement + 'Pre').append('<span>' + pre + '</span>');
}
});
});
Demo: Fiddle
I took a look at your code and you're missing a space when querying the checkbox:
$('#'+parentElement+ ' .modal-body input[type="checkbox"]')
It wasn't able to find your checkbox and couldn't find the texts.
Other than that I would advice against the .parent().parent() structure, cause it's very prone to future bugs. Maybe just call the id directly, but I'm not sure how you're using this code.

Categories

Resources