Change HTML5 <button>'s formaction dynamically with jquery - javascript

I have a form with different multiple submit buttons that perform separate actions.
One of these buttons is part of a bootstrap modal that adds a quantity field. When I press this button I would like it to add the value of the quantity field as a url parameter. For example a user enters 25 in the quantity text field and clicks submit, they should POST the form data to the page www.example.com/folder/?quantity=25.
Unfortunately I am a complete novice to javascript and jquery, so I tried to modify an answer to someone else's question on how to change a form's action to work on my button.
Right now my modal and submit button are working, but the button's formaction is not being changed. I have also tried changing the form's action using the script below and removing the action from the button, but with no success.
Any assistance would be much appreciated. Additionally, I do not care about not supporting older browsers. If just firefox and chrome support it, that is good enough for me.
<div class="modal fade bs-order-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<input type='text' name='quantity' id="quatity">
<li><button name='btn-add' id='btn-add' type="submit" form="id-details" formaction="/inventory/order/" class="btn btn-info">Add to Order List</button></li>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/docs.min.js"></script>
<script>
$(function() {
$('#btn-add').submit(function(){
var quantity = $('#quantity').val();
$(this).attr('formaction', "/inventory/order/?quantity=" + quatity);
});
});
</script>

Issue is the button doesn't have a submit event - the form does. What you want to do is modify the click event of the button instead. Also for safety I prefer to use $(document).ready() when attaching the event:
$(document).ready(
function () {
$('#btn-add').on('click', function () {
var quantity = $('#quatity').val(); // Your ID on the "quantity" input is missing an "n"
$(this).attr('formaction', "/inventory/order/?quantity=?quantity=" + quantity);
});
});
Finally, you may want to add some basic validation to make sure the value in the textbox isn't empty or alphanumeric.

Related

Change <input> value and submit automatically via jquery

I am prototyping a way for a user to view all the data behind a visualization. Basically they would click on a point, a modal would pop up, and the table within modal would be dynamically filtered by a string submission. I've got almost everything working perfectly so far, but I can't get the filter to submit on value change.
The tables library I am using is DataTables, so I have been trying to test this with a small jquery script and some html buttons.
Currently my script is triggered on click of a specific button, it then opens the modal, finds the table's unique id and then the closest child that is an input element, and then it writes a string as that input's value.
Example Sript:
<script>
$('#test-button-2').on('click', function () {
var search_input = $("#x-data-modal").find('input:first');
search_input.val('May 16, 2018');
})
</script>
Relevant HTML:
<div class="modal fade" id="x-data-modal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="moday-body">
<div class='row'>
Search:<input type="search" class="form-control form-control-sm" placeholder=""
aria-controls="x-data-table">
</div>
<table id='x-data-table'>table stuff</table>
</div>
</div>
</div>
</div>
I cannot access the input directly as it is created by the DataTables library without a unique id, but this does the trick. Upon clicking the button the modal is opened and the relevant input is changed to the included string. But for some reason it doesn't submit. So basically the table opens with a canned search when I wanted to open with that canned search either executed or in the process of executing.
I've tried:
<script>
$('#test-button-2').on('click', function () {
var search_input = $("#x-data-modal").find('input:first');
search_input.val('May 16, 2018');
search_input.submit();
})
</script>
And similarly (using the built in DataTables search module):
<script>
$('#test-button-2').on('click', function () {
var search_input = $("#x-data-modal").find('input:first');
search_input.val('Apr 27, 2018');
var table = $('#x-data-table').DataTable();
search_input.on('change', function () {
table.search(this.value).draw();
console.log(('This was the search') + this.value);
});
console.log('Ran Whole Function');
});
</script>
You need to call the .submit() function on the form element, not the input element.
Solved this by watching the Event listener for the search and piggy-backing off the DataTables function. Ended up being much eaiser to locate the search with this as well.
<script>
$('#test-button-2').on('click', function () {
var table = $('#x-data-table').DataTable();
table.search('Jun 10, 2018').draw();
})
</script>

Dynamically create buttons or send data to buttons

