Run a javascript function before submitting form

What seems to be the problem:
How can I run a javascript function before submitting my form
I have a form with a readonly field and I would like to remove this attribute just before the submission

I tried

<button type="button" onclick="javascript:$('#testfield').attr('readonly', false);" wire:click.prevent="store()" class="btn btn-primary">Save</button>

but it does not work

Steps to Reproduce:

Are you using the latest version of Livewire:

Do you have any screenshots or code examples:

You can have the button trigger a function then have the function emit an event that will get picked up by livewire if you really need to run the javascript before the wire:click action. But I’d have to wonder what you’d need a read-only field for and if there’s a better way to accomplish this. Maybe a hidden input? This doesn’t really feel livewire-y to me. It seems like you’re submitting a form and that’s it.

If you’re intent on going down this path, this might work for you:

<button type="button" onclick="javascript:$('#testfield').attr('readonly', false); Livewire.emit('storeFields')" class="btn btn-primary">Save</button>
Component.php

protected $listeners = ['storeFields'];

public function storeFields() // must be the same as the listener, or you need to define the function in the listener array
{
    // whatever you're trying to do.
}

Again, I’m unsure why you need the field read-only and if you’re wire:model-ing that field, livewire should send that field through regardless if it’s read-only or not.

1 Like

Hey, @Frederico

What’s the job of this disabled attribute in this case?

@skywalker @shortbrownman

Hi

My goal is to show users the URL of the page they are creating.

My livewire component has a title,a slug, and other fields
The title field is editable. The slug field is readonly.
When the title is updated by the user, the slug field gets updated and a validation is run by livewire to check if any other page has the same slug, and we updated the slug field

When submitting the component, my slug is not passed to livewire. My guess is it is because of the readonly state of the slug field.

At the minute, I do not want the slug to be editable by the user but I might allow it in the future

I don’t think there is a sense if the user cannot edit the slug, anyway you can validate the slug and check if exists or not by updatedTitle method.

public function updatedTitle($field)
{
    $this->slug = slug($this->title);

   $this->validateOnly($field, ['slug', => 'exists:articles']); // ....
}

okay. Thank you for the help. I think I will make the slug editable. It will solve my issue

Many thanks

Hey, @Frederico
I’m glade you figure out how to solve your issue.

Happy coding mate.