Reputation:
I have the following input elements:
<input id="AAA_RandomString_BBB" type="text" />
<input id="AAA_RandomString_BBB_Start" type="text" />
<input id="AAA_RandomString_BBB_End" type="text" />
AAA & BBB are constants and I will always know what they are. However RandomString will always be random.
I want to get the value of AAA_RandomString_BBB. I do not want the values from the input elements with ID ending in either _Start or _End.
I tried the folowing:
$('[id^="AAA_"]')
But the above selects all of the input elements that have an ID starting with "AAA_"
I need some way to select using a regex type syntax like:
$('[id^="AAA_(.+?)_BBB"]')
Is this possible? If not, can anyone suggest a method of selecting
Upvotes: 62
Views: 88779
Reputation: 2002
How about this :
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<input id="AAA_RandomString_BBB" type="text" />
<input id="AAA_RandomString_BBB_Start" type="text" />
<input id="AAA_RandomString_BBB_End" type="text" />
<script>
$(document).ready(function () {
debugger
var targetElement = $('input')
.filter(function () {
var el = this.id.match(/^AAA.*BBB$/g);
return el;
});
console.log(targetElement.val());
})
</script>
</body>
</html>
Upvotes: 0
Reputation: 18250
I use to solve this with the class selectors which don't need to be unique.
This also has a positive effect on speed because no complex search is required Additionally you can use this for the different styling of different elements
e.g.
<elem id="1" class="aa">element type aa</elem>
<elem id="2" class="aa">element type aa</elem>
<elem id="3" class="aa bb">element type aa and bb</elem>
<elem id="4" class="bb">element type bb</elem>
Now you can simply use the class selector
$('.aa').click(function(){
console.log( 'clicked type aa #' + $(this).attr('id') );
});
$('.bb').click(function(){
console.log( 'clicked type bb #' + $(this).attr('id') );
});
Upvotes: 0
Reputation: 314
It would be better to just check for the id ending on _BBB by
$("[id$=_BBB]")
Upvotes: 0
Reputation: 23537
You can combine both selectors in a multiple attribute selector.
$("[id^=AAA_][id$=_BBB]")
It will return all the elements that matches all the specified attribute filters:
[id^=AAA_]
matches elements with id
attribute starting with AAA_
, and[id$=_BBB]
matches elements with id
attribute ending with _BBB
.Another generic alternatives:
:regex()
selector,.filter()
-based approach.Upvotes: 136
Reputation: 433
This can be done like so:
$('input').filter(function(){ return this.id.match(/^AAA_.+_BBB$/) })
You can give use $('input', <context>)
to make the search more precise.
See also here
Upvotes: 7
Reputation: 5674
You can look for id's starting with AAA
and ending with BBB
like this:
$("[id^=AAA_][id$=_BBB]")
The working fiddle: http://jsfiddle.net/DN9uV/
Upvotes: 8
Reputation: 167182
$('[id^="AAA_"][id$="_BBB"]')
Upvotes: 17