2

I have a form.When I submit that form the require attribute of the text field of that form should be set to true.I am trying this with javascript.But unable get the positive result.My code is

<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>

in both these methods I am unable to set required to true.any help please...

1 Answers1

1

You can return on form submit like below example. This is reference url.

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

See Demo

With 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>

With 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>
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44