4

I have the following code and I'm trying to retrieve the txtboxes where id does not contain the the word OT.

<input type="text" id="txtMo1">
<input type="text" id="txtOTMo1">
<input type="text" id="txtTu1">
<input type="text" id="txtOTTu1">
...
...
<input type="text" id="txtMo4">
<input type="text" id="txtOTMo4">
<input type="text" id="txtTu4">
<input type="text" id="txtOTTu4">
...
...

I tried using .find where id starts with txt but it gives me everything (obviously). How do I retrieve only the textboxes where id starts with txt but does not contain OT?

.find("input[id ^= 'txt']")
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
tempid
  • 7,838
  • 28
  • 71
  • 101
  • If you're the one generating this markup, consider making use of classes: ``. Then you can simply do `$(".cal").not(".cal-ot")` etc. – Ates Goral Feb 09 '12 at 15:23
  • Yes, I'm generating the markup (using jtemplates). Thanks for the excellent idea. I think it will have less overhead as well. Learning new things with jquery everyday! – tempid Feb 09 '12 at 15:28

2 Answers2

6

Don't use a selector: use filter:

.find('input[id^="txt"]').filter(function() {
    return -1 === this.id.indexOf('OT');
});

The callback to filter should return true if the element should be kept and false if it should be removed. In this case, the function will return true and the element will be kept if indexOf returns -1, which means that OT is not present.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Worked perfectly. Thank you so much! Quick question if you don't mind -- why did you use `===` instead of `==`? – tempid Feb 09 '12 at 15:30
  • @enigma Here, there's no particular reason; it doesn't make much difference. Frequently, however, there is a difference in meaning, and I think it's a good habit to always use `===` except where you *mean* `==`. – lonesomeday Feb 09 '12 at 15:59
  • regarding "why did you use === instead of ==?" please look here http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – Mandeep Janjua Jun 12 '13 at 16:05
2

Why don't you use a class instead for those specific textboxes and use a class selector instead?

But still if you need a solution here it is.

$('input[id^-"txt"]').filter(function() {
    return this.id.indexOf('OT') == -1;
});

You can render your mark something like this and make your code simple.

Mark up

<input type="text" id="txtMo1">
<input type="text" class="OT" id="txtOTMo1">
<input type="text" id="txtTu1">
<input type="text" class="OT"id="txtOTTu1">

Js

$('input.OT').doYourStuff();
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124