I am dynamically trying to pass data that I get from my for loop to the buttons. I am using django to get the data in the for loop, html to make the button and jquery to pass the data. I am not sure if this is the best description though.
My code is:
{% for dogs in Dogs.Other %}
<form id="primaryDogForm" action="{% url 'personal:account:email_dog_confirm' %}" method="post">
{% csrf_token %}
<input type="hidden" id="dogId" name="dogId" value="{{ dogs }}">
<input type="button" value="Make this your primary dog" id="makePrimaryButton" class="btn btn-primary" data-toggle="modal" data-target="#makePrimary" />
</form>
{% endfor %}
Basically, people can add a list of dogs to their account and select a dog to be their primary dog. I want a modal to be called when I click on the button. And that modal should display the name of the dog that is potentially being made the primary dog.
The modal code is as follows:
<div class="modal fade" id="makePrimary" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Make Primary</h4>
</div>
<div class="modal-body">
<p>
You are about to make <span id="newDog" name="newDog"></span> your primary dog.
</p>
<hr>
Submit
</div>
</div>
</div>
</div>
The jquery for to make everything work is:
$('#makePrimaryButton').click(function() {
($('#newDog').text($('#dogId').val()));
});
$('#makePrimarySubmit').click(function(){
$('#primaryDogForm').submit();
});
The problem I am facing is that, suppose I have a list of three dogs, each with a "Make this your primary dog" button, then the button works for only the first dog. The rest of buttons dont work until the first button gets clicked.
Once the first button is clicked, all the other buttons also get the value of the first dog. Hence, the dog 2 and dog 3 in the list cant be made primary dogs.
I am pretty sure the problem is with my html and jquery. Is there a way for me to make button dynamic so that the button gets the value of the dog it is associated with? That way, any dog can be made primary dog.
Thank you so much.
The problem here is with the ID's you're placing on the initial HTML in the for loop. ID's are unique in HTML - you should only have one of them with that ID name on a page. This is also why the jquery selector only picks up the first button properly.
Instead, one way to fix this is to use classes instead of ID's, like so:
{% for dogs in Dogs.Other %}
<form class="primaryDogForm" action="{% url 'personal:account:email_dog_confirm' %}" method="post">
{% csrf_token %}
<input type="hidden" class="dogId" name="dogId" value="{{ dogs }}">
<input type="button" value="Make this your primary dog" class="btn btn-primary makePrimaryButton" data-toggle="modal" data-target="#makePrimary" />
</form>
{% endfor %}
Then you'll need to update your jquery code to reflect this change:
var lastEditedForm = null;
$('.makePrimaryButton').click(function() {
lastEditedForm = $(this).closest('form');
var dogId = lastEditedForm.find('.dogId').val();
$('#newDog').text(dogId);
});
$('#makePrimarySubmit').click(function(){
lastEditedForm.submit();
});
Note that because you've got a click event for the modal defined outside of which dog button you've clicked - which dog button got clicked last needs to be tracked for when the modal is confirmed.
Using a variable outside the two click handlers is just one way to deal with this, and potentially not the best way. Another approach is to define a temporary event handler after the initial dog button is clicked - but that also requires ensuring that the event gets cleaned up properly in the event the modal gets cancelled.
-- Edit explaining temporary event handler --
In order to have a temporary event handler created on each of your dog button clicks, you also need to ensure that the temporary handler gets removed (no matter what) each time. In this case, because you're using a bootstrap modal, we can use the close event on the modal to definitively clear out the event handler.
The javascript looks like this:
$('.makePrimaryButton').click(function() {
// note we're still placing the form in a variable here
// so we have easy reference to it in the temporary event
// handler below
var currentForm = $(this).closest('form');
var dogId = currentForm.find('.dogId').val();
$('#newDog').text(dogId);
$('#makePrimaryButton').one('click', function(){
currentForm.submit();
})
});
// hidden.bs.modal is for Bootstrap v3 or v4. If you're using
// Bootstrap v2 it's just 'hidden.'
$('#makePrimary').on('hidden.bs.modal', function(){
// clears absolutely all event handlers on the button,
// not just the ones we set. We would need a reference to
// the function we set earlier in order to take just
// that function off.
$('#makePrimaryButton').off();
})
You should add a data attribute to the button. The link below gives a good example of it's implementation:
Passing data to a bootstrap modal

Why is HTML 5 validation triggering when I run Jquery function

