0

I'm trying to do an edit function, Where I'll get the data from the backend. So if the value of dependents is '1,2' then box the checkbox should be selected. I should be able to unselect the checkbox and send the value again if needed. In the below one, When we click on the add for the second row I'm checking if value of check box as 2 (line:79) and it's showing as checked. The problem is when I'm unable to unselect it and send it again.

https://codesandbox.io/s/naughty-rhodes-i2sn9?file=/src/App.js

2 Answers 2

1

I have changed your code a bit, dependents state cannot handle dependents of all form values, so I have added a dependent object inside the form values object, I have tested it and it is working, Only the code and logic for checkbox is modified all other codes is similar to yours

https://codesandbox.io/s/react-fiddle-forked-ubcz4

try this

import React, { useState } from "react";

const App = () => {
  const [formValues, setFormValues] = useState([
    { orderno: 1, inputValue1: "", inputValue2: "", dependentParams: [] }
  ]);
  const [dependents, setDependents] = useState("");

  // control order number in a state to make sure
  // that it does not get messed when you remove
  // an indice from formValues
  // !! default was 0. so set it to 1
  const [orderNumber, setOrderNumber] = useState(1);

  const addFormFields = () => {
    let dependentString = [];
    formValues.map((d, i) => {
      dependentString.push(i + 1);
    });
    setFormValues((prevState) => [
      ...prevState,
      {
        orderno: orderNumber + 1,
        inputValue1: "",
        inputValue2: "",
        dependentParams: dependentString.length ? dependentString : []
      }
    ]);
    // increment order number
    setOrderNumber((prev) => prev + 1);
  };

  const removeFormFields = (i) => {
    let newFormValues = [...formValues];
    newFormValues.splice(i, 1);

    setFormValues(newFormValues);

    // decrement order number
    setOrderNumber((prev) => prev - 1);
  };

  const onChangeFieldValue = (index, key, value) => {
    setFormValues((prevState) => {
      let copyState = [...prevState];
      copyState[index][key] = value;
      return copyState;
    });
  };
  const onchangeCheckbox = (e, orderNo, index) => {
    setFormValues((prevState) => {
      let copyState = [...prevState];
      let dependentParams = [...copyState[orderNo].dependentParams];
      console.log(index, dependentParams);
      if (dependentParams.indexOf(index) !== -1) {
        dependentParams.splice(dependentParams.indexOf(index), 1);
      } else {
        dependentParams.push(index);
      }
      copyState[orderNo].dependentParams = dependentParams;
      return copyState;
    });
  };

  const saveFields = (e) => {
    const queryparam = {
      data: "xxx",
      DbData: "xxx",
      SQlData: "xxx", // only checked ones
      overallData: { formValues : formValues.map(d => ({...d, dependentParams:d.dependentParams.join(',')})) }
    };
    console.log(queryparam, "hhhhhhh");
  };

  const rows = (ele, orderno) => {
    let rowNos = [];
    for (let i = 0; i < orderno; i++) {
      rowNos.push(
        <>
          <input
            type="checkbox"
            value={orderno - i}
            id={orderno - i}
            checked={ele.dependentParams.indexOf(orderno - i) !== -1}
            onChange={(e) => {
              onchangeCheckbox(e, orderno, orderno - i);
            }}
          />
          Params {orderno - i}
        </>
      );
    }
    return rowNos;
  };
  return (
    <>
      {formValues.length <= 4
        ? formValues.map((element, index) => (
            <div className="form-inline" key={index}>
              <label>{index + 1}</label>

              <input
                type="text"
                value={element.inputVal1}
                onChange={(e) =>
                  onChangeFieldValue(index, "inputValue1", e.target.value)
                }
              />
              <input
                type="text"
                value={element.inputVal2}
                onChange={(e) =>
                  onChangeFieldValue(index, "inputValue2", e.target.value)
                }
              />
              {rows(element, index)}

              <button
                className="button add"
                type="button"
                onClick={() => addFormFields()}
              >
                Add
              </button>

              <button
                type="button"
                className="button remove"
                onClick={() => removeFormFields(index)}
              >
                Remove
              </button>
            </div>
          ))
        : ""}
      <button
        type="button"
        className="button remove"
        onClick={(e) => saveFields(e)}
      >
        Save
      </button>
      <button
        type="button"
        className="button remove"
        //onClick={(e) => cancelFields(e)}
      >
        cancel
      </button>
    </>
  );
};

export default App;
Sign up to request clarification or add additional context in comments.

12 Comments

While sending data as well as from the backend the dependentParams value will come as string not as an array or obj.For example, second row as value "1" and for 3 row as depdenpdent param value is '1,2', For 4th row as '1,2,3' if all the check boxes are selected. Not as an array it will be a string.
Yes, i have used that dependentParams array for an example you could use it how it needed to be, just change that array of objects to a string array or a string itself and on each checkbox check whether the index + 1 exists or not in dependentParams if exists return true to checked if not then return false to checked, Show me the final data sample which you needed to send to server I will modify the code based on that
I tried and with string the prev state is not working for the second row.Its showing as "". My Data to server will be [{orderno: 1, inputValue1: "", inputValue2: "", dependentParams: ""},{orderno: 2, inputValue1: "", inputValue2: "", dependentParams: "1" // if param 1 is checked.if its not checked then it will ""} {orderno: 2, inputValue1: "", inputValue2: "", dependentParams: "1,2"/ /if param 1,2 is checked.if its not checked then it will ""
show me the result data you needed to send to server
{"data":"xxx","DbData":"xxx","SQlData":"xxx","overallData":{"formValues":[{"orderno":1,"inputValue1":"tes123","inputValue2":"tes123","dependentParams":""},{"orderno":2,"inputValue1":"tes123","inputValue2":"tes123","dependentParams":"1"},{"orderno":3,"inputValue1":"tes123","inputValue2":"tes123","dependentParams":"1,2"},{"orderno":4,"inputValue1":"tes123","inputValue2":"tes123","dependentParams":"1,3"}]}}
|
0

Change checkbox checked attribute condition to

 checked={orderno === 1 ? true : false}

and try again

1 Comment

I tried this with null too, I could'nt uncheck the value again and send it to the backend,

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.