I have a View that displays a custom post type for coupon codes.
The content template is set up with a button to trigger a modal, using "promo ID" field to make each modal ID unique, like this:
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal-[types field='promotion-id'][/types]">Get Discount Code</button>
Within the Modal that pops up, I have a text input that displays the actual promo code, and I want a button next to it for the user to copy the code to their clipboard, like this:
<input type="text" value="[types field='code'][/types]" id="DiscountCode"></div>
<button onclick="myFunction()">Copy text</button>
The JS to copy the text looks like this:
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("DiscountCode");
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
from the main View output, all of the modals pop up correctly, to reflect each post.
The problem is the copy text function - it only copies the text for the FIRST ITEM IN THE LOOP.
My query therefore, is how to make the ID of the text field unique, or more specifically, how to get that unique ID in the JS code?
I'd like to change the id of the text field to the unique [types field='promotion-id'] - but then how do we use that in the copy function (where it currently uses the static iD "DiscountCode".
thanks
Alan
My query therefore, is how to make the ID of the text field unique, or more specifically, how to get that unique ID in the JS code?
I think you could use the promotion-id field to make the ID of the text field unique. I suggest you always use the output='raw' attribute in code like this. Then to get that unique selector into the JavaScript function, the idea is to use a dynamic parameter, set to the unique ID:
<input type="text" value="[types field='code'][/types]" id="DiscountCode-[types field='promotion-id' output='raw'][/types]"></div>
<button onclick="myFunction('DiscountCode-[types field='promotion-id' output='raw'][/types]')">Copy text</button>
If you change the ID, make sure it adheres to HTML standards - i.e. it should not begin with a number, should contain alphanumeric characters, etc.
function myFunction(textid) {
/* Get the text field */
var copyText = document.getElementById(textid);
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
Absolutely brilliant Christian, thank you!