jQuery: children count = 0 and ajax - javascript

I'm working on a jQuery that gets a list of elements from a server, appends it to an element, and then loops in the newly appended elements to transform them (make them jEditable).
I'm having trouble with the loop. The appending works alright, so I have a list of elements like :
<div id="innerModal">
<label id="exampleTitle">Title :</label>
<label id="exampleField" class="ftext">Value</label>
</div>
Then I try to loop in:
function makeListEditable(element, type){
//I checked here that the element sent is well '#innerModal'
alert($(element).children().length);
$(element).children().each(function() {
if( $( this ).is( 'ftext' ) ){
makeEditable( $( this ), type, '', '' );
}
});
}
The alert prints "0".
Where does that issue come from? How can I fix it?
Edit : Here's the call of makeListEditable :
getFormOnElement(//Gets the form and appends it
"getorganisationeditable/"+curOId,
"#innerModal"
);
makeListEditable('#innerModal');
Thanks in advance!

Since ajax is asynchronous, it will not wait till elements are appended and execute makeEditable. Since ajax might not necessarily have completed, the element has no children. Move makeEditable to ajax call's success callback

ftext is a class and needs 'dot' .is(".ftext")

Add an other allert like:
alert($(element).text());
or
alert($(element).html());
so you can know if your selector work fine.

Related

Multiselect js append with getJson not displaying any option

Im probably doing something wrong inside the function but I don't know what it is.
So, I want to display the options after executing getJSON, I want them to be displayed inside a select in the form of a checkbox.
This is my code:
<div class="form-group">
<label>Forma de pago</label>
<select id="formaPago" name="formaPago[]" class="form-control listado-metodosPago" autocomplete="off" multiple="multiple"></select>
</div>
$(".listado-metodosPago").ready( function(){
$(".listado-metodosPago").append('<option value="">Seleccione una opciĆ³n</option>');
$.getJSON( url2 + "Clientes/lista_metodosPago").done( function( data ){
$.each( data, function( i, v){
event.preventDefault();
jQuery.noConflict();
$(".listado-metodosPago").append('<option value="'+v.id_opcion+'" data-value="'+v.id_catalogo+'">'+v.nombre+'</option>');
});
});
$(".listado-metodosPago").multiselect('refresh');
});
I try to use
$(".listado-metodosPago").multiselect('refresh');
I try to put it inside getJSON, but when i do that it doesn't recognize the '$(...).multiselect' function
Also I try to use:
$(".listado-metodosPago").multiselect('rebuild');
And this: source of json in Multiselect jQuery
But still it doesn't recognize the '$(...).multiselect' function.
I was able to find an answer that helped me, in case someone goes through the same problem, I had to replace $ for jQuery. In other words, my first try:
(".listado-metodosPago").multiselect('rebuild');
And the answer (at least in my case):
jQuery('#formaPago').multiselect( 'rebuild');
And the link:
https://forum.jquery.com/topic/multiselect-is-not-a-function-error-message-using-jquery-ui-multiselect-widget

get value from localStorage and append it to class

I'm messing around with setting data into localStorage, but I'm trying to extract a value and have it populate into an empty span on a specific page load.
This is what I've been messing with, but I'm not sure if this is the correct way to go about it:
if($(".body-class-name").length > 0){
$('.title span').append($(localStorage.getItem("first_name")));
}
The only other examples I've tried to work with deal with external JSON data and that's a little too much for what I'm trying to work with.
The code does what it is suppose to. You could improve abit.
if($(".body-class-name").length > 0){
var firstname = $(localStorage.getItem("first_name");
if (firstname) {
$('#title-text').text(firstname));
}
}
Then there is some missing context in your post. But i would also look at:
Using text instead of append if you don\t want to keep append firstnames to that span.
And as others mentioned in comments be aware of your selector. I changed it to query for an ID instead.
if ( $ ( ".body-class-name" ). length > 0 ){
$ ( '.title span' ). append ( localStorage . getItem ( "first_name" )); }
The $() isn't needed around the localStorage.getItem()
You don't need using load event.
Load event is for assets files, you can use ready event.
In basically jQuery code run after document ready.
You just need to wrap with function, For example:
<h1 class="title">Hello again <span>User</span></h1>
<br/>
<label>
Enter your name here:
<input name="firstname" />
</label>
<script>
(function($){
$("input[name='firstname']").change(function(){
// Store
localStorage.setItem("first_name", $(this).val() );
});
// Load store
$('.title span').text( localStorage.getItem( "first_name" ) );
})(jQuery);
</script>
Live code here

having an issue to call Javascript function from jquery

