Home > Software design >  How to store the selected value in a variable?
How to store the selected value in a variable?

Time:07-22

The user can choose their gender. I need to somehow write the selected response to a variable so that I can use it later when submitting the form. How can i do this? The choice itself is implemented using pop-up buttons when passing the questionnaire:

function genderNext() {
  $(".chooseGenderM").click(() => {
    document.querySelector(".chat-content-buttons-gender").style.display = "none";
    myMassange("Male");

    setTimeout(() => {
      process = true;
    }, 500);
    scrollDown();
  });
  $(".chooseGenderW").click(() => {
    document.querySelector(".chat-content-buttons-gender").style.display = "none";
    myMassange("Woman");

    setTimeout(() => {
      process = true;
    }, 500);
    scrollDown();
  });
}

CodePudding user response:

You can store it in a property on an object variable (or directly in a mutable variable using let) elsewhere in your program, and then reference the value when you need to submit the form:

// Elsewhere, in a higher scope in your program
// that you can access "later when submitting the form":

const userData = {
  gender: "Unknown", // or initialize it as undefined, etc.
};

// In the function you showed, assign the gender to the associated property:
function genderNext () {
  $(".chooseGenderM").click(() => {
    document.querySelector(".chat-content-buttons-gender").style.display = "none";
    // Here:
    userData.gender = "Male";
    myMassange("Male");

    setTimeout(() => {
      process = true;
    }, 500);
    scrollDown();
  });
  $(".chooseGenderW").click(() => {
    document.querySelector(".chat-content-buttons-gender").style.display = "none";
    // And here:
    userData.gender = "Woman";
    myMassange("Woman");

    setTimeout(() => {
      process = true;
    }, 500);
    scrollDown();
  });
}

// "later when submitting the form", use the value however you want to. For example:
submitForm(userData.gender);

Alternatively, if you can't create or assign to a higher-scoped variable for some reason, then you can assign the string value to a property on an element's .dataset property and retrieve it later. See Using data attributes for more info.

  • Related