Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selector: ID starts with something (keyword "section")

I want to target all divs that have an id that begins with "section"; for each of these divs, I want to show child divs of type input that begin with "pre".

    //groups = $('div [id^=section]');  
    groups = $('[id^=section]');    

    $.each(groups, function(key, group) {
         alert(key + ': ' + group); 
        //inputs = group.('[id^=pre]'); 
    });


<div id="section-A1">       
    <input id="preBeginDtl" name="BeginDtlFields" value="" type="hidden">
    <input id="other" name="name2" value="" type="input">
    <input id="preGroup" name="GRP" value="AA" type="hidden">
</div>
like image 857
mustapha george Avatar asked Aug 12 '11 18:08

mustapha george


People also ask

Which is the correct form of using ID selector in jQuery?

The #id Selector The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

What is difference between the id selector and class selector in jQuery?

Differentiate the concepts of ID selector and class selector: The only difference between them is that “id” is unique in a page and it is applied to one HTML element while “class” selector can apply to multiple HTML elements.

Which of the following jQuery selector selects elements with the given element ID some ID?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


2 Answers

This would work as the selector:

$('[id^=section] > [id^=pre]')

But, I don't think you can change the type attribute for input elements. You would probably just want to set the 'pre' inputs as type="text" (instead of type="hidden"), and set their css display property to none. Then use the jQuery show() to unhide it.

<div id="section-A1">       
    <input id="preBeginDtl" name="BeginDtlFields" value="" type="text" style="display:none">
    <input id="other" name="name2" value="" type="text">
    <input id="preGroup" name="GRP" value="AA" type="text" style="display:none">
</div>

and

$('[id^=section] > [id^=pre]').show()
like image 186
markle976 Avatar answered Nov 15 '22 18:11

markle976


Rather than look for a partial id, perhaps you should add classes "section" and "pre" to the divs? Then you can search on

groups = $('div.section div.pre');

What you are doing is essentially a class-based lookup, and that would be the appropriate mechanism.

like image 42
Jeremy Holovacs Avatar answered Nov 15 '22 17:11

Jeremy Holovacs