我的代码在外部文件<script src="action_input.js"></script>
中无效
我将此代码放在<body></body>
或<head></head>
中,但它无效。
我的代码在<body><script> code js</script></body>
中运行,但不是这样。
我的代码是:
// identify form elements:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate() {
// show verification result:
if(search_code.value == insert_code.value) {
result.textContent = 'cod gasit';
result.className = "ok";
audio.play(); //http://soundbible.com/tags-winning.html
} else {
result.textContent = 'codul nu este corect';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
//sterge textul cand se da click pe input
function clearField(input) {
input.value = "";
};
我的意见是:
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
答案 0 :(得分:0)
使用
e.preventDefault();
阻止submit button
的默认操作或使用type='button'
没有标识为result
试试这个:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'cod gasit';
result.className = "ok";
audio.play(); //http://soundbible.com/tags-winning.html
} else {
result.textContent = 'codul nu este corect';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
//sterge textul cand se da click pe input
function clearField(input) {
input.value = "";
};
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value="" />
<br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value="" />
<br/>
<br/>
<div id="result"></div>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>