I have a button that triggers the below jquery function. Currently the function works and hides/shows the form element as desired. However it is tripping the html 5 validation (which I want on submit). Is there a reason it is triggering and a way I can prevent this? I experimented with having a return at the end of the function but no luck. Also neither form is required as part of the validation. I keep getting a pop up telling me previous items are required when I hide/show the form elements..
<button class="col-sm-2 btn btn-success" onclick ="hideFormField ()">Hide</button>
function hideFormField (){
if(!$("#trail").is(":visible"))
{
$("#trail").show();
$("#blazers").hide();
}else{
$("#trail").hide();
$("#blazers").show();
}
}
Try this:
<button class="col-sm-2 btn btn-success" onclick ="hideFormField ();return false;">Hide</button>
Try:
<button class="col-sm-2 btn btn-success" onclick="hideFormField();event.preventDefault();">Hide</button>
Jonathan Lonowski was correct in his comment. Buttons are submit-type by default so you need to explicitly define a button with type="button" attribute if you don't want any additional effects when the button is clicked.
A small example that illustrate the activation of HTML5 form validation through default button behavior is in this jsfiddle: http://jsfiddle.net/zk3jr9vn/
by default button is submit type so add Type to button
like
<button type="button" class="col-sm-2 btn btn-success" onclick ="hideFormField ()">Hide</button>

Form not submitting on iPad

I have the following modal structure containing a form:
<div class="modal fade" id="by-email" role="dialog" >
<div class="modal-dialog">
<div class="modal-header">
<small class="waiting"></small>
</div>
<div class="modal-content">
<form action="/test" method="post" id="form-email">
<button type="button" class="btn btn-default btn-modal" data-dismiss="modal">Cacenl</button>
<input type="submit" class="btn btn-primary btn-modal btn-send" value="Send">
</form>
</div>
</div>
</div>
Also, I am using jQuery to show a "loading gif" once the user submit the form via submit button:
$('.btn-send').on('click', function(e){
/* with this line, I pretend to disable both buttons in order to
prevent the user click them while the form is submitted */
$('.btn-modal').attr('disabled', "disabled");
/* show the gift image */
$('.waiting').fadeIn('fast');
});
In most browsers it works cool. However in iPad the form is never submitted. According to my debug session this is happening in iPad:
Submit button clicked
Buttons disabled
Loading image showed
Strangely I can make it works in iPad if I remove the line $('.btn-modal').attr('disabled', "disabled");, but as consequence buttons are not disabled neither loading is displayed. So, how can I prevent this error in iPad? Thank you in advance
Let the form submit without changing elements that participate in/trigger the submission process. Disable buttons later:
$('.btn-send').on('click', function(e){
setTimeout(function() {
/* with this line, I pretend to disable both buttons in order to
prevent the user click them while the form is submitted */
$('.btn-modal').attr('disabled', "disabled");
/* show the gift image */
$('.waiting').fadeIn('fast');
}, 1);
});
The default action of submit button click is to submit the form. In jQuery, you can use event.preventDefault() or return false; from event handler to prevent the default action from happening.
The default action for the event will not be triggered
http://api.jquery.com/event.preventdefault/
Your code should look like this
$('.btn-send').on('click', function(e){
e.preventDefault();
$('.waiting').fadeIn('fast');
});
You could submit the form via ajax. On success, you can disable the button. An example would be:
$('.btn-send').on('click', function(e){
$.ajax({
url: /test,
type:'POST',
data: { 'foo': foo},
success: function(data) {
$('.btn-modal').attr('disabled', "disabled");
/* show the gift image */
$('.waiting').fadeIn('fast');
}
)};
});
You'll probably need to edit this a little but this is the gist.

How to disable a submit button after one click?

I have this form inside a div and the submit button inside another div.
<div class="container1">
<form name="reg-form" id="signup" action="" method="post">
<div class="sep"></div>
<div class="inputs">
<input type = "submit" id="submit" name="submitkey" value="GENERATE KEY" />
</div>
</form>
</div>
How would I disable the submit button after one click? I tried every javascript code I find but it doesn't work on me. I dont know if it is because the form is inside a div and the submit button is inside another div. Thank you.
document.getElementById('signup').onsubmit = function() {
document.getElementById('submit').disabled = true;
};
Demo
The code should be put under the script, or wrapped inside a DOMContentLoaded/window.onload handler. Make sure your HTML does not have duplicated IDs.
Also, if the button must stay disabled after a page refresh/form submission, you will need cookies or a server-side session. None of these methods are foolproof though, and this is outside of the scope of the question I believe.
If you have jquery you can use this code:
$('#signup').submit(function(){
$('#submit').attr('disabled', 'disabled');
});

Categories

Resources