2016-09-27 12 views
-5

ページ上の要素を入力テキストフィールドからJavaScriptでオプション要素を選択するように変更することはできますか?JavaScript変更入力テキスト選択オプション

greasemonkeyで一部のページをカスタマイズします。

+0

はい、可能です。あなたはまだ試しましたか? –

+0

はい。これを行う方法はたくさんあります。 SOは具体的な実装上の問題ではありません。行って自分で実装しようとすると、より具体的な問題に戻ります。 – Aeolingamenfel

+0

いいえ、不可能です。要素tagNameを変更することはできませんが、別の要素と置き換えることはできます。 – adeneo

答えて

2

フォームと入力要素(名前またはIDのいずれか)を識別する必要があります。新しいselect要素を作成し、それに多くの要素を作成して追加し、最後に既存のテキスト入力要素の場所に挿入する必要があります。

あなたは、例えば、このようなものを使用することができます

// ** change 'form' and 'text' to correctly identify the form and text input element ** 
var inputElement = document.forms['form'].elements['text']; 
var selectElement = document.createElement('select'); 

// get the existing input element's current (or initial) value 
var currentValue = inputElement.value || inputElement.getAttribute('value'); 

// add a list of options to the new select element 
// ** change value/text and add/remove options as needed ** 
var options = [{value: 'option1', text: 'Option 1'}, 
       {value: 'option2', text: 'Option 2'}, 
       {value: 'option3', text: 'Option 3'}]; 

options.forEach(function (option, i) { 
    var optionElement = document.createElement('option'); 
    optionElement.appendChild(document.createTextNode(option.text)); 
    optionElement.setAttribute('value', option.value); 
    selectElement.appendChild(optionElement); 

    // if the option matches the existing input's value, select it 
    if (option.value == currentValue) { 
     selectElement.selectedIndex = i; 
    } 
}); 

// copy the existing input element's attributes to the new select element 
for (var i = 0; i < inputElement.attributes.length; ++ i) { 
    var attribute = inputElement.attributes[i]; 

    // type and value don't apply, so skip them 
    // ** you might also want to skip style, or others -- modify as needed ** 
    if (attribute.name != 'type' && attribute.name != 'value') { 
     selectElement.setAttribute(attribute.name, attribute.value); 
    } 
} 

// finally, replace the old input element with the new select element 
inputElement.parentElement.replaceChild(selectElement, inputElement); 

それはすでにそれに接続されている多くのスクリプトなしの通常のフォーム要素だ場合、それはかなり簡単です。ただし、テキスト要素(フォーカス、変更、ぼかしなど)に添付されたスクリプトイベントがあった場合、それ以上は機能しません。 select要素に似たスクリプトイベントが必要な場合は、それらのイベントを書き換えて、代わりに適用する必要があります。

新しいselect要素は、元のinput要素とは異なるサイズ/スタイルである可能性があります。デフォルトの外観が気に入らなければ、新しい要素のスタイルを変更するコードを追加することができます。

関連する問題