views:

291

answers:

1

I have just stared using jQuery and although following code gets the job done, I have a feeling that it can be shortened.

var accountAddress = $(document.createElement("input")).addClass("readOnly").attr("contentEditable", "false").attr("id", "d_accountAddress");
$("#customerid_c").next().next().next().append(accountAddress);

If it is not clear - what I'm doing is creating new input tag, assigning class and making it readonly, then positioning new input two TD's to the right of some known text.

Update:

This is simplified HTML that I'm modifying. The place where I add content is marked with ##1## and ##2##.

<TD id=customerid_c><LABEL for=customerid>Customer</LABEL></TD>
<TD id=customerid_d></TD>
<TD class=ms-crm-Field-Normal><LABEL>##1##</LABEL></TD>
<TD>##2##</TD>
+21  A: 

Yes, it can.

$('#customerid_c').nextAll().eq(2)
    .append('<input class="readOnly" id="d_accountAddress" />');

In jQuery 1.4.2, you can write

$('#customerid_c~:eq(2)')
    .append('<input class="readOnly" id="d_accountAddress" />');

This selector, which does not work correctly in earlier versions of jQuery, uses the Next Siblings Selector (~) to select all sibling elements following #customerid_c, then uses the :eq selector to select the third (zero-based) element matched by the other selector.

jQuery has a large variety of selectors that can probably replace the indexed sibling. If you show us your HTML, we can find you one.

Other notes:

You can set multiple attributes in one call:

$(something).attr({ id: 'd_accountAddress', type: 'text' });
SLaks
I've never seen that syntax before, what does `#el~:eq(2)` specifically do?
Tatu Ulmanen
Wow! i just learned something. thnx http://api.jquery.com/eq/
used2could
I think that the ~ is used to navigate to the children of an element, in this case #customerid_c, and eq is the equality operator, in this case used to go to the 0 based index, so the third child.
Kieron
A cleaner way to write it would be. $('#customerid_c').nextAll().eq(2).append('<input class="readOnly" id="d_accountAddress" />');
PetersenDidIt
that is cool I shall remember that one
mcgrailm
@Tatu, @used, @Kieron, @mmcgrail: That selector does work in 1.4.2. SO uses 1.3.2, which apparently has a bug.
SLaks
@Kieron > is child elements, ~ is siblings
Ed Woodcock
@Ed Ah, thanks ed!
Kieron
@petersendidit - please post this as an answer, for the googler's sake.
stereofrog
@stereofrog: I already edited that in.
SLaks