简体   繁体   中英

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):

在此处输入图片说明

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:

在此处输入图片说明

**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!

The problem is that onload is not a valid attribute for a checkbox. Because of this your initValue never runs. Add a script tag like so below your elements.

<script>
// self executing function here
(function() {
    initValue();
})();
</script>

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