Jobert Enamno
Jobert Enamno

Reputation: 4461

jQuery check if input has matched name based on keyword

I have a form. In this form I'm tracking the input value through blur event. I have a need that I will take only the values if input name has or contains txt_asnLineRepeat. My problem is that my selector is always undefined. I need to have true or false as return. Please help. Here's my code.

<input type="text" name="txt_asnLineRepeat" value="1000" size="10"/>
<input type="text" name="txt_asnLineRepeat_0" value="200" size="10"/>
<input type="text" name="txt_asnLineRepeat_1" value="500" size="10"/>
<input type="text" name="DeliveryDate"/>
<input type="text" name="TrackingNo"/>
$('#frmDocument input:not(.button),select').on("blur", function () {
    var selector = $(this);
    var name = selector.attr('name');
    //check if selector name contains txt_asnLineRepeat 
    //should return true or false
    var hasResult = selector.attr("name:contains('txt_asnLineRepeat')")
    //hasResult always gives me undefined. Return must be true or false or 1 or 0.
});

Upvotes: 1

Views: 79

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You could save the logic in the event handler by only attaching the event to the relevant elements by using the 'attribute starts with' selector:

$('#frmDocument input[name^="txt_asnLineRepeat"]').on("blur", function () {
    // your logic here...
});

Upvotes: 3

eisbehr
eisbehr

Reputation: 12452

You can use indexOf to look for the string inside name. But only if you want to do further stuff in your event handler. Otherwise go with @RoryMcCrossan answer!

var hasResult = selector.attr("name").indexOf("txt_asnLineRepeat") >= 0;
// or
var hasResult = name.indexOf("txt_asnLineRepeat") >= 0;

Upvotes: 2

Related Questions