Chrisk8er Chrisk8er - 3 months ago 13
React JSX Question

Grab dynamic input value in react

this is my form view:

My form

and this is my dynamic input form code:

...
let subJudulInput = []; // this variable will render
for (var i = 0; i < this.props.subtitleInput.index; i++) {
let index = i + 1;
subJudulInput.push(
<div key={'formgroup' + index} class="form-group">
{(i === 0) ? <label for="subJudulInput">Sub Judul</label>:false}
<input key={'input' + index} type="text" class="form-control" placeholder={`Masukan Sub Judul ${index}`}/>
</div>
);
}
...


if i click the plus button, the new input form will show..

this is my form handler:

onAddingTitle(event) { // if the submit button get pressed
let formData = {subJudul:[]};
event.preventDefault();

console.log(event.target.elements);

}


how i can grab all of that dynamic input value? (best ways) to formData object. like this:

let formData = {subJudul:[
'sub judul 1 value here',
'sub judul 2 value here',
'sub judul 3 value here',
'next new input'
]};

Answer

Add name attribute to the text field: name={"textbox-"+index}

Try the below code to get your expected values

    onAddingTitle(event) { 
      event.preventDefault();
    let formElements = event.target.elements;
    let formData = {
      subJudul: []
    };
    Object.keys(formElements).forEach((key) => {
      if (formElements[key].type == 'text') {
        formData.subJudul.push(formElements[key].value)
      }
    });
    console.log('formData', formData);
   }

Explanation:

  • Get the form elements (which is a object)
  • loop through the object elemets using keys
  • Check the type of the field, if its a textbox(add as per your need) push the value of the field to array.
Comments