Jquery - find matching selected option and label t

2019-08-11 04:52发布

Solved: http://jsfiddle.net/arkjoseph/swDy5/20/

Goal is to create an amazon style search box which will reduce the amount of space needed for multiple input search/filter fields all on one page.

Search Flow:

obtain labels from the search form.
append labels to a select option field.

on select change, obtain selected value.

If selected val matches a label, display closest div.input,div.option (This is where it all goes wrong. Since im searching an array, i don't think i can locate the closest hidden container near the label. Any tips?)

So far, I have passed the new select values to an array and have attempted to find a match on change.

    $("body").append("<select id='selopt'></select>");

var _op = [];
var _se = "";
$(".views-exposed-widget label").each(function(){
    var text = $(this).text();
    _se += '<option value="'+ text +'">'+ text +'</option>';
    _op.push($(this).text());
    // Monthly Release,Title,New Provider/Show Name
});


$("#selopt").change(function() {
 $("form .views-exposed-widget .views-widget").fadeOut();
    _op[$(this).val()].next('div').css("z-index","100").fadeIn();
    });        

Updated Jquery: http://jsfiddle.net/arkjoseph/swDy5/14/

1条回答
你好瞎i
2楼-- · 2019-08-11 05:18

This will show the closest div to the dropdown that is also hidden.

$("#selopt").change(function() {
    $(this).closest('div:hidden').show();
}); 

Update

Based on your comment this should get you close. Instead of pushing the text into an array, we can create a dictionary of the text to the actual label. Then when the selection changes use the label to find the closest div. Like so:

$("body").append("<select id='selopt'></select>");

var _op = {};
var _se = "";
$(".views-exposed-widget label").each(function(){
    var text = $(this).text();
    _se += '<option value="'+ text +'">'+ text +'</option>';
    _op[$(this).text()] = $(this);
    // Monthly Release,Title,New Provider/Show Name
});


$("#selopt").change(function() {
     _op[$(this).val()].closest('div:hidden').show();
});   

This may have unexpected results if the text of the labels have special characters. In which case we can modify our array a bit more, but still possible.

查看更多
登录 后发表回答