使用按钮更改元素的值

时间:2019-04-30 12:20:59

标签: javascript html

我正在尝试通过单击按钮来禁用/启用输入行

我可以在输入行中手动输入单词“ closed”,它可以正常工作,但是我无法通过按钮输入“ closed”

       var obj = document.getElementById("state");    
       obj.onchange = function(status){
         if(this.value=="closed"){
            document.getElementById("test").disabled = 'disabled';

         }else{
            document.getElementById("test").disabled = '';
         }
       }
    <button id="state" name="state" type="submit" value="open">open</button>
    <button id="state" name="state" type="submit" value="closed">closed</button> 
    <input id="test"/>

输入id = state行工作正常,但是当我单击按钮时没有任何反应

3 个答案:

答案 0 :(得分:0)

也许您想要切换?

window.addEventListener("load", function() {
  document.getElementById("state").addEventListener("click", function(e) {
    e.preventDefault(); // not really needed on type="button"
    var closed = this.value == "closed";
    this.value = this.innerText = closed ? "open" : "closed";
    document.getElementById("test").disabled = closed;
  })
})
<button id="state" name="state" type="button" value="open">open</button>
<input id="test" />

答案 1 :(得分:0)

尝试这样的事情,

var buttonClick = function(status) {
  if (status == "closed") {
    document.getElementById("test").disabled = true;
  } else {
    document.getElementById("test").disabled = false;
  }
}
<button id="openState" name="OpenState" type="submit" value="open" onclick="buttonClick(value)">open</button>
<button id="closedState" name="ClosedState" type="submit" value="closed" onclick="buttonClick(value)">closed</button>

<input id="test" />

答案 2 :(得分:0)

有几件事要考虑:

  • 您不能多次使用相同的ID(状态)
  • 按钮不会对onChange做出反应,但会对onClick
  • 做出反应
  • 您可以直接使用onClick HTML属性

function disableInput(disabled){
  document.getElementById("test").disabled = disabled
}
<button onClick="disableInput(false)">open</button>
<button onClick="disableInput(true)">closed</button>

<input id="test" />