I want to update the value of textarea with JavaScript but when i submit the words i can only get data that users typed directly inside textarea and not changes by JavaScript
what should i do?
here is my code:
Translate::make()
->locales(['fa', 'en'])
->columnSpanFull()
->columns(2)
->schema(fn (string $locale) => [
Forms\Components\Select::make('variables')
->extraAttributes([
'onchange' => 'insertToTextarea("'.$locale.'")'
])
->options(NotificationTemplateVariableEnums::class),
Forms\Components\Textarea::make('template')
->required()
->columnSpanFull()
->reactive(),
])
// javascript
function insertToTextarea(locale) {
const textarea = document.getElementById('data.template.'+locale+'');
const variable = document.getElementById('data.variables.'+locale+'').value;
if (!textarea) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const value = textarea.value;
textarea.value = value.slice(0, start) + variable + value.slice(end);
textarea.selectionStart = textarea.selectionEnd = start + variable.length;
textarea.focus();
}
protected function mutateFormDataBeforeSave(array $data): array
{ dd($data);
}
I updated the JavaScript code, and the issue was resolved. I used the Livewire.find(componentId)
method provided by Livewire's frontend JavaScript library to locate the component and set the Textarea value:
function insertToTextarea(locale) {
const textarea = document.getElementById('data.template.'+locale+'');
const variable = document.getElementById('data.variables.'+locale+'').value;
if (!textarea) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const value = textarea.value;
textarea.value = value.slice(0, start) + variable + value.slice(end);
textarea.selectionStart = textarea.selectionEnd = start + variable.length;
textarea.focus();
Livewire.find(document.querySelector('[wire\\:id]').getAttribute('wire:id')).set(`data.template.${locale}`, textarea.value);
}