选中复选框时,我尝试在ID为“ pred”的输入字段上应用css('color','red')
。当前代码在选中时已成功禁用输入字段,但是由于某些原因,我无法弄清楚如何在同一代码中应用样式。
我知道如何使用单独的函数执行此操作,但我想知道如何在此代码中执行此操作并了解我做错了什么。
<div class="w3-row">
<div class="w3-col s1">
<label>Za predmet:</label>
<input class="w3-input w3-border w3-light-grey" type="text" required placeholder="Naš broj" style="width: 90%;" name="pred" id="pred" />
</div>
<div class="w3-col s3">
<div style="padding-top: 20px;">
<input class="w3-check" type="checkbox" id="predsvi" name="predsvi" value="da" onclick="var input = document.getElementById('pred'); if(this.checked){ input.disabled = true; input.css('color','red');}else{input.disabled=false; input.focus();}">
<label for="predsvi"> Sve predmete</label>
</div>
</div>
</div>
短代码:
onclick="var input = document.getElementById('pred'); if(this.checked) {
input.disabled = true;
input.css('color','red');}else{input.disabled=false; input.focus();
}
该版本的错误是input.css不是函数。
如果我这样做,我不会出错,但是什么也不会发生。
$('pred').css('color','red')
最佳答案
更改禁用元素的颜色属性是没有意义的。我认为您想更改占位符颜色。
请注意:使用内联JavaScript不是一个好习惯。
然后尝试以下方式:
function myFunc(el){
var input = document.getElementById('pred');
if(el.checked){
input.disabled = true;
input.focus();
input.classList.add('el-color');
}
else{
input.disabled=false;
input.classList.remove('el-color');
}
}
.el-color::placeholder {
color: red;
}
<div class="w3-row">
<div class="w3-col s1">
<label>Za predmet:</label>
<input class="w3-input w3-border w3-light-grey" type="text" required placeholder="Naš broj" style="width: 90%;" name="pred" id="pred" />
</div>
<div class="w3-col s3">
<div style="padding-top: 20px;">
<input class="w3-check" type="checkbox" id="predsvi" name="predsvi" value="da" onclick="myFunc(this)">
<label for="predsvi"> Sve predmete</label>
</div>
</div>
</div>