tags:

views:

120

answers:

3

I am rendering a similar construct to the below with some server side code. The server side code inserts hard returns in between the project label and text fields. Not a big deal except the below jQuery code inserts the project label and text fields mashed together.

var projectLabel = $('<label for="project">Project</label>');
var projectField = $('<input type="text" name="project" id="projectName" />');
projectLabel.insertBefore($(this));
projectField.insertBefore($(this));

Because of this discrepancy the elements rendered server side have a space between them while the ones rendered on the client do not. I've tried adding a &nbsp; at the end of each line to no avail. Unfortunately, I have been unable to remove the hard returns outputted by the server side code. Further because of the space I can't fix this with CSS. What are my options for adding spacing via jQuery?

A: 

Perhaps something as simple as adding \n at the end of projectLabel and projectField as you build them?

Ken Redler
A: 

I think it'd be helpful to see the server side code and the output. I'm not sure if you're trying to get the space or not. If you're goal is to have them mash right up to each other, try the following:

You could try formatting an input and label as so:

<label>Project<input type="text" name="project" id="projectName" /></label>

Or when you construct it, construct it right next to each other :

var projectLabelAndField = $('<label for="project">Project</label><input type="text" name="project" id="projectName" />');
projectLabelAndField.insertBefore($(this));
wag2639
The server side code is a series of ASP.NET form controls. Some normal HTML with `runat=server` and others that are traditional `<asp:.....>`.
ahsteele
+1  A: 

When the server side code creates this, with the whitespace between the label and input tags, it is inserting text which is sent to the browser. The browser then interprets that text (as HTML) and builds a DOM tree. When you use insertBefore() in jQuery on the client side, you are inserting DOM nodes directly into the tree. The difference is that the server-generated text ends up creating three sibling nodes: the label, a text node, then the input; while the client side is only creating two nodes: just the label and the input. If you create a text node with a single space (it doesn't even have to be a non-breaking space) and insert it between the other two nodes it should appear the same.

projectLabel.insertBefore($(this));
textNode.insertBefore($(this));
projectField.insertBefore($(this));

I can't tell ya off the top of my head how to create a text node in jQuery.

Stephen P
Used document.createTextNode(' ') as I don't believe there is a jQuery specific mechanism. Thanks for the great answer.
ahsteele