HTML Form Submit disable and change text on click - javascript

Whats the best way to disable a HTML Form Submit button when it is clicked and also change the text value on it?

Someone recommended a Javascript onclick event, but I would instead recommend using onsubmit. This will be on the form itself rather than the button, and this encompasses the real event that you want to disable the button with (submission), as well as other events that could possibly trigger submit.
document.getElementById('FormId').addEventListener('submit',function(){
var button = document.getElementById('buttonId');
button.innerText = 'Something new!';
button.disabled = true;
});
Edited my answer to include the extra changes you were looking for (text of button, disabled as well).
Edit again: lets be super cross browser!
var form = document.getElementById('FormId');
function submitForm(){
var button = document.getElementById('ButtonId');
button.innerText = 'Something new!';
button.disabled = true;
}
if(form.addEventListener){
form.addEventListener('submit',submitForm,false);
} else {
form.attachEvent('onsubmit',submitForm);
}
This covers versions of IE prior to IE9. Obviously if you have more than one form you would try to make this a little more reusable, but this is the general gist.

The best way to achieve this is via JQuery.
Let say your form submit button has an id="submitButton". So add this script to you page head and refer the place where you put your downloaded JQuery and JQuery-UI script.
<script type="text/javascript" src="Scripts/jquery-2.0.3.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui-1.10.3.js"></script>
<script>
function submitButton_OnClick() {
$("#submitButton").text("New Text");
$("#submitButton").attr("disabled", "disabled");
}
$(document).ready(function() {
$("#submitButton").click(submitButton_OnClick);
});
</script>
and this to your html
<button id="submitButton">test</button>
Check it work!

You can add an onclick event and implement a javascript function to do what you want. You can have a look here to see how to disable a button from javascript. Also take a look here for an example how to change the text of the button using javascript.

