Home > Back-end >  How can I link a radio input to another input field, and get the value inside the selected input (nu
How can I link a radio input to another input field, and get the value inside the selected input (nu

Time:10-11

By selecting one of those radio inputs, it should allow me to take the value of the input field beside it to use it as the main operator in another function. I don't know if linking them with label is enough.

I also want to store the input's value of those dynamic inputs outside the for. How can I do this?

let buddy = document.getElementById("companion")
let buddyResult = document.getElementById("companion-inputs")

function createResult() {
  for (let i = 1; i <= buddy.value; i  ) {
    const element = buddy.value[i];
    buddyResult.innerHTML  = `<div id="lvl-check"><input  id="companion-${i}" type="number" placeholder="Buddy ${i} level"/><input type="radio" name="active" /><label for="companion-${i}">active</label></div>`
  }
}
<input onchange="createResult()"  id="companion" type="number" placeholder="Amount of gardening companions" />
<div id="companion-inputs"></div>

CodePudding user response:

Details are commented in example

/*
These values must be outside of function since at the end of a function all
values are removed.
*/
let count = 0; // Current count of radio buttons
let activeLvl = 0; // Value of selected radio button
let budValue = 0; // Value of the <input> left of selected radio button

// Reference <form>
const buds = document.forms.buds;
// When <button> is clicked <form> is submitted, createResult() runs
buds.onsubmit = createResult;
// When the <form> detects an input event on a radio button, getBuddy() runs
buds.oninput = getBuddy;

// Event handler passes event object by default
function createResult(event) {
  // Stop <form> from sending data to a server
  event.preventDefault();
  // Reference all <input>, <fieldset>, <button>, etc.
  const fc = this.elements;
  // Clear <fieldset> of all content
  fc.result.replaceChildren();
  // <input type="number"> value   number of radio buttons
  const qty = parseInt(fc.companion.value)   count;
  /*
  Create an array of >qty< empties
  Render htmlString >qty< times in <fieldset>
  */
  [...Array(qty)].forEach((_, i) => {
    fc.result.innerHTML  = `
    <div >
      <input id="companion-${i   1}" type="number" 
       placeholder="Buddy ${i   1} level" min="1"/>
      <input name="active" type="radio" value="${i   1}"/>
      <label for="companion-${i   1}"> active</label>
    </div>`;
  });
  // Assign number of radio buttons to >count< (it's outside of function)
  count = Array.from(fc.active).length;
}

function getBuddy(event) {
  // Reference the radio button user selected
  const bud = event.target;
  /*
  If the element user interacted with is not <form> AND has name="active"...
  ...assign the value of selected radio button to >activeLvl< (located outside)
  ...assign the value of the <input> to the left of selected radio button to
  >budValue< -- defaults to 0 (located outside of function)
  */
  if (bud !== this && bud.name === "active") {
    activeLvl = parseInt(bud.value);
    budValue = parseInt(bud.previousElementSibling.value) || 0;
    console.log("Radio Button: "   activeLvl);
    console.log("Input Value: "   budValue)
  }
}
.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}

.as-console-wrapper {
  min-height: 100%;
  max-width: 50%;
  margin-left: 50%;
}
<form id="buds">
  <input id="companion" type="number" placeholder="Amount of gardening companions" min="1" />
  <button>Done</button>
  <fieldset name="result"></fieldset>
</form>

CodePudding user response:

You can try the following script code:

let buddy = document.getElementById("companion");
      let buddyResult = document.getElementById("companion-inputs");
      let results = {};
      let count = 0;

      function getResult(id) {
        let el = document.getElementById(`${id}`);
        results[id] = el.value;
      }

      function createResult(event) {
        console.log("results", results);
        for (let i = 1; i <= buddy.value; i  ) {
          count  ;
          const element = buddy.value[i];
          buddyResult.innerHTML  = `<div id="lvl-check">
            <input  id="${count}"
              onchange="getResult(${count})"
              value="${results[count]}"
              type="number"
              placeholder="Buddy ${i} level"
            />
            <input type="radio" name="${count}" />
            <label for="${count}">active</label>
          </div>`;
        }
      }

CodePudding user response:

You can add a data-something attribute to the radio so you can identify its corresponding input. I also refactored my solution a little so you can print or pass the value of a radio using a callback.

let buddy = document.getElementById("companion")
let buddyResult = document.getElementById("companion-inputs")

function createResult() {
  for (let i = 1; i <= buddy.value; i  ) {
    const element = buddy.value[i];
    buddyResult.innerHTML  = `<div id="lvl-check"><input  id="companion-${i}" type="number" placeholder="Buddy ${i} level"/><input type="radio" name="active" data-companion-id="companion-${i}"/><label for="companion-${i}">active</label></div>`
  }
  document.querySelectorAll("#companion-inputs [type=radio]").forEach(function(radio) {
    radio.addEventListener('click', function(ev) {
      get_value(this, console.log)
    });
  })
}

function get_values() {
  document.querySelectorAll("#companion-inputs [type=radio]").forEach(function(radio) {
    console.log(get_value(radio));
  })
}

function get_value(radio, foo) {
  var id = radio.getAttribute('data-companion-id');
  var value = document.getElementById(id).value;
  if (typeof foo === 'function') {
    foo(value)
  }
  return value;
}
<input onchange="createResult()"  id="companion" type="number" placeholder="Amount of gardening companions" />
<div id="companion-inputs"></div>
<button onclick="get_values()">print values</button>

  • Related