简体   繁体   中英

How to store the selected value in a variable?

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(); }); }

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.

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