Auto fill input fields

Hello, Little new with javascript.
I have around 20 text input fields, which user have to input and form will store the value in DB.
Each data entry are little different then one another. Is there any way to and how to do, when user entry data in “Input01” field, rest of the field will entered auto fill. without any button to click
For example:
Input01: 192.168.1.0 <<< user will input the text field
Input02: 192.168.2.0 << auto fill
Input03: 192.168.2.128 << auto fill
Input04: 192.168.3.0 << auto fill
Input05: 192.168.3.128 << auto fill

Thank you for the help

There might be, but I’m not spotting a consistent pattern in the desired autocompleted values.
Why is 192.168.1.128 excluded?

Assuming that it was an unintended error, here’s a first attempt.

The HTML code is quite simple, just being input fields. I’ve disabled the auto-filled fields for this initial demonstration to help give a visual indicator about things.

<p>Please enter an ip address, such as 192.168.1.0 </p>
<p>The rest of the fields should autofill with incrementing values.</p>
<p>Input 1: <input name="input1"></p>
<p>Input 2: <input name="input2" disabled></p>
<p>Input 3: <input name="input3" disabled></p>
<p>Input 4: <input name="input4" disabled></p>
<p>Input 5: <input name="input5" disabled></p>
<p>Input 6: <input name="input6" disabled></p>
<p>Input 7: <input name="input7" disabled></p>
<p>Input 8: <input name="input8" disabled></p>
<p>Input 9: <input name="input9" disabled></p>
<p>Input 10: <input name="input10" disabled></p>

When the first input is changed, we can have it call a function to update the other ones:

const input = document.querySelector("[name=input1]");
input.addEventListener("change", ipInputHandler);

That ipInputHandler function can get the entered ip, and the other input fields, and pass them to a function that updates those other input fields. It’s usually best if the handler function is very simple, and passes work off to other functions.

function ipChangeHandler(evt) {
  const input = evt.target;
  const ip = input.value;
  const inputs = document.querySelectorAll("input");
  const otherInputs = Array.from(inputs).slice(1);
  updateInputs(otherInputs, ip);
}

The updateInputs function just loops through the other inputs, giving them the next value.

function updateInputs(inputs, ip) {
  inputs.forEach(function (input) {
    ip = nextIp(ip);
    input.value = ip;
  });
}

And that nextIp function doesn’t at this stage have to be all that smart at all.

function nextIp(ip) {
  var parts = ip.split(".");
  if (parts[3] === "128") {
    parts[2] = Number(parts[2]) + 1;
    parts[3] = "0";
  } else {
    parts[3] = "128";
  }
  return parts.join(".");
}

A working example for this is up at https://jsfiddle.net/1kb7rf6t/1/

Hopefully this gives you a basis to work from.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.