You have to use JavaScript and set on click event for example it should be:
HTML:
input type="button" value="value" id="1" onClick="OnClick(this.id)"/>
JavaScript:
function OnClick(id)
{
//some stuff...
}
Also you can use jQuery and catch on submit, for example:
$("form").on('submit',function(event)
{
event.preventDefault();
//some stuff...
}

You can use to onclick attribute to set the disabled attribute. Note that I don't cover how to reenable the button when form submission is complete.
<button type="submit" onclick="this.setAttribute('disabled', 'disabled');">Submit</button>
See the live example here at this fiddle:
http://jsfiddle.net/yinkadet/DPJGw/
I hope this helps

Here is my example of providing this functionality using Ruby on Rails and jQuery - it is an implementation example of the jQuery answer which i found very useful! (so there, haters):
<div class="col s12">
<div class="actions">
<%= f.submit nil, class: "waves-effect waves-light btn green darken-3", id: "gsb" %>
<script>
function submitButton_OnClick() {
$("#gsb").val("***CREATING***");
$("#gsb").attr("disabled", "disabled");
$("#new_group").submit();
}
$(document).ready(function() {
$("#gsb").click(submitButton_OnClick);
});
</script>
</div>
</div>

Related

gtag Linker not working on JS form.submit()

I used correct google tagging to enable cross-domain tracking. When the form is submitted by clicking on submit button the ?ga=... will be added to the destination URL but, it won't be added if I trigger the submit event by JS.
Code is as follows:
<head>
<script>
//All other common JS code exist
gtag('set', 'linker', {
'domains': ['example.com'],
'decorate_forms': true
});
gtag('config', 'UA-...');
</script>
</head>
<body>
<form method="POST" action="https://example.com/a/b">
<button type="submit">Submit</button>
</form>
<button id="bt">Click to submit form using JS</button>
<script>
$(document).on('click', '#bt', function(e){
$('form').submit();
});
</script>
</body>
If I add submit button to form and click on it directly the destination will be something like https://example.com/a/b?_ga=.... However, when I submit the form via JS, destination URL is just like the form action without GA appendix.
I have to note that I'm using gtag and not GTM.
It can be solved in two different ways:
Method 1
We can change the submit trigger to a click trigger on the submit button. Don't know why but, it solves the issue :)
$(document).on('click', '#bt', function(e){
$('form button[type="submit"]').trigger('click');
});
Method 2
We can handle anything we want in the submit event instead of the click event on some other button other than submit.
$(document).on('submit', 'form', function(e){
//Do your stuff and handle the event
return true;
});
Although the problem seems to be solved, the main question still exists and it seems it is pointing to a potential bug for gtag or jquery form.submit(). Therefore, if you can provide any solution or answer for the open question, go ahead and publish your post and I'll make your answer as a correct one.

Disable submit button until input fields are filled

This is my website link, Here i have been trying it using jquery code to enable/disable the button but could not succeed to achieve. You could inspect element to see the code please and output is off course there
Tushar's solution is working perfectly. But I would recommend you to use formal/standard approach for validation.
Do not disable submit button. Just use required attribute for each radio button either in html like
<input id="input_5_0_1" class="form-radio" type="radio" required="required"
name="customer_appointment" value="Good" />
or using js (its short cut way) like
$(document).ready(function () {
$('form input').attr('required','required');
});
Demo on Fiddle
This way you will not be able to submit until you fill all fields, though your button is not disabled.
However if you have to use button disable approach you can follow the above answer of #Tushar
Edit This solution works only with modern browsers who support html5.
Browsers other than mentioned in this link http://html5readiness.com/ (e.g internet explorer 4,5,6) do not support HTML5
Try following code:
$(document).ready(function () {
var noOfRadio = 0;
var names = [];
$('form :radio').each(function () {
if (!names[$(this).attr('name')]) {
names[$(this).attr('name')] = 1;
noOfRadio++;
}
});
console.log(noOfRadio);
$('form').on('change', ':radio', function () {
console.log($('form').find('input[type="radio"]:checked').length);
if ($('form').find('input[type="radio"]:checked').length === noOfRadio) {
console.log('Enable');
$('#input_2').prop('disabled', false);
} else {
$('#input_2').prop('disabled', true);
}
});
});
Demo: https://jsfiddle.net/tusharj/u0mLLo3L/
Why your Submit button is disabled or render as disabled. I checked in firebug and get this. Via firebug if I remove disable="disabled", it will work means post.
<div class="form-buttons-wrapper" style="text-align:left">
<button id="input_2" class="form-submit-button form-submit-button-light_rounded" name="submit" type="submit"> Submit </button>
</div>

$.fn.submit() event don't trigger inside an <iframe>

Simply speaking, I have a form, and a field.
<!-- inner.html -->
<form id="inner_form">
<input type="text" name="username" />
<input type="submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$('#inner_form').submit(function() {
alert('Inner submit is triggered!');
});
});
</script>
The above code goes well: when I click the submit button, it triggers the submit event of #inner_form, and alerts the sentence: Inner submit is triggered!
My problem is, when I make another page, and loads the inner.html inside an <iframe>:
<!-- outer.html -->
<iframe id="the_frame" src="inner.html">
</iframe>
<button id="outer_submit">Submit Inner</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$('#outer_submit').click(function() {
// it don't trigger the inner submit() event!
$('#the_frame').contents().find('#inner_form').submit();
});
});
</script>
As the above code (which might not working well in the snnipet), I click the #outer_submit button, and the #inner_form do submitted, but the event I defined inside it don't triggered!
Why do this happen? And if I want the inner event triggered well with outer action, how can I got it?
While I can't give you an answer as to 'why', here's some discoveries I made while testing this:
Replacing the .submit() action with
$('#the_frame').contents().find('#inner_form input[type="submit"]').click();
Will trigger the alert. This isn't a proper fix though, because there's more ways to submit a form. Still, it shows that the events are not completely broken. So I dug deeper.
I tried using native javascript events instead of jquery's .submit([function]) bind in inner.html:
<form id="inner_form" onsubmit="alert('hi')">
That actually shows the alert. And so does this:
$('#inner_form')[0].onsubmit = function() {
alert('Inner submit is triggered!');
}
So there seems to be something wrong with the way jQuery sets and/or detects its own submit() method.
One more try:
$('#inner_form').on('submit', function() {
alert('Inner submit is triggered!');
});
This also shows the submit!
My wild guess is that for some reason when the events in inner.html are being bound, it doesn't know the form yet, even though the bind is wrapped in an implicit document.ready event through $(function(){ .. });.
As for the how and why of this I remain in the dark, but the fix is simple: wrap your event binds in an .on() method.

How do I use this JQuery code to clean input fields of their content onclick of reset button?

Code:
<script type="text/javascript">
$(".reset_form").click(function() {
$(this).closest('form').find("input, textarea").val("");
});
</script>
Button:
<div class="reset_form">
<a class="anchor_link">
<span class="reset_button">
Reset
</span>
</a>
</div>
Using the code above I want to be able to clean input fields of their content when a user clicks on reset_form. However, being new to JS/JQuery I am unsure as to how to accomplish this since I am not using an input button but a div that looks like a button.
Question
How can i tweak my code so that when a user clicks on .reset_button that the fields will be cleared?
<div class="form-container">
<form>
<input type="text" />
<textarea></textarea>
</form>
<div class="clear-form">
<span class="reset_button">Reset form</span>
</div>
</div>
$(document).ready(function() {
$('.clear-form').on('click', function() {
$(this).closest('.form-container').find('input, textarea').val('');
});
});
Fiddle
In order to help you use the DOM traversal selectors like closest() and find(), it is first necessary to know roughly where your form is in relation to the .reset_form <div>, does it have an ID attribute (which makes it very easy to select the form), etc.
However, assuming there is only one form on the page, then this code will work:
Working jsFiddle example
$(".reset_form").click(function() {
$('form').find("input, textarea").val("");
});
As Jedediah mentions below, the above code will reset/clear all forms on the page. If you only wish to clear one specific form, then you can specify an ID in your form tag, thus:
<form id="justthisform"> ... </form>
You can clear only that form by modifying the active line as follows:
$('#justthisform').find("input, textarea").val("");
If you want to clear all elements in the form (radio reset to defaults, dropdowns, etc) you can use the native reset on the form DOM object but use jquery to find it like this:
<script type="text/javascript">
$(".reset_form").click(function() {
$(this).closest('form')[0].reset();
});
</script>
Well one thing to note is that HTML forms natively support resetting via a reset function in the browser:
$(".reset_form").click(function() {
$(this).closest('form')[0].reset();
});
But yeah if your function isn't working then it looks like your (fake) button isn't embedded within the form itself. jQuery's .closest() function will find the form if you do
$(this).closest("form")
So the only thing you need to fix is finding that form.

Submit a form with associated Live Event

I'm developing an web application using asp.net MVC and jQuery. I have in my page 10 forms and I'm using jQuery (live events) to do a async submit them. Something like this:
Everything works fine, but I need to format a Div with an image and when user clicks on this div I need to submit the form, but... the form is not executing the async operation like the submit button. It's executing default behavior...
My div is something like this:
My Script:
$("#jobs form").live('submit', function() {
$.post($(this).attb('action'), $(this).serialize(), function(result) {
//get and format result in my content divs...
});
});
My HTML:
<div id="jobs">
<% foreach(var job in Model) { %>
<form ...>
<!-- hide this button -->
<input type='submit' class='hide' id='mysubmitButton_<%=job.Id%>' />
<!-- need to submit this form -->
<div class='buttonImage' onclick="$('#mysubmitButton_<%=job.Id%>').click();"></div>
</form>
<% } %>
</div>
How can I set in 'onclick' to do a assync submit like the Submit Button in my page?
I don't know how to format this button, So I'm using an div or a hyperlink...
Thanks
Firstly, you have $.post($(this).attb('action'), .... This won't work -- the function is attr, so you need $.post($(this).attr('action'), .... Even better would be to avoid the jQuery object and use $.post(this.action, ....
For your submit image, the following code should work:
$('.buttonImage').live('click', function(){
$(this).closest('form').submit();
});
This will find the parent form and call the submit action on it, which should trigger the handler you defined in your question.
Just to note that it doesn't appear that you are preventing the default action occuring. You need to call your live method on the form like this:
$("#jobs form").live('submit', function(e) {
e.preventDefault();
// do the rest of your code
}
This prevents the default submit action occuring.

Categories

Resources