繁体   English   中英

使用Javascript选择组合框,更改文本字段的样式

[英]Change style of text field based on the selection of a combo box using Javascript

我想根据在组合框中选择的值来更改文本字段的样式。 具体来说,如果cboSource中选择的选项值为1,我想做的是将txtDepartment字段设置为灰色并标记为“只读”。我已经尝试过下面的代码,但是我想至少我的样式代码是错误的,如果没有其他东西。 任何帮助表示赞赏。 谢谢!

<select name="cboSource" id="cboSource" onClick="displayDepartment(this);">
    <option value = 1>Source 1</option>
    <option value = 2>Source 2</option>
</select>

<input name="txtDepartment" type="text" id="txtDepartment" size="6" maxlength="6"></p>

<script>
function displayDepartment(obj)
{
    var selectedValue = obj.value;
    var txtDepartment = document.getElementById("txtDepartment");


    if (selectedValue == "1") 
    {
        txtDepartment.style.display = "Disabled style='background-color:#E8E8E8'";

    }
}
</script>
txtDepartment.style.backgroundColor = "#E8E8E8";

txtDepartment.disabled = 'disabled';

使用jQuery,您的整个函数会变小很多:

function displayDepartment(obj)
{
    if($(obj).value=="1") {
        $("#txtDepartment").css('background-color','#E8E8E8');
        $("#txtDepartment").disabled ='disabled'
     }
}

首先,在cboSource上使用onchange。

然后:

if(selectedValue == "1")
    txtDepartment.disabled = 'disabled';

设置元素的disabled属性

// on
txtDepartment.setAttribute("disabled","disabled")

// off
txtDepartment.removeAttribute("disabled")

使用jQuery的可能解决方案:

<style>
  .disabled { 
    background-color:#E8E8E8;
  }
</style>

<script language="javascript">

    $(document).ready(function() {
        var txtDepartment = $("#txtDepartment");
        var cboSource = $("#cboSource");

        cboSource.change(function() {
            txtDepartment.removeClass().removeAttr("disabled"); 
            if (cboSource.val() == 1) {
                txtDepartment.addClass("disabled").attr("disabled", true); 
            }
        });
    });

</script>

<select name="cboSource" id="cboSource">
    <option value = 0>Choose</option>
    <option value = 1>Source 1</option>
    <option value = 2>Source 2</option>
</select>

<input name="txtDepartment" type="text" id="txtDepartment" size="6" maxlength="6"></p>

我认为onclick更适合,因为更改对于不同的浏览器具有不同的含义

尝试这个

<select name="cboSource" id="cboSource" onClick="displayDepartment(this);">
    <option value = 1>Source 1</option>
    <option value = 2>Source 2</option>
</select>

<input name="txtDepartment" type="text" id="txtDepartment" size="6" maxlength="6"></p>

    <script>
    function displayDepartment(obj)

    {
        var txtDepartment = document.getElementById("txtDepartment");  
        txtDepartment.disabled = false;  
        txtDepartment.style = "";
        if (obj.value == "1") 
        {
            txtDepartment.style = "background-color:#E8E8E8";
            txtDepartment.disabled = true;  
        }
    }

</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM