幼稚園時代「何組」でしたか?

下記のようなコードでイベントを発生したいと考えています。
キーボードによる打ち込みではなく、文章をコピー&ペーストすることで
「firstBox2」の表示を消し、「secondBox2」を表示させたいと考えています。

ご教授お願いします。

<input id="target_input" type="text" value="" />

<select id="firstBox2">
<option value="select1">-----</option>
<option value="select2">------</option>
</select>

<select id="secondBox2" style="display:none;">
<option value="select1">午前中</option>
<option value="select2">2度目以降の利用</option>
</select>

<script type="text/javascript">
var timer = null;

var input = document.getElementById("target_input");

var prev_val = input.value;

input.addEventListener("focus", function(){
window.clearInterval(timer);
timer = window.setInterval(function(){
var new_val = input.value;
if(prev_val != new_val){
document.getElementById('firstBox2').style.display = "none";
document.getElementById('secondBox2').style.display = "";
};
prev_value = new_value;
}, 10);
}, false);

input.addEventListener("blur", function(){
window.clearInterval(timer);
}, false);
}
</script>

A 回答 (2件)

xxx.style.display = ""; //?



<style>
xxx { display:; } /* ? */
</style>

--
input.value = '0';
if (input.value) {
;// ?
}
    • good
    • 0

よくわかりませんが、とりあえずご提示の内容で…




・スクリプトの最後の「}」が余分
・prev_value = new_value; の行で、未定義変数参照のエラーになっている
を修正すれば動作すると思われます。

ついでに、余計なお世話ですが…
全体でやっていることは、selectの表示切替えを1回だけ行っているというもので、それでよいのであれば、最初の値の変化を取得できさえすれば良いと考えられます。
・focusやblurで処理する必要はなく、selectを切り替えたらsetIntervalを止めればよい
・prev_valやnew_valで値を控えているが、初期値と変わったことを判定条件にすれば
 if(input.value){~~}
 のような条件でも十分です。(値を控えておく必要がなくなる)
・控えがいらないので、現在エラーとなっている、prev_value = new_value;なども不要

あと、setIntervalのintervalはもう少し時間をとっても良いかも…


てなことを反映するとこんな感じでも、ご提示の処理は可能かと…
var input = document.getElementById("target_input");
var timer = setInterval(function(){
 if(input.value){
  clearInterval(timer);
  document.getElementById('firstBox2').style.display = "none";
  document.getElementById('secondBox2').style.display = "";
 };
}, 50);
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!


おすすめ情報