Home > database >  Jquery validation check
Jquery validation check

Time:02-02

Im working on creating a form and saving it into a DB,

i have multiple fields ( text fields, date fields etc )

which works fine!, however i want it to check if its empty or not, if its empty it shouldn't continue,

i know it's better to make it in a form but it there anyway to do it without using a form?

a solution would be to check if the fields are empty and if they are the button is disabled, if every field is filled in than it's enabled,

Below is my jquery code

$('#savert').click(function(){
  
      $.ajax({
                 type: "POST",
                 dataType: "JSON",
                 url: "update.php",
                 data: {
                     name: $("#name").val(),
                     date: $("#date").val(),
                     complaint: $("#complaint").val(),
                     material: $("#material").val(),
                     id: complaint_id,
                     approval_ms: $("#approval_ms").val(),
                     amount: $("#amount").val(),
                     pallets: $("#pallets").val(),
                     topic: $("#topic").val()
                 },
                 success: function (data) {
                   console.log("Succes")
                   console.log( $("#approval_ms").val())
                   console.log($("#complaint").val())
                //    window.location = origin   '/?page=retour_form_details&id='   complaint_id;
                   event.preventDefault();

                 },
                 error: function () {
                     console.log("failed..")
                     alert('better check you self before you hurt yo self')
                 }

             });
});

CodePudding user response:

You can either block your form submission, or inrtercept button submit click (like your code does). In the latter case:

$('#savert').click(function(){
    if ($('element').val() != '') { // or other check
        $.ajax({ ... })
    }
      
});

CodePudding user response:

the solution is to check every field in your post and i have created a quick function that will return the post data or false if any is empty

            function preparePostData() {
                var data = {
                    name: $("#name").val(),
                    date: $("#date").val(),
                    complaint: $("#complaint").val(),
                    material: $("#material").val(),
                    id: complaint_id,
                    approval_ms: $("#approval_ms").val(),
                    amount: $("#amount").val(),
                    pallets: $("#pallets").val(),
                    topic: $("#topic").val()
                };

                var isEmpty = Object.values(data).every(x => x === null || x === '');
                return isEmpty ? false : data;
            }

now conditionally use this preparePostData function in your click handler

            $('#savert').click(function () {

                var data = preparePostData();
                if (data) {
                    $.ajax({
                        type: "POST",
                        dataType: "JSON",
                        url: "update.php",
                        data: data,
                        success: function (data) {
                            console.log("Succes")
                            console.log($("#approval_ms").val())
                            console.log($("#complaint").val())
                            //    window.location = origin   '/?page=retour_form_details&id='   complaint_id;
                            event.preventDefault();

                        },
                        error: function () {
                            console.log("failed..")
                            alert('better check you self before you hurt yo self')
                        }

                    });
                }
            });

finally you can try adding change handler to enable or disable the save/submit button

            $("#name, #date, #complaint, #material, #approval_ms, #amount, #pallets, #topic").change(function () {
                if (preparePostData()) {
                    ('#savert').prop('disabled', false);
                } else {
                    ('#savert').prop('disabled', true);
                }
            });

CodePudding user response:

Here's something for you to play around with.

//here we have an array that will contain values for each field
var fields = ['name', 'date', 'complaint','material','approval','amount','pallets','topic'];

$('.submit').on('click',function(e){
  //firstly, we get the total number of fields we want to submit, minus by one which is the submit button and we dont want to submit the submit button value
  const inputFields = $(this).parent('div').children().length - 1;
  //the for loop uses the numerical class names to loop through each field... you can use foreach for this but I prefer giving input fields numerical class names and use a forloop instead
  for(let i = 0; i < inputFields; i  ){
    //for each field we loop through we firstly assign its value to the matching name in the fields array
    fields[i] = $('.' i).val();
    //then if that input field does not have a value
    if($('.' i).val() == ''){
      //firstly we add the `empty` class to that empty input field so that it gets a red border
      $('.' i).addClass('empty');
      //then after 3 seconds we remove that class
      setInterval(() => {
        $('.' i).removeClass('empty');
      },3000);
      //then we get the name attribute of that input field
      let fieldName = $('.' i).attr('name');
      //and use it to create an error message which we display on the h5 elements in the HTML markup
      $('h5').text(fieldName   ' field requires a value');
      //we then use `break;` keyword to exit the for loop
      break;
      //else if no input field with no value is found and the for loop have reached its maximum value, which is 7, we run the else-if statement below
    }else if(i == 7){
    //i used this forloop and console.log to display all the values i have to submit
      for(let x = 0; x < fields.length; x  ){
        console.log(fields[x]);
      }
      //this is the function we calling and passing the array of provided values which we will submit via ajax
      submitValues(fields);
    }
    
  }
});

function submitValues(fields){
  $.ajax({
    //type
    //dataType
    //url
    data: {
      name: fields[0],
      date: fields[1],
      complaint: fields[2],
      material: fields[3],
      id: complaint_id,
      approval_ms: fields[4],
      amount: fields[5],
      pallets: fields[6],
      topic: fields[7],
    }
  });
}
div>input, textarea {
  display:flex;
  margin-top: 10px;
}

h5 {
  color: black;
  font-size: 18px;
  font-weight: bold;
}

.empty {
   border: 2px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text"  name="name" placeholder="Name"/>
<input type="date"  name="date"/>
<textarea  row="3" name="complaint" placeholder="Complaint..."></textarea>
<input type="text"  name="material" placeholder="Material"/>
<input type="text"  name="approval" placeholder="Approval"/>
<input type="number"  name="amount" placeholder="Amount"/>
<input type="text"  name="pallets" placeholder="Pallets"/>
<input type="text"  name="topic" placeholder="Topic"/>
<input type="submit"  name="name" value="Submit"/>
</div>

<h5></h5>

  •  Tags:  
  • Related