2017-02-04 11 views
1

Возможно ли это ?:как иметь различные значения для <option> на фокус и вне фокуса Javascript

enter image description here

У меня есть:

var titles = ["opt1 (beginner)", "opt2 (intermediate)", "opt3 (prof)"] 
 
var select = document.getElementById('select'); 
 
for (i = 0; i < titles.length; i++) { 
 
    var option = document.createElement("option"); 
 
    option.textContent = titles[i]; 
 
    select.append(option); 
 
} 
 
select.options[select.selectedIndex].innerHTML = "option1" 
 

 
select.onfocus = function(){ 
 
for (i = 0; i < titles.length; i++) { 
 
    select.options[i].textContent = titles[i]; 
 
} 
 
};
<select id="select"></select>

Это показывает мне с значениями опций, определенными в заголовках.

Когда <select> находится в фокусе, он должен показать мне полные значения, определенные в заголовках, тогда как, когда выбор не находится в фокусе, я хочу, чтобы он показывал что-то другое, поэтому в этом случае опция1 вместо opt1 (новичок).

Я попытался добавить это:

select.options[select.selectedIndex].innerHTML = "option1" 

select.onfocus = function(){ 
for (i = 0; i < titles.length; i++) { 
    select.options[i].textContent = titles[i]; 
} 
}; 

, а также пытались OnChange события, но ничего не работает до сих пор.

вот fiddle

+2

Не используйте внешнюю скрипку, используйте [Stack Snippets] (https://stackoverflow.blog/2014/09/introducing-runnable-javascript -css-and-html-code-snippets /) – Barmar

+1

Что-то вроде этого? https://jsfiddle.net/c52Lh5md/2/ – charlietfl

+0

точно!, безукоризненное спасибо, если вы разместите его в качестве ответа, я приму его – Tom

ответ

1

Да, это возможно. Используйте событие onblur http://www.w3schools.com/jsref/event_onblur.asp. Вот пример, основанный на вашей скрипке:

var titlesBlur = ["option 1", "option 2", "option 3"]; 
select.onblur = function(){ 
select.options[select.selectedIndex].innerHTML = titlesBlur[select.selectedIndex]; 
} 
1

Что-то, как это должно работать:

var titles = { 
 
    'opt1 (beginner)' : 'option1', 
 
    'opt2 (intermediate)' : 'option2', 
 
    'opt3 (prof)' : 'option3' 
 
}; 
 

 
var select = document.getElementById('select'); 
 

 
for (var title in titles) { 
 
    var option = document.createElement("option"); 
 
    option.textContent = title; 
 
    select.append(option); 
 
} 
 

 
select.onfocus = function() { 
 
    var i = 0; 
 
    for (var title in titles) { 
 
    select.options[i++].textContent = title; 
 
    } 
 
} 
 

 
select.onblur = function() { 
 
    select.options[select.selectedIndex].innerHTML = titles[select.value]; 
 
}
<select id="select"></select>

0

Вы также можете попробовать использовать JQuery, следующим образом:

Javascript

var options = [ 
    {value: '1', off: 'Option 1', on: 'Opt 1'}, 
    {value: '2', off: 'Option 2', on: 'Opt 2'}]; 

$(function(){ 
    var $select = $('#dynamic-select'); 
    // create options 
    $.each(options, function(index, elem) { 
     $('<option>').val(elem.value).text(elem.off).appendTo($select); 
    }); 

    $('#dynamic-select').focus(function(){ 
     // when focused, alternate text to property 'on' 
     alternateText('on'); 
    }).blur(function(){ 
     // when blur occurs, alternate text to property 'off' 
     alternateText('off'); 
    }).change(function(){ $select.blur();}); 
}); 

function alternateText(property) { 
    $.each(options, function(index, elem) { 
      $('#dynamic-select option:eq(' + (index+1).toString() + ')').text(elem[property]); 
    }); 
}; 

HTML

<select id="dynamic-select"> 
    <option selected="selected">choose...</option> 
</select> 

Working JSFiddle