简体   繁体   中英

Select all the inputs with name attribute contain Substring - jQuery

I want to select all the inputs with name attribute end with *Name .

I have 6 inputs type text with name :

  • deviceName
  • profileName
  • ssidName
  • captiveName
  • trafficName
  • sessionName

HTML

<input class="form-control" type="text" name="deviceName">
<input class="form-control" type="text" name="profileName">
<input class="form-control" type="text" name="ssidName">
<input class="form-control" type="text" name="captiveName">
<input class="form-control" type="text" name="trafficName">
<input class="form-control" type="text" name="sessionName">

I'm trying to prevent any space enter on those 5 inputs

I've tried

$("input[name='*Name']").keyup(function() {
    this.value = this.value.replace(/\s/g, '');
});

My selection doesn't seem to take any effects.

To select element ending with attribute value 'Name' use $("input[name$='Name']") - https://api.jquery.com/attribute-ends-with-selector/ .

 $("input[name$='Name']").keyup(function() { this.value = this.value.replace(/\\s/g, ''); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="form-control" type="text" name="deviceName"> <input class="form-control" type="text" name="profileName"> <input class="form-control" type="text" name="ssidName"> <input class="form-control" type="text" name="captiveName"> <input class="form-control" type="text" name="trafficName"> <input class="form-control" type="text" name="sessionName"> 

Note - If you want to make attribute selector case-insensitive add i before closing square bracket i:e $("input[name$='name' i]") .

 console.log($("input[name$='name' i]")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="form-control" type="text" name="deviceName"> <input class="form-control" type="text" name="profileName"> <input class="form-control" type="text" name="ssidName"> <input class="form-control" type="text" name="captiveName"> <input class="form-control" type="text" name="trafficName"> <input class="form-control" type="text" name="sessionName"> 

I think you are using the correct selector but in the wrong place.

you need to use it like so $("input[name*='Name']")

See the link to jquery documentation. https://api.jquery.com/attribute-contains-selector/

Just a small error in your code with the attribute contains selector -

Change:

$("input[name='*Name']")

to

$("input[name*='Name']")

Check this JSBin for playing around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM