开发者

onkey event - problem with disabled button

Explanation: At the beginning the value of the field is YYYY-MM-DD. if the user delete the value and doesn't type anything, the button "ok" should be disabled. if the user delete the value and type new value, the button "ok" should be enable. The code is working only for the second case.

function ChangeOkButton()
   {
     if(document.getElementById('fromDate').value == null)
        {  document.getElementById('save').disabled = true;  }
     else {document.getElementById('save').disabled = false;  }
   }  

<input type="text" name="fromDate" id="fromDate" value="YYYY-MM-DD" onkeypress="ChangeO开发者_运维百科kButton();"/>

Is this possible?

Thank you!


That function is not very useful for that kind of control, since you could overwrite the value with '12345', 'foobar' or something else different than a realistic value. I suppose you want date starting from 2000-01-01

function ChangeOkButton(field) {
   var okbtt = document.getElementById('save');
   if ((/^(YYYY\-MM\-DD|2\d{3}\-(0[1-9]|1[0-2])\-(0[1-9]|[12]\{d}|3[01]))$/).test(field.value)) {
      okbtt.removeAttribute('disabled');
   }
   else {
      okbtt.disabled = 'disabled';
   }
}  

and your input is

<input type="text" name="fromDate" id="fromDate" value="YYYY-MM-DD" onkeyup="ChangeOkButton(this);"/>

Please note I've not considered leap years or days per month, this is only a more reliable control on data type entered by the user. Change the regexp as you like

Note: consider to put the 'okbtt' variable outside to the function for a matter of performance, otherwise you need to obtain a reference each time you call this function. awful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