Я пытаюсь создать функцию copyToClipboard, которая извлекает значения из TextFields на странице и копирует эти значения при нажатии кнопки «Копировать».Вот функция:
function copyToClipboard() {
const textArea = document.createElement("textarea");
textArea.innerText = "";
const parentElement = document.getElementById("span");
if (parentElement) {
textArea.value = parentElement.innerText;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
textArea.remove();
}
}
А вот мои текстовые поля:
<Grid id="span" container spacing={8}>
<Grid item xs={6}>
<TextField
fullWidth
label="Last Pulled"
value={formatTimestamp(r.createdAt, "MM/DD/YYYY")}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
className="text"
/>
<TextField
fullWidth
label="Credit History Length(months)"
value={creditHistLength}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="SSN Match Indicator"
value={r.ssnMatch}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
className="text"
/>
<TextField
fullWidth
label="Date of Birth"
value={formatTimestamp(r.dateOfBirth, "MM/DD/YYYY")}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
className="text"
/>
<TextField
fullWidth
label="FICO"
value={r.fico}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="Monthly Mortgage Payment"
value={mortgagePayment}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="Disputed?"
value={r.isDisputed ? "YES" : "NO"}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="Hit Indicator"
value={r.hitIndicator}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
</Grid>
</Grid>
А вот и кнопка:
<Button variant="contained" color="primary" onClick={copyToClipboard}>
<FileCopy />
copy to clipboard
</Button>
В настоящее время функция copyToClipboard только выбирает и копирует метки каждого TextField, а не выбирает значения каждого TextField.В идеале это будет захватывать как метки, так и значения, но я остановлюсь на решении, которое захватывает только значения.