简体   繁体   中英

Edit sliding html menu with javascript

I'm using a sliding menu (select/object html one), which is generated dynamically by taking data from a DB, using a jsp page.

I also have an input text field, where I can search things from the sliding menu. I want to write the root of a word that is contained in my menu, and my menu must "resize" showing all the items with the root that I've wrote, and only those ones.

I can't use server side operations (like sending data via post) but I need to solve this client side (because I need this result immediately).

Can I maybe solve this problem only with an onclick event applied to a button? And how?

See this demo: http://jsfiddle.net/UKseV/8/

As it is not possible to hide an <option> with display:none (demo: http://jsfiddle.net/UKseV/ -style is added correctly, but it does not work), I clone select object to store initial options as they will be removed from initial object. And later I'm using that cloned object to filter options and add those that match my condition to initial object. Here is a code:

HTML:

<select multiple id="testSelect">
<option>test</option>
<option>temp</option>
<option>cast</option>
<option>dest</option>
<option>inst</option>
</select>

<input type="text" value="" onkeyup="searhSelect(this)" />​

searhSelect function will be called on each key press (when user release a key actually) and will filter #testSelect object.

JS:

var optionsList;
function searhSelect(el) {
    var select = document.getElementById('testSelect');
    if(!optionsList) {        
        optionsList = select.cloneNode(true);  //copy select to a variable for future use      
    }
    select.innerHTML = "";//remove all options.

    for(var i =0; i < optionsList.options.length; i++) {
        var opt = optionsList.options[i];
        if((opt.innerText || opt.textContent).indexOf(el.value) != -1) {
            select.appendChild(opt.cloneNode(true));
        } 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM