0

i tried few days to make this code working but today i got the idea to ask some help. Here is the problem: when i try to send the value of my input fields to my params variable, i just get nothing, an empty value. However when i remove my validation function,

$(document).input.hasAttribute('required').each(function () {
    if ($(this).val() == "") {
        alert('Please fill all the fields');
    }
});

all the parameters are in my url : ?rpt=123456&etc...etc...

Do you know why i loose my variable value on the way? If yes how to solve this?

Thanks for the help

jQuery(document).ready(function() {
  jQuery("#vb_report_date").datepicker({
    format: 'dd/mm/yyyy',
    autoHide: true
  });
  jQuery("#vb_verify_button").click(function() {
    check_required_inputs(true);
  });
});

function check_required_inputs(hasbeenSubmited) {
  var params = "";
  if (hasbeenSubmited) {
    $(document).input.hasAttribute('required').each(function() {
      if ($(this).val() == "") {
        alert('Please fill all the fields');
      }
    });
    params = "?rpt=" + jQuery("#vb_report_no").val() + "&d=" + jQuery("#vb_report_date").val() + "&pin=" + jQuery("#vb_verif_pin").val();
  }
  window.location.href = "verify-reports.php" + params;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body>

  <form id="requiredform" class="verify-box">
    <input type="text" id="vb_report_no" placeholder="Report Number" size="22" data-error="This field is required." class="" required>
    <input type="text" id="vb_report_date" placeholder="Date of Issue" size="12" class="hasDatepicker" data-error="This field is required." required>
    <input type="text" id="vb_verif_pin" placeholder="Verification PIN" size="22">
    <input type="submit" value="Verify" id="vb_verify_button">
  </form>
</body>

</html>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
newbjs
  • 1
  • 2
  • `.hasAttribute('required')` will return a `Boolean` and you can't iterate over it. You must be getting a syntax error with that code. Have you checked the console? – Anurag Srivastava Mar 16 '20 at 08:21
  • Thanks for you answer mate! Required attribute directly on the field not work on all safari browsers, thats why i used js for this, then if i just focus on other browsers so the problem was: the form was submitted right away after displaying quickly: "This field is required".. If i submit it directly i will not have anymore the url and i need this url for the next steps. – newbjs Mar 16 '20 at 08:28
  • @AnuragSrivastava thanks for your answer. no error in the console =/ – newbjs Mar 16 '20 at 08:31
  • Unless you have some other code/third party plugin, the code `$(document).input.hasAttribute` *will* give error: `VM146:1 Uncaught TypeError: Cannot read property 'hasAttribute' of undefined`. Then your function will stop running and the submit of the button will continue (ie the form will submit and reset the page). – freedomn-m Mar 16 '20 at 09:23

2 Answers2

0

To select all required inputs in the document, use $(document).find('input[required]').

Your function should look like:

function check_required_inputs(hasbeenSubmited) {

  // do the check only when hasBeenSubmited
  if (hasbeenSubmited) {

    // assume inputs are filled
    var isValid = true;

    // check required inputs
    $(document).find('input[required]').each(function () {
      // input value is missing
      if ($(this).val() == "") {
        alert('Please fill all the fields');
        isValid = false;
      }
    });

    // do the redirect if isValid
    if (isValid) {
      // make query string
      var params = "?rpt=" + $("#vb_report_no").val() + "&d=" + $("#vb_report_date").val() + "&pin=" + $("#vb_verif_pin").val();

      // do the redirect
      window.location.href = "verify-reports.php" + params;
    }
  }
}
Moutah
  • 332
  • 3
  • 9
  • just tried. Now i got the alert working when fields are empty but automatically redirected to the url with empty parameters rpt=&d=&pin=. But once i fill paramters so im redirected to the same page without parameters only a question mark: ? – newbjs Mar 16 '20 at 08:53
  • There should be validation logic involved to check if inputs are filled. I've updated my answer, adding some logic to do the redirect only if required inputs are filled. Feel free to adjust to your needs. – Moutah Mar 16 '20 at 09:03
  • With your new edit i progressed a lot, now after the alert we are not forcing anymore the redirect after check as we have the if statement. Thanks But unfortunately, the redirect not work, we still have nothing as parameters only a question mark : ? – newbjs Mar 16 '20 at 09:06
  • Are you sure that ```params``` is properly formatted? What do you get when doing ```console.log(params)``` instead of the redirect? Maybe the ids are incorrect? Is the date (#vb_report_date) properly formatted? Also, as a general consitency concern, I'd suggest using ```$``` everywhere instead of ```jQuery```. – Moutah Mar 16 '20 at 09:10
  • Ok thanks for advices. I tried to replace by a console log as you suggested but not any new line appears once submitted. So nothing happened but we have a kind of redirection then the ? is added to the url then we come back to the form. – newbjs Mar 16 '20 at 09:19
0

You can use onsubmit method.

<form id="requiredform" class="verify-box" onsubmit="return getdata()" >
    <input type="text" id="vb_report_no" placeholder="Report Number" size="22" data-error="This field is required." class="" required>
    <input type="text" id="vb_report_date" placeholder="Date of Issue" size="12" class="hasDatepicker" data-error="This field is required." required>
    <input type="text" id="vb_verif_pin" placeholder="Verification PIN" size="22">
    <input type="submit" value="Verify" id="vb_verify_button">
</form>

function getdata() {
  check_required_inputs(true);
}

Try querySelectorAll with an attribute selector to get all required inputs in the document.

document.getElementById('requiredform').querySelectorAll("[required]")

Now function will be like this,

function check_required_inputs(hasbeenSubmited) {
  var params = "";
  console.log(hasbeenSubmited)
  if (hasbeenSubmited) {
     document.getElementById('requiredform').querySelectorAll("[required]").forEach(function (element) {
       if ($(element).val() == "") {
          alert('Please fill all the fields');
       }
     });
  params = "?rpt=" + jQuery("#vb_report_no").val() + "&d=" + jQuery("#vb_report_date").val() + "&pin=" + jQuery("#vb_verif_pin").val();
  }
 window.location.href = "verify-reports.php" + params;

}

For more details: how to get value from a form before submit

Check the working snippet here..

    function check_required_inputs(hasbeenSubmited) {
      var params = "";
      console.log(hasbeenSubmited)
      if (hasbeenSubmited) {     
     document.getElementById('requiredform').querySelectorAll("[required]").forEach(function (element) {     
     if ($(element).val()== "") {
      alert('Please fill all the fields');
     }     
        });
     params = "?rpt=" + jQuery("#vb_report_no").val() + "&d=" + jQuery("#vb_report_date").val() + "&pin=" + jQuery("#vb_verif_pin").val();
      }
     console.log(params);
    window.location.href = "verify-reports.php" + params;
   }

function getdata() {
  check_required_inputs(true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    
<form id="requiredform" class="verify-box" onsubmit="return getdata()" >
 <input type="text" id="vb_report_no" placeholder="Report Number" size="22" data-error="This field is required." class="" required>
 <input type="text" id="vb_report_date" placeholder="Date of Issue" size="12" class="hasDatepicker" data-error="This field is required." required>
 <input type="text" id="vb_verif_pin" placeholder="Verification PIN" size="22">
 <input type="submit" value="Verify" id="vb_verify_button">
</form>
Jeni
  • 320
  • 2
  • 12
  • Hi thanks for your answer, tried but it not works. Url still empty – newbjs Mar 16 '20 at 08:50
  • pass element variable on foreach loop, you will get value by using $(element).val() – Jeni Mar 16 '20 at 08:57
  • thanks but still same issue with this new edits: i don't have the alert and not the parameters too once fields are filled and form submitted. I just have a question mark after url (don't have rpt=&d=&pin= neither rpt=XXXX&d=XX/XX/XXXX&pin=XXX – newbjs Mar 16 '20 at 08:58
  • you can't submit the form if the required fields has empty values. Therefore you won't receive alert box anymore – Jeni Mar 16 '20 at 09:03
  • right. after tested your code, we are not redirected automatically after empty fields and get the alert. But redirection still not have any parameters unfortunately only a question mark: ? – newbjs Mar 16 '20 at 09:13
  • thanks a lot but still have the problem. I tried the code in jsfiddle, it works too. But not on my server. Unbelievable. I tried to deactivate the htaccess in case but still not work im still redirected to the same form nce everything filled and nothing in the url. – newbjs Mar 16 '20 at 09:38
  • Just tried in http https too but still the same issue – newbjs Mar 16 '20 at 09:49
  • checkes yes, i even tried to copy paste the jsfiddle code to my page and its not work. Ill try to put the code in another server for check, ill update you soon – newbjs Mar 16 '20 at 10:17