Make the first option to select unselectable using the arrow keys in Google Chrome

I have a choice with parameters, and when the user selects a parameter, it is removed from the selection and displayed as a button. When the button is pressed, the option returns to my selection. Everything works fine with a click of the mouse, but if we move with the arrow key, the user can select my first option, which will "choose fruits." How to make it unselectable? disabled = "disabled" does not work. Here's the jsfiddle http://jsfiddle.net/gbjcw1wp/2/ . To reproduce the problem, select the fruit, then press the up arrow key on the keyboard.

EDIT: ONLY GOING ON GOOGLE CHROME.

Disabling the arrow keys, but I would like another way to accomplish this.

HTML:

<select id="combobox" onchange="cbchange();">
    <option selected="selected">Choose Fruit</option>
    <option value="apple">apple</option>
    <option value="pear">pear</option>
    <option value="orange">orange</option>
    <option value="banana">banana</option>
</select>
    <br>
    <br>
 <div id="buttons"></div>

Javascript:

var fieldnames = [];
var valuenames = [];  
function sortComboBox() {
    document.getElementById("combobox").remove(0);
    var my_options = $("#combobox option");
    my_options.sort(function (a, b) {
        if (a.text.toUpperCase() > b.text.toUpperCase()) return 1;
        if (a.text.toUpperCase() < b.text.toUpperCase()) return -1;
    return 0;
    });
    $("#combobox").empty().append('<option>Choose Fruit</option>').append(my_options);
    $('#combobox option:first-child').attr("selected", "selected");
}  
function cbchange() {
    var index = $('#combobox').get(0).selectedIndex;
    var text = $('#combobox option:selected').text();
    var selectedItem = $('#combobox').val();
    $('#buttons').append('<table class="ui"><tr><td class="variable">' + text + '</td><td class="icon"><span id="' + selectedItem + '" class="icon ui" value="X" onclick="addOption(\'' + text + '\',this.id)">X</span></td></tr></table>');
    $('#combobox option:eq(' + index + ')').remove();
    fieldnames.push(text);
    valuenames.push(selectedItem);
}
function addOption(text, selectedItem) {
    for (var i = valuenames.length - 1; i >= 0; i--) {
        if (valuenames[i] === selectedItem) {
            valuenames.splice(i, 1);
            fieldnames.splice(i, 1);
        }
    }
    $("#combobox").append($("<option></option>").val(selectedItem).text(text));
    $('#' + selectedItem).parent().parent().parent().parent().remove();
    sortComboBox();
}
+4
source share
1 answer

Just changing your code can solve your problem.

Give the default options some kind of weird value. For instance:

<option value="null" selected="selected">Choose Fruit</option>

And add the following code to the top of your cbchange () function.

if($('#combobox').val()=="null"){
        return false;
    }

See jsfiddle example

+2
source

All Articles