简体   繁体   English

javascript 根据另一个表单域的值隐藏表单域

[英]javascript hide form field based on value of another form field

I have the following two fields on an HTML form:我在 HTML 表单上有以下两个字段:

<input type="hidden" name="Valid" id="Valid" value="True">

<input type="text" id="Address">

I need a JavaScript method that will disable the address input if the value of the valid input is true.我需要一个 JavaScript 方法,如果valid输入的值为 true,它将禁用address输入。

What can I use to do this, please?请问我可以用什么来做到这一点?

I think I need a way of toggling disabled on the Address input form.我想我需要一种在Address输入表单上切换disabled的方法。

You can define a "onchange"-event, which triggers when the value of that hidden input changes.你可以定义一个“onchange”事件,当隐藏输入的值改变时触发。 Here is an example of that: Does HTML Hidden control have any events?下面是一个例子: HTML 隐藏控件是否有任何事件? Like onchange or something? 像 onchange 什么的?

But from reading the comments, that wasn't needed at all:-)但是从阅读评论来看,这根本不需要:-)

What is needed, is a logic which runs on page-load.需要的是在页面加载时运行的逻辑。 Your function only needs to add the disabled-attribute to the field, when the valid-value is true.当有效值为真时,您的 function 只需将 disabled-attribute 添加到该字段。

<input type="hidden" name="Valid" id="Valid" value="True">


<script>
// Define your function
function yourfunc() {
    var validValue = document.getElementById("Valid").getAttribute('value');
    if(validValue == 'True') {
        document.getElementById("Address").setAttribute('disabled', true);
    }
}
yourfunc(); // Call the function: is important, otherwise your code will never be run.
</script>

To remove the disabled-property again, you can check this thread: .setAttribute("disabled", false);要再次删除禁用属性,您可以检查此线程: .setAttribute("disabled", false); changes editable attribute to false 将可编辑属性更改为 false

I need a javascript method that will disable the address input if the value of the valid input is true.我需要一个 javascript 方法,如果有效输入的值为 true,它将禁用地址输入。

Based on this line alone, the below code should work仅基于这一行,下面的代码应该可以工作

const validInput = document.querySelector('#Valid');
const addressInput = document.querySelector('#Address')

const toggleAddress = () => {
    const inputVal = validInput.value;
    
    if(inputVal === 'True') {
            addressInput.disabled = true
    }
}

toggleAddress()

Although your question doesn't say when it should be enabled.尽管您的问题没有说明何时应该启用它。

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

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