我正在制作一个表单,并将输入字段设置为仅使用 JavaScript 进行读取。我更改了只读属性的默认颜色。我想在字段为只读时显示默认值,即“NIL”
HTML
<input type="radio" name="sex" value="male">Male<br/>
<input type="radio" name="sex" value="female">Female <br/>
Age:<input type="text" name="age" id="age" size="20">
Hobbies:<input type="text" name="hobbies" id="hobbies" size="20"><br/>
Phone:<input type="text" name="phone" id="phone" size="20"><br/>
JS
$("input[name='sex']").change(function() {
if($(this).val() == "female") {
$("#age,#phone").attr("disabled", true).css("background-color","#0F0");
} else if($(this).val() == "male") {
$("#age,#phone").attr("disabled", false).css("background-color","#FFF");;
}
});
如果该字段是只读的,我想添加默认值“Nil”。请指导我如何将此属性添加到我的脚本中。
最佳答案
要为所有具有readonly
属性的元素赋予值“Nil”,您可以使用[readonly]
attribute selector像这样:
$('[readonly]').val('Nil');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" readonly />
<input type="text" />
在执行此操作之前,您可能需要首先确保元素的值为空。为此,您需要引入 filter()
像这样:
$('[readonly]').filter(function() {
return this.value == ""
}).val('Nil');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" readonly />
<input type="text" value="Has a value" readonly />
<input type="text" />
关于javascript - 想要通过 JavaScript 设置输入字段的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26400022/