I've a form inside a custom template and I would like to trigger the submit button clicking on one div. Then the function submitForm sends the form-data to a webservices using Drupal httpClient.
The twig template is like:
<div class="Rectangle" id="rectangle-div" >
This is the div containing some stuff that I want to click to submit the form.
</div>
<form id="form-id">
{{ form.elem }}
{{ form.actions.submit }}
</form>
I tried with a simple jQuery function like:
jQuery(function($) {
$(document).ready(function () {
$('#rectangle-div').on('click', function () {
var wrapper = $('#form-id');
$('.form-submit', wrapper).trigger( "click" );
});
});
});
I tried also to write a selector like:
$('button[id^="edit-mod-submit"]', wrapper).trigger( "click");
if I try with a simple submit like
$('form-id').submit();
the js code submits the form but refresh the page avoiding ajax and furthermore doesn't send data to the WS:
(if I use the submit button the data goes to the WS).
Any other ideas?
UPDATE #1: FIXED
I added inside the ajax option of my submit button the event 'click' and now, using jQuery, I am able to send the post request to the WS. The form is like:
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Save'),
'#button_type' => 'primary',
'#ajax' => [
'callback' => '::setMessage',
'event' => 'click',
],
);
The jQuery function is:
jQuery(function($) {
var wrapper = $('#form-id');
$('.form-submit', wrapper).trigger( "click" );
});
Now I should intercept the response coming from the webserver and then execute a JS script, but these are other questions :)
<div class="Rectangle id="rectangle-div" >
is missing a " after Rectangle which would cause the rest of the code to not work correctly