无法更改输入的contentEditable和value?

时间:2017-03-11 04:23:20

标签: javascript html

我正在尝试将输入更改为contenteditable = false(最好)或在选择框的选项=是时禁用。

我有if语句,然后是每个case的switch语句,但是当我尝试更改输入contenteditable或值时,没有任何变化。

为什么输入没有变为contenteditable = false且值设置为0?

HTML:
<input type="text" id="ca1"></input>

<select id="ns1" onchange="test(this)">
        <option value="default" id="default" selected></option>
        <option value="yes">yes</option>
        <option value="no">no</option>
</select>

js:

function test(el)
{
  //if select box = yes, change contenteditable = false for cash and tip
  //and set values of cash and tip to 0
  if (el.value === "yes")
  {
    console.log("yes");

    //find what row has 'yes'
    var regex = /(\d+)/g;
    var string = el.id;
    var rowNumber = string.match(regex).toString();
    console.log(rowNumber);

    //make cash and tip contenteditable = false, change values to 0
    switch(rowNumber)
    {
      case 1:
        var ca1 = document.getElementById("ca1");
        ca1.value = 0;
        ca1.contentEditable = false; //.disabled = false doesn't work either
        break;
      case 2:
        //
        break;
      case 3:
        //
        break;
      case 4:
        //
        break;
      case 5:
        //
        break;
      default:
        //
    }
  }
  else
  {
    console.log("no");
  }
}

2 个答案:

答案 0 :(得分:1)

因为您正在将字符串与数字进行比较。

改变这个:

var rowNumber = string.match(regex).toString();

var rowNumber = parseInt(string.match(regex).toString());

工作Fiddle

答案 1 :(得分:0)

1)只需在开关案例中使用Number()

2)使用disabled

添加属性setAttribute()

&#13;
&#13;
function test(el)
{
  //if select box = yes, change contenteditable = false for cash and tip
  //and set values of cash and tip to 0
  if (el.value === "yes")
  {
    console.log("yes");

    //find what row has 'yes'
    var regex = /(\d+)/g;
    var string1 = el.id;
    alert(string1);
    var rowNumber = string1.match(regex).toString();
    console.log(rowNumber);

    //make cash and tip contenteditable = false, change values to 0
    switch(Number(rowNumber))
    {
      case 1:
        alert("1111");
        var ca1 = document.getElementById("ca1");
        ca1.value = 0;
        //ca1.contentEditable = false; //.disabled = false doesn't work either
       ca1.setAttribute("disabled", true);
        break;
     
      default:
        
    }
  }
  else
  {
    console.log("no");
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ca1"></input>

<select id="ns1" onchange="test(this)">
        <option value="default" id="default" selected></option>
        <option value="yes">yes</option>
        <option value="no">no</option>
</select>
&#13;
&#13;
&#13;