javascriptjqueryregexjquery-selectors

Please help me with this regular expression


I am trying to search inputs with the required ids. But it seems my regular expression is incorrect. How can I correct it?

I will have inputs with ids like.. a1_1,b1_1,c3_999,d4_777 etc. Those will be there inside a <td>. What I want is I need to some inputs with the passed ids. Like

   NoneArray=[a_1,c_3].

So I need to find these ids and assign a Class. For that I am using below code.

http://jsfiddle.net/nnQxN/

for(var i = 0;i < NoneArray.length;i++)
{
    var x = NoneArray[i]+"_";
    $('input').filter(function() { 
        return $(this).prop('id').match(^[''+x+''][0-9]{})
    }).addClass('xve');
}

How can I resolve this? Or please suggest me any another way using pushstack and map functions.


Solution

  • I think you can just use a "starts with" selector. I'm not sure how your HTML is structured but if the things you're searching for are all inside a <div id="container">, then:

    var NoneArray = ['a1', 'c3'];
    $.each(NoneArray, function(i, pat) {
        $('#container').find('[id^=' + pat + '_]').addClass('xve');
    });
    

    Live example: http://jsfiddle.net/ambiguous/MwqyS/

    If you're just looking for <input> elements then this should work:

    var NoneArray = ['a1', 'c3'];
    $.each(NoneArray, function(i, pat) {
        $('input[id^=' + pat + '_]').addClass('xve');
    });
    

    Live example: http://jsfiddle.net/ambiguous/tDTjh/