Reputation: 6558
I have this basic form:
jQuery(document).ready(function($) {
$('#btn').click(function() {
var form = document.getElementById('form');
form.setAttribute('action', 'export.php');
form.submit()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="get.php" id="form">
<div>
<label for="date">From</label>
<input type="date" name="from-date" id="date" />
</div>
<div>
<label for="date">To</label>
<input type="date" name="to-date" id="date" />
</div>
<div>
<input type="checkbox" name="flags[new]" /> New
<input type="checkbox" name="flags[updated]" /> Updated
<input type="checkbox" name="flags[existing]" /> Existing
</div>
<div>
<input type="submit" />
</div>
<div>
<button type="button" id="btn">
<span>Export</span>
</button>
</div>
</form>
This works as (near) expected. However, I then clicked on the submit input and it tried going to export.php
. For some reason my brain was telling me that this is incorrect behaviour, but I get that I've changed the attribute value within the DOM and thus, anything post-clicking the export button will render the attribute value (until I refresh).
I'm aware that I can do another event handler to reset the attribute value, but I feel like that's counter-intuitive, is there something in JS/jQuery that allows me to "toggle" an attribute for the event only? Or do I have to make-do with a hard reset?
TL;DR
Is there a way to temporarily set an attribute within an event?
Upvotes: 0
Views: 510
Reputation: 484
Try something like this:
jQuery(document).ready(function($) {
$('#btn').click(function() {
let form = document.getElementById('form');
//Save the current attr
let currentAttr = form.getAttribute('action');
form.setAttribute('action', 'export.php');
form.submit();
//Reset the previous attr
form.setAttribute('action', currentAttr);
})
})
You actually save the current attr, submit the form and then set the attribute to the original one.
Hope it solved your issue!
Upvotes: 1