无法使用javascript将必需属性设置为true

时间:2018-03-31 12:07:37

标签: javascript

我有一个表单。当我提交该表单时,该表单的文本字段的require属性应该设置为true。我正在尝试使用javascript.But无法得到肯定的结果。我的代码是

<html>
    <head>
        <script>
        function validate()
        {
            alert("ok");
            document.getElementById("sample").required = true;//method-1

      document.getElementById("sample").setAttribute("required","")//method-2
        }
        </script>
    </head>
    <body>
        <form method="post" action="" onsubmit="validate()">
            <input type="text" id="sample">
            <input type="submit" value="submit">
        </form>
    </body>
 </html>

在这两种方法中,我都无法将其设置为true。请帮助...

1 个答案:

答案 0 :(得分:0)

您可以像下面的示例一样返回表单提交。这是参考url

<form name="myForm" action="/action_page.php"onsubmit="return validateForm()" method="post">

参见演示

  

使用element.required = true;

function validate() {
  var el = document.getElementById("sample");
  if (el.value) {
    alert(el.value);
    return true;
  } else {
    alert('Value is required..');
    el.required = true; //method-1
    return false;
  }
}
<form method="post" action="#" onsubmit="return validate()">
  <input type="text" id="sample">
  <input  type="submit" value="submit">
</form>

  

使用element.setAttribute(“required”,“”);

function validate() {
  var el = document.getElementById("sample");
  if (el.value) {
    alert(el.value);
  } else {
    alert('Value is required..')
    el.setAttribute("required", "");
    return false;
  }
}
<form method="post" action="" onsubmit="return validate()">
  <input type="text" id="sample">
  <input  type="submit" value="submit">
</form>