mattruma
mattruma

Reputation: 16677

Trying to set properties/attributes on nested objects with jQuery

I have the following code ... I simplified it by not including the options in the select tags:

    <div>
        Show all tasks where assigned to <span><strong></strong>
           <select></select></span>
        and project is <span><strong></strong>
            <select></select></span>
        and status is <span><strong></strong>
            <select></select></span>
        and category is <span><strong></strong>
            <select></select></span>
    </div>

When the page loads I would like to do the following:

When a user clicks on the strong I would like for it to hide strong tag and show the select.

That being said, I have it working if I assign specific id values to each, for lack of a better term, filter. I would like to streamline my jquery so I can avoid the extra HTML.

Hopefully that made some sense ... here is where I am at with my jquery ...

$(function () {
    $("#filter select").hide();

    $("#filter strong").each(function () {
        $(this).html($(this).siblings("select:first option:selected").text())); // not working
    });

    $("#filter strong").each(function () {
         $(this).bind("click", function () {
             $(this).css("display", "none"); // not sure if this will work, need to get the first part working
             $(this).siblings("select:first").css("display", "");
         });
    });
});

I'm going to keep working on this, but would appreciate any help provided! I think my struggle is with how sibling selectors work in jQuery.

Update

Thanks @alex and @Andy ... here is the final working solution:

$(function () {
    $("#filter select").hide();

    $("#filter strong").html(function () {
        return $(this).next().find(":selected").text(); 
    })

    $("#filter strong").each(function () {
        $(this).bind("click", function () {
            $(this).css("display", "none");
            $(this).siblings("select:first").css("display", "");
        });
    });
}); 

Upvotes: 1

Views: 355

Answers (2)

Andy
Andy

Reputation: 30135

you could use:

$('strong').click(function(){ $(this).hide().next().show(); });

here you have one too many brackets -> .text());

 $("#filter strong").each(function () {
     $(this).html($(this).siblings("select:first option:selected").text())); // not working
 });

Upvotes: 1

alex
alex

Reputation: 490173

I think my struggle is with how sibling selectors work in jQuery.

The siblings() method will select all elements that are neighbours of the current element. It is essentially the same as...

var element = $('#something'),

    siblings = element.parent().children().not(element);

You may also be trying to select too much with your selector string passed to siblings().

Try using...

.siblings("select:first").find("option:selected")

Upvotes: 1

Related Questions