I have a Datepicker for Bootstrap and I am having an issue to run a function called "listCampaignsFiltered(search, type, from, 'dataTable')" that filters the results once I click on any date from the calendar. Here is the code:
Html
<div id="showfrom">
<label for="from" class="filter">From:
<input type="text" class="filter" value="01/01/2014" id="from"/>
</label>
</div>
Js
$(document).ready(function(){
$('#showbrand input').val(01/01/2014).click(listCampaignsFiltered);
});
The proper form would be:
$('#showbrand input').val('01/01/2014').on('click', function() {
listCampaignsFiltered(...params....)
});
The call val(01/01/2014) would set the value to 1 divided by 1 divided by 2014. You are missing quotes.
Are you sure you always want to set the date back to 01/01/2014? If so use the commented out line instead of the line bellow it.
Next listCampaignsFiltered has be be defined and without error. I am assuming it works and you've tested it independently of the listner.
Next, to pass the values into it, you need wrap the function in an lambda/anonymous function.
I am also assuming that the values for function are all in inputs with the ids matching the parameters you gave in your post.
Here is what you end up with, with those changes:
$(document).ready(function()
{
/*$('#showbrand input').val('01/01/2014').click(function()*/
$('#showbrand input').click(function()
{
listCampaignsFiltered
(
$('#search').val(),
$('#type').val(),
$('#from').val(),
'dateTable'
);
});
});
may be this is what you intended
$(document).ready(function(){
$('#showbrand input').val('01/01/2014').on('click', function()
listCampaignsFiltered(param1,param2,param3,param4);
});
});
jsfiddle.net/JixunMoe/29wBy/
Not sure if that's what you want, but the callback works as expected (for me).

Focus element loaded by jQuery $.get(...)

I'm loading a html snippet, insert it after a certain element and want to focus an input field with the class .focus. There could be more than one element with this class. Similar code with load(...) works.
var item = $(this).closest(".something");
$.get(
url,
function(data) {
item.after(data);
$(data).find(".focus").focus(); /* everything works except this line */
}
);
The relevant part of the loaded html:
<input type="text" class="focus" value="" name="email"/>
It looks like the element to be focussed is found (in the debugger), but it doesn't get the focus. Any idea what is wrong?
item.after(data) parses data into a set of DOM elements and puts them in your document.
$(data) then parses data into another set of DOM elements, which are never displayed.
You want
$(data).insertAfter(item).find(".focus").focus();
This is because data is not in the DOM.
Try this:
var item = $(this).closest(".something");
$.get(
url,
function(data) {
var $data = $(data);
item.after($data);
$data.find(".focus").focus(); /* everything works except this line */
//or you can do: $(".focus", $data).focus();
}
);
Try,
item.next().find(".focus").focus();
Try using item.next().find('.focus').focus(). In the Ajax callback, data isn't a jQuery object but a string of HTML; calling item.after() makes jQuery create DOM nodes from the HTML but they're not linked to your data variable.
That is because you are not calling focus() on the element which is added into the dom.
Try this.
var item = $(this).closest(".something");
$.get(
url,
function(data) {
item.after(data);
item.nextAll(".focus").focus(); /* everything works except this line */
}
);

Using fadein and append

I am loading JSON data to my page and using appendTo() but I am trying to fade in my results, any ideas?
$("#posts").fadeIn();
$(content).appendTo("#posts");
I saw that there is a difference between append and appendTo, on the documents.
I tried this as well:
$("#posts").append(content).fadeIn();
I got it, the above did the trick!
But I get "undefined" as one of my JSON values.
If you hide the content before you append it and chain the fadeIn method to that, you should get the effect that you're looking for.
// Create the DOM elements
$(content)
// Sets the style of the elements to "display:none"
.hide()
// Appends the hidden elements to the "posts" element
.appendTo('#posts')
// Fades the new content into view
.fadeIn();
I don't know if I fully understand the issue you're having, but something like this should work:
HTML:
<div id="posts">
<span id="post1">Something here</span>
</div>
Javascript:
var counter=0;
$.get("http://www.something/dir",
function(data){
$('#posts').append('<span style="display:none" id="post' + counter + ">" + data + "</span>" ) ;
$('#post' + counter).fadeIn();
counter += 1;
});
Basically you're wrapping each piece of the content (each "post") in a span, setting that span's display to none so it doesn't show up, and then fading it in.
This should solve your problem I think.
$('#content').prepend('<p>Hello!</p>');
$('#content').children(':first').fadeOut().fadeIn();
If you are doing append instead then you have to use the :last selector instead.
You have to be aware that the code doesn't execute linearly. The animated stuff can't be expected to halt code execution to do the animation and then return.
commmand();
animation();
command();
This is because the animation uses set timeout and other similar magic to do its job and settimeout is non-blocking.
This is why we have callback methods on animations to run when the animation is done ( to avoid changing something which doesn't exist yet )
command();
animation( ... function(){
command();
});
$(output_string.html).fadeIn().appendTo("#list");
assuming you have the following in the css defined:
.new {display:none}
and the javascript should be :
$('#content').append('<p class='new'>Hello!</p>');
$('#content').children('.new').fadeIn();
$('#content').children.removeClass('new');
$('#content').children('.new').hide();
First is convert received data to jQuery Object.
Second, hide it immediately.
Third, append it to a target node.
And, after this all, we can clearly use necessary animation, just like fadeIn :)
jNode = $("<div>first</div><div>second</div>");
jNode.hide();
$('#content').append(jNode);
jNode.fadeIn();
im have a exprensive,for this:
$("dt").append(tvlst.ddhtml);
$("dd:last").fadeIn(700);
I tried what you said did the trick but is not working.
it worked with the following code
$("div").append("content-to-add").hide().fadeIn();

Categories

Resources