jQuery: select all inputs with unique id (Regex/Wildcard Selectors)

江枫思渺然 提交于 2020-01-02 01:21:11

问题


I have some textboxes on a webform that have ids like this:

txtFinalDeadline_1
txtFinalDeadline_2
txtFinalDeadline_3
txtFinalDeadline_4

In my jQuery how do I find all of those in order to assign a value to them. Before I had the underscore and they were all named txtFinalDeadline I could do this and it worked.

$(this).find("#txtFinalDeadline").val(formatDate);

However, that was when they were all named the same thing. Now I have the _x after the name and I'm not sure how to go about assigning that same value as before to them.


回答1:


I don't know if I can guarantee "in order", but this elector should work:

$(this).find('input[id^=textFinalDeadline_]').val(formatDate);

Even then, jQuery is optimized to handle ids in a special way, and may only process 1 id.

A better way would be to have these textfields use a class (perhaps date) so you could just use the '.date' selector.




回答2:


There are multiple ways to do a regex or wildcard select:

Using jQuery selector's inline wildcards:

$('#textFinalDeadline_\\S*').val(formatDate);

update: I noticed that this method is no longer working since jQuery 1.3.2.

Using CSS3 selectors:

$('input[id^=textFinalDeadline_]').val(formatDate);

Using .filter() & match():

$('input').filter(function(){
  return this.id.match(/txtFinalDeadline_*/);
}).val(formatDate);

At last you might want to use a regex selector.

$('input:regex(id, txtFinalDeadline_*)').val(formatDate);



回答3:


Does Child Selector help you?



来源:https://stackoverflow.com/questions/2707265/jquery-select-all-inputs-with-unique-id-regex-wildcard-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!