Jimmy Jimmy - 2 years ago 104
jQuery Question

I need to run a JQuery method when an attribute contains a certain value?

I would like to run a method if the "name" attribute contains the word "test". I believe that I am using an incorrect syntax.

if($("input[name*='test']")) {
alert('found!'); //Do Something

The HTML I am using is

<input name="test" type="text">

Answer Source

You didn't specified what is the exact problem with your code, but there's an obvious problem with the way your are testing your selector result.

$("input[name*='test']") will always return a jquery object even if there's no match for the specified selector. In order to validate if the selector has a match, you should check using the length property:

if($("input[name*='test']").length) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download