Changing hidden field based on select box selection

Changing hidden field based on select box selection

We have the following:

  • Select field called "favePet"
  • Hidden field called "petRefCode"

Because we have no control over the server, we have to do this on the front end. We need to send a certain "petRefCode" based on the favorite pet selection:

  1. favePet is Dog, then petRefCode is 'domestic01'
  2. favePet is Cat, then petRefCode is 'domestic01'
  3. favePet is Hamster, then petRefCode is 'domestic02'
  4. favePet is Parrot, then petRefCode is 'domestic02'
  5. favePet is Spider, then petRefCode is 'domestic03'
  6. favePet is Goldfish, then petRefCode is 'domestic03'

  1. <input type="hidden" name="petRefCode " id="petRefCode " value="">

  2. <label for="favePet">Choose your favorite pet:</label>
  3. <select id="favePet" name="favePet">
  4.     <option value="">--Please choose an option--</option>
  5.     <option value="dog">Dog</option>
  6.     <option value="cat">Cat</option>
  7.     <option value="hamster">Hamster</option>
  8.     <option value="parrot">Parrot</option>
  9.     <option value="spider">Spider</option>
  10.     <option value="goldfish">Goldfish</option>
  11. </select>
How can I submit a hidden field based on the selection? I was experimenting with this:

  1. var refCode={
  2. dog : "domestic01",
  3. cat : "domestic01",
  4. hamster : "domestic02",
  5. parrot : "domestic02", 
  6. spider : "domestic03",
  7. goldfish : "domestic03"
  8.  }

  9. $("#favePet").change(function(e) {
  10. var [ petRefCode] = e.target.value;
  11. if ( e.target.value ) {
  12. $('#petRefCode').val(refCode[petRefCode]);
  13. } else {
  14. $('#petRefCode').val('');
  15. }
  16. })