Wednesday, May 01, 2013

.html() stripping off form tags


Recently I have been working on jQuery and KnockoutJs a bit. A bit means, a lot. :) It has been really exciting times as I have been learning lot of stuff. There are also times where I pull my hair off. :)

I have a View which is a pure html file, with no bells and whistles, except the "data-bind"s for the Knockout. And I load it using .get{} and place it in a
inside a page. Kinda SPA we have in place.

.get ("/<SomeDir>/<Somefile.html>", function(data){
 
 $("#someDiv").html(data); 
 ko.applyBindings(new ViewModel, $("#formElement")[0]);
});
See the second line after the html placement? The ko binding, that is. The application crashes on the line. While debugging, I found that $("#formElement")[0] turns out to be "undefined". "formElement" is the
tag I have which wraps the contents in the html file. I was getting this only on IE10. I have no issues in IE8 and IE9. This really started bothering me. I looked around the internet and had no clue! I started debugging again, with my ultra modern debugging tool - alert() statements :). I place an alert statement right after the html placement. As:
.get ("/<SomeDir>/<Somefile.html>", function(data){
 
 $("#someDiv").html(data);
 alert($("#someDiv").html());
 ko.applyBindings(new ViewModel, $("#formElement")[0]);
});
This retrieved the html data that we placed in. What I saw really took my skin off! I saw that the
form tag (with id as formElement) had been stripped of! Yes, stripped off. Taken off! And that meant there was no "formElement" that got loaded in the DOM and hence the crash. I went hunting for answers again. And I found that I was not alone. Eventhough there was only one link which helped me: http://forum.jquery.com/topic/is-jquery-stripping-form-tags In HTML5, you cannot have a
tag inside a
tag. So, the html() strips the
tag out, without any warning! Thats bizarre. But thats what it does. In the article/forum post mentioned above, there are three workarounds:

1. Take out the "form" tag from the html file.
 This is the easiest and straightforward approach. But my case is different. I have validations in place, using jQuery UI Validation plugin. And that works only against "form"s.

2. Add a "form" tag in the beginning. Just before the opening "form" tag. Even though it would work, it seems like a hack to me. No, it is one.

 3. Use append() function instead of html(). Like,
 
$("#someDiv").html();
$("#someDiv").append(data);

Even though the 1st one is the right move, I would go with the 3rd one. Hope this would save hours of someone's life, as it did mine :) Have a wonderful programming day!

No comments:

Post a Comment

Cookies, anyone?

  Our application started having integration issues early March this year. Did I say that was intermittent? To add to our confusion, we coul...