Friday, August 24, 2018

How to check null objects in jQuery

I'm using jQuery and I want to check the existence of an element in my page. I have written following code, but it's not working:

if($("#btext" + i) != null) {
    //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

How do I check the existence of the element?

Solved

Check the jQuery FAQ...

You can use the length property of the jQuery collection returned by your selector:

if ( $('#myDiv').length ){}

(Since I don't seem to have enough reputation to vote down the answer...)

Wolf wrote:

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!

Instead try this:

 // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE!  -- EleotleCram
if($("#something") !== null){
  // do something
}

or

 // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE!  -- EleotleCram
if($("#something") === null){
  // don't do something
}

While it is true that calling the length property on an undefined or null object will cause browsers to fail, the result of jQuery's selectors (the $('...')) will never be null or undefined. Thus the code suggestions make no sense. Use one of the other answers, they make more sense.


(Update 2012) Because people look at code and this answer is pretty high up the list: For the last couple of years, I have been using this small plugin:

  jQuery.fn['any'] = function() {
     return (this.length > 0);
  };

I think $('div').any() reads better than $('div').length, plus you won't suffer as much from typos: $('div').ayn() will give a runtime error, $('div').lenght will silently most likely always be falsy.

__

Edits november 2012:

1) Because people tend to look at code and not read what is said around the code, I added two big caveat lector notes to the quoted code of Wolf.

2) I added code of the small plugin I use for this situation.


The lookup function returns an array of matching elements. You could check if the length is zero. Note the change to only look up the elements once and reuse the results as needed.

var elem = $("#btext" + i);
if (elem.length != 0) {
   elem.text("Branch " + i);
}

Also, have you tried just using the text function -- if no element exists, it will do nothing.

$("#btext" + i).text("Branch " + i);

jquery $() function always return non null value - mean elements matched you selector cretaria. If the element was not found it will return an empty array. So your code will look something like this -

if ($("#btext" + i).length){
        //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

In jQuery 1.4 you get the $.isEmptyObject function, but if you are forced to use an older version of jQ like us poor Drupal developers just steal use this code:

// This is a function similar to the jQuery 1.4 $.isEmptyObject.
function isObjectEmpty(obj) {
  for ( var name in obj ) {
    return false;
  }
  return true;
}

Use it like:

console.log(isObjectEmpty(the_object)); // Returns true or false.

no matter what you selection is the function $() always returns a jQuery object so that cant be used to test. The best way yet (if not the only) is to use the size() function or the native length property as explained above.

if ( $('selector').size() ) {...}                   

if ( $('#whatever')[0] ) {...}

The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties; one of them being a "length" property. You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, i.e. $(elem)[0]


use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)


Using the length property you can do this.

jQuery.fn.exists = function(){return ($(this).length < 0);}
if ($(selector).exists()) { 
   //do somthing
}

What about using "undefined"?

if (value != undefined){ // do stuff } 

when the object is empty return this error:

Uncaught TypeError: Cannot read property '0' of null

I try this code

try{ if ($("#btext" + i).length) {};

} catch(err){ if ($("#btext" + i).length) { //working this code if item not NULL }; }


if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!

Instead try this:

if($("#something") !== null){
  // do something
}

or

if($("#something") === null){
  // don't do something
}

Monday, August 20, 2018

How to detect unexpected end of request in Express while the request body is being piped into a child process stdin

I have a child process spawned in my Node.js app, the request body payload is piped directly to the child stdin. Even though the client TCP socket is closed, no relevant events are omitted. What I tried:

close/error/end on req, req.socket and child.sdtdin; disconnect and error on the child. None of them are fired when I close the browser tab sending the request.

I'm looking for your hints.

Solved

So it was my fault, sorry.

The events are called in this particual order:

[2017-02-19 19:10:43] [LOG] req socket event error { [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' } [2017-02-19 19:10:43] [LOG] req event close undefined [2017-02-19 19:10:43] [LOG] req socket event close true


Sunday, August 19, 2018

Stickyjs and jumping navigation menu

How to fix a sticky navigation bar on a site?

The problem is that the header section just jumps to the left at the moment, when I start scrolling, I just want it to stay exactly where it is, if I add position:absolute; to the section it stops to jump, great, however, the site has a blue line, that has the navigation menu on and goes across the width of the page, this is regardless of how wide the screen is.

If I use the position:absolute; code on the header section it stops the line from appearing across the remaining space and cuts it in line with the actual body of the website. The footer remains fine and its making it look unbalanced. Can anyone think of a way to not lose the blue strip?

Also, for some reason part of the header section, which covers the shopping cart and items inside doesn't want to move down with the sticky header, it gets left behind at the top. Is there an easy way in coding to just associate whatever that section is to be part of the header section, or will I have to create a second sticky code for that and make it float in the correct place?

What can I give to help out any further, I'm using the stickyjs plugin, although if you can figure a way to fix everything using another method it will be great.

This link shows what the site is doing at my current stage: http://pressparts.oxatis.com/Default.asp?ADContext=1

Solved

For a sticky navigation bar on a website you should use

position: fixed;
top: 0px;
left: 0px;

This will put your nav bar on the top-left corner of the screen, regardless of scrolling.


Saturday, August 18, 2018

ajax in the spring mvc + thymeleaf application

I'm playing around with spring mvc + thymeleaf.

However I'd like to have integration with ajax (partial page rendering).

Can you recommend me some sample code/tutorial to follow?

I've only found following:

however I'm not interested in using apache tiles or spring web flow at all.

Solved

Tiles is mandatory, for this purpose - according to the site documentation

http://docs.spring.io/spring-webflow/docs/current/reference/html/spring-js.html#spring-js-ajax

Refer section titled - "12.5. Handling Ajax Requests"

This link tells you what is needed is just a parameter with your request, named fragments

http://brosan.net/2012/09/25/partials-with-spring-mvc-3-1-and-apache-tiles/