I have a table with some PHP and a form. Here is a part of it which shows that a button is placed in a cell:
if ($giorno == "ven"){
echo '<td>'.$qres["ven_1"].'</td>;
echo '<td>';
?>
<form action="?" method="post">
<input type="hidden" id="ven_1" name="ven_1" value="<?php echo $qres["ven_1"];?>">
<button type="submit" class="btn" id="ts">click me</button>
</form>
<?php
echo '</td>';
}
Below the table I have a script which triggers a modal dialog.
It basically counts some cells and shows the number in a dialog.
<script>
const re1 = /^[0-9][A-Z]/;
const re2 = /^c[0-9]/;
const actives = $('td').filter(function() {
const text = $(this).text();
const makeActive = text.match(re1) !== null;
$(this).toggleClass('active', makeActive);
$(this).toggleClass('compresenza', text.match(re2) !== null);
return makeActive;
}).length;
$('<div id="messaggio"></div>').html(`${actives}`).dialog({
title: 'Title',
width: '300px',
buttons: {},
modal: true,
});
</script>
As it is, the dialog opens when the HTML page is loaded.
I would like to set the dialog to autoOpen: false
and open it only when the button in the table above is clicked on.
What is the correct procedure to achieve this?
You can put the dialog opening into a function
, like
function openDialog(actives) {
$('<div id="messaggio"></div>').html(`${actives}`).dialog({
title: 'Title',
width: '300px',
buttons: {},
modal: true,
});
}
and create an event, like
document.querySelector('form button#ts').addEventListener("click", function() {
//TODO: Make sure actives is reachable and properly initialized here
openDialog(actives);
e.preventDefault();
return false;
});
EDIT:
Your button submits the form, this is why your dialog appears only for a fraction of a second. To fix this problem you will need to e.preventDefault()
and/or return false;
inside the click handler that will prevent the form from being submitted.