vendredi 22 décembre 2017

JavaScript to change value of textbox

This code is for an unsubscribe form, where I need to toggle whether or not a checkbox is checked on initial start, and then change values based on a user's selection.

Basically, I'm passing a value into the html through our email platform. If the value is I, the checkbox should be checked and the value I. Conversely, if the value is O, the checkbox should not be checked and the value O.

For the data to be passed back into our email platform I have to use a hidden input to capture the value, otherwise it won't actually send the I or O back.

The JavaScript, which I have as a tag in the head (HTML Email)

var initValue = function() {
    var permStat = document.getElementById("emailPref").value
    if(permStat === "I"){
      document.getElementById("checkbox").checked = true;
    } else {
      document.getElementById("checkbox").checked = false;
    }
  }
  var changeValue = function(){
    var optValue = document.getElementById("checkbox").value;
    if(optValue === "I"){
      document.getElementById("checkbox").value = "O";
      document.getElementById("emailPref").value = "O";
      document.getElementById("checkbox").checked = false;
    } else {
      document.getElementById("checkbox").value = "I";
      document.getElementById("emailPref").value = "I";
      document.getElementById("checkbox").checked = true;
    }
  }

The visible label for toggling the style (using CSS only)

<input type="checkbox" id="checkbox" name="emailPerm" value="$EMAIL_PERMISSION_STATUS_$" onload="initValue();" onclick="changeValue()">
<label class="toggle" for="checkbox"></label>

And the hidden input, the one that passes data back to our email platform

<input type="hidden" id="emailPref" name="EMAIL_PERMISSION_STATUS_" value="$EMAIL_PERMISSION_STATUS_$">

Additional info

On loading with I value, it appears as this (which would be the "O" value):

enter image description here

On clicking, after this state, the value does set to "O" and the styling remains the same. On a second click, the value goes back to "I" and displays properly:

enter image description here

**I apologize in advance if this is an obvious mistake, since I typically cannot use JavaScript in HTML emails but since this is technically presented as a landing page, it works.

Thanks!




Aucun commentaire:

Enregistrer un commentaire