简体   繁体   中英

Function that will only push value of most recent inputs

I have 3 groups of inputs, in chronological order (manufacturer info, repair info, test info). When the user hits the "confirm button", I want an if statement to iterate through each input, compare if (input.val() !== "") , and then make sure it is the most recent data (ie. repair info will supercede mfg info) before pushing that value to the #asreceived fields.

I have manually done an if statement for each set of inputs to iterate through, however I would have to add to the function if I wanted to enter more fields.

This is what I have currently:

  $("#model-received").val(function() {
    if ($("#model-test").val() != "") {
      return $("#model-testonly").val();
    } else if ($("#model-repair").val() != "") {
      return $("#model-repair").val();
    } else {
      return $("#model-initial").val();
    }
  });

I have used this code for each set of inputs (roughly 50)

I have tried to compare groups using the .each(), but I am stuck here.

let $inputMfg = $("#manufacturers-tag").find("input , select").each(function() {
      if ($(this).attr("name").indexOf("-initial") > -1) {
        return
      }
    });
let $inputRep = $("#repairtag-old").find("input , select").each(function() {
      if ($(this).attr("name").indexOf("-repair") > -1) {
        return
      }
    });
let $inputTO = $("#testonlytag-old").find("input , select").each(function() {
      if ($(this).attr("name").indexOf("-testonly") > -1) {
        return
      }
    });
let $inputAsRec = $("#asreceived").find("input , select").each(function() {
      if ($(this).attr("name").indexOf("-received") > -1) {
        return
      }
    });

$("#asreceived"),$("#testonlytag-old"),$("#repairtag-old"),$("#manufacturers-tag") are all the same HTML, minus the name suffix on each input ("-initial")

HTML

<div id="repairtag-old" hidden>
            <div class="entry-col3">
              <div class="entry-line">
                <label class="entry-label">Company: </label>
                <input class="entry-input" type="text" name="company-repair">
              </div>
            </div>
            <div class="entry-col3">
              <div class="entry-line">
                <label class="entry-label">Date: </label>
                <input class="entry-date" type="date" name="date-repair">
              </div>
            </div>
            <div class="entry-col3">
              <div class="entry-line">
                <label class="entry-label">VR Stamp: </label>
                <select class="entry-select" id="vrstamp-old" name="vrstamp-old">
                  <option></option>
                  <option>Yes</option>
                  <option>No</option>
                </select>
                <label class="entry-bylabel">VR: </label>
                <input class="entry-input" type="text" name="vrnumber-old">
              </div>
            </div>
            <div class="entry-col2">
              <div class="entry-line">
                <label class="entry-label">Job Number: </label>
                <input class="entry-input" type="text" name="jobnumber-repair">
              </div>
            </div>
            <div class="entry-col2">
              <div class="entry-line">
                <label class="entry-label">Model Number: </label>
                <input class="entry-input" id="model-repair" type="text" name="model-repair">
              </div>
            </div>
            <div class="entry-col3">
              <div class="entry-line">
                <label class="entry-label">Set Pressure: </label>
                <input class="entry-input" id="setpressure-repair" type="text" name="setpressure-repair">
                <select class="entry-select" name="setunit-repair">
                  <option>psig</option>
                </select>
              </div>
            </div>
            <div class="entry-col3">
              <div class="entry-line">
                <label class="entry-label">Cold Test Pressure: </label>
                <input class="entry-input" type="text" name="coldpressure-repair">
                <select class="entry-select" name="coldunit-repair">
                  <option>psig</option>
                </select>
              </div>
            </div>
            <div class="entry-col3">
              <div class="entry-line">
                <label class="entry-label">Capacity: </label>
                <input class="entry-input" type="text" name="capacity-repair">
                <select class="entry-select" name="capacityunit-repair">
                  <option>scfm</option>
                </select>
              </div>
            </div>
            <br>
          </div>

The final result should push the value of the most important value (test only 1st, repair 2nd, mfg 3rd). If the (input.val === "") , it should use the older values.

---UPDATED---

I figured it out. Code snippet below. Thank you for the responses, I was a little intimated in trying to implement them (I am new at coding). However, Mark Meyer's response got me on the right track. This works exactly as intended.

$("#copybtn-received").click(function(i) {
    $("#asreceived").find("input, select").each(function() {
      let $output = $(this).attr("name").split("-received")[0];
      let $inputTO = $("#testonlytag-old").find("[name^=" + $output + "]");
      let $inputRep = $("#repairtag-old").find("[name^=" + $output + "]");
      let $inputMfg = $("#manufacturers-tag").find("[name^=" + $output + "]");
      if ($inputTO.val() !== "") {
        $(this).val($inputTO.val());
      } else if ($inputRep.val() !== "") {
        $(this).val($inputRep.val());
      } else if ($inputMfg.val() !== "") {
        $(this).val($inputMfg.val());
      } else {
        $(this).val("");
      }
    });
  });

You could put your values in an array that is in the order of precedence you want then use find() which returns the first value found. In the find callback just return whether the value is truth, which "" isn't. This will allow you to decide arbitrary orders without all the if/else statements.

Here's a simplified example. It will log the highest value filled in.

 function getBest(){ /* values in the order values will be found */ let values = [ document.getElementById("one").value, document.getElementById("two").value, document.getElementById("three").value, document.getElementById("four").value ] /* find the first truthy value */ let best = values.find(val => val) console.log(best) } 
 <input id="one" type ="text"><br /> <input id="two" type ="text"><br /> <input id="three" type ="text"><br /> <input id="four" type ="text"><br /> <button onclick="getBest()">Go</button> 

I'm not sure I understand the question correctly, so this is a bit of a guess. Perhaps something like this would do?:

const findFirst = (ids, idx = ids.find(id => $(`#${id}`).val() !== '')) =>
    idx > -1 ? $(`#${id}`).val() : 'not found'

$("#model-received").val(findFirst(
    ['model-testonly', 'model-repair', 'model-initial']
))

You can then update the list by simply appending to that array. And if the 'model-' prefix is universal, you can include that in the function and only pass ['testonly', 'repair', 'initial'] in the call.

I don't know if you have a better default than the 'not found' here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM