0

I am a beginner in programming. My code has a lot of errors and any help will be welcome. First I'm trying to write a function on the JavaScript file where it is sending the data to the back-end, I have posted a snippet to my front-end to help visualize what I am trying to achieve.

Basically, I want to send some data, but before the back-end receive the data I would like to validate the data, and send an error to the user informing what is wrong with the input field.

Quantity(indivQty) should be ONLY int more than 0 and less than the stockIndivQty.

Function to send/save the data:

        async function saveTransfer(){

    //ID (inventorylocation table)
    let invLocId = document.querySelector('#itemID span').textContent;
    console.log('invLocId: '+invLocId);
    // Item SKU
    let customSku = document.querySelector('#sku span').textContent;
    console.log('itemSku: '+customSku);
    // Type
    let invType = document.querySelector('#type span').textContent;
    console.log('type: '+invType);
    // InvID
    let invId = document.querySelector('#invID span').textContent;
    console.log('Inventory ID: '+invId);
    let stockIndivQty = document.querySelector('#indivQty span').textContent;

    let trs = document.querySelectorAll('.rows .row');
    let locations = [];

    for(let tr of trs) {
        let location = {};
        location.indivQty =  tr.querySelector('.quantity').value;
        location.locationName =  tr.querySelector('.input-location').value;
        locations.push(location);
    }
    console.log('locations: '+locations);

    let formData = new FormData();
    formData.append('invLocId', invLocId);
    formData.append('customSku', customSku);
    formData.append('locations', JSON.stringify(locations));
    formData.append('invType', invType);
    formData.append('invId', invId);

    let response = await fetch(apiServer+'itemTransferBay/update', {method: 'POST', headers: {'DC-Access-Token': page.userToken}, body: formData});
    let responseData = await response.json();

    if (!response.ok || responseData.result != 'success') {     
        window.alert('ERROR');
    } else {
        window.alert('teste');
        location.reload();
            }
}

window.addEventListener("load", () => {
  let elTotalQuantity = document.querySelector("#totalqty");
  let totalQuantity = parseInt(elTotalQuantity.innerHTML);
  
  function getSumOfRows() {
    let sum = 0;
    for (let input of document.querySelectorAll("form .row > input.quantity"))
      sum += parseInt(input.value);
    return sum;
  }
  function updateTotalQuantity() {
      elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
  }
  
  function appendNewRow() {
    let row = document.createElement("div");
    row.classList.add("row");
    let child;
    
    // input.quantity
    let input = document.createElement("input");
    input.classList.add("quantity");
    input.value = "0";
    input.setAttribute("readonly", "");
    input.setAttribute("type", "text");
    row.append(input);
    
    // button.increment
    child = document.createElement("button");
    child.classList.add("increment");
    child.innerHTML = "+";
    child.setAttribute("type", "button");
    child.addEventListener("click", () => {
      if (getSumOfRows() >= totalQuantity) return;
      input.value++;
      updateTotalQuantity();
    });
    row.append(child);
    
    // button.increment
    child = document.createElement("button");
    child.classList.add("decrement");
    child.innerHTML = "-";
    child.setAttribute("type", "button");
    child.addEventListener("click", () => {
      if (input.value <= 0) return;
      input.value--;
      updateTotalQuantity();
    });
    row.append(child);
    // label.location
    child = document.createElement("label");
    child.classList.add("location-label");
    child.innerHTML = "Location: ";
    row.append(child);

    // input.location
    let input2 = document.createElement("input");
    input2.classList.add("input-location");
    input2.value = "";
    input2.setAttribute("type", "text");
    row.append(input2);
    // button.remove-row
    child = document.createElement("button");
    child.classList.add("remove-row");
    child.innerHTML = "Remove";
    child.setAttribute("type", "button");
    child.addEventListener("click", () => {
      row.remove();
      updateTotalQuantity();
    });
    row.append(child);
    
    document.querySelector("form .rows").append(row);
  }
  
  document.querySelector("form .add-row").addEventListener("click", () => appendNewRow());
  
  appendNewRow();
});
<form>
  <label>Total Quantity: <span id="totalqty">10</span></label>
  <br>
  <div class="rows">
  </div>
  <button type="button" class="add-row">Add new row</button>
</form>

2
  • your question is not matching your title, anyways if I'm understand it correctly the update and insert is working fine.. but the function should only check if value already exist or not. then insert / update ? Commented Nov 10, 2020 at 3:58
  • @ash yes the question wasn't clear, so I edited focusing the issue I have Commented Nov 10, 2020 at 4:47

1 Answer 1

1

You can use the JavaScript functions parseInt() and isNaN() to check if a value is a valid number, and then use basic if-statements to check if the number is inside a given range.
If not, then display a notification that some value is incorrect (best: highlight the incorrect input-field) and return, to not reach the code where you send the data to the back-end.

An example would look like this:

let valueFromString = parseInt("10");
if (isNaN(valueFromString)) valueFromString = 0; // Define default value

let lowerBound = 0;
let upperBound = 20;

// Checking if valueFromString is of range [lowerBound, upperBound]; if not, 'return;'
if (valueFromString < lowerBound || valueFromString > upperBound) return;

Now, most of the values don't necessarily need an extra assignment to new variables like lowerBound or upperBound. However, for the purpose of the example, it is demonstrated here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.