Dynamically change string with JS?

2019-08-22 23:17发布

问题:

I'm using a form that needs to pass a hidden field:

<script type="text/javascript">
    var ss_form = {'account': 'XXXXX', 'formID': 'XXXXX'};
    ss_form.width = '100%';
    ss_form.height = '500';
    ss_form.domain = 'app-XXXXX.marketingautomation.services';
    ss_form.hidden = {'field_XXXXX': 'test item, another item' }; 
</script>

All it needs to be is a comma separated list, but I'm trying to dynamically add comma separated items using external buttons, for example clicking:

<button>add this string</button>

would make it

ss_form.hidden = {'field_XXXXX': 'test item, another item, add this string' }; 

I've tried using append to a div and then using innerHTML as a variable but it's just passing the initial div content from page load rather than the dynamically added items as well. JS is not my strong suit... any help is very much appreciated. Thank you!

回答1:

Looks like you want something like this:

<button id="button">add this string</button>

document.getElementById("button").onclick = function(event) {
  ss_form.hidden.field_XXXXX += ' ' + this.innerHTML;
}


回答2:

Have you tried to concatenate the values? The conactenacion is a process in which two or more values are joined by an operator, commonly more (+) or two points (..).

Try this way

<button id="btn">add this string</button>

<script>
document.getElementById ("btn").onclick = function (event) {
   ss_form.hidden.field_XXXXX + = this.innerHTML + ', '; //Add separated comma values
}
</script>