How to re-enable disabled form fields after submitting form? - javascript

I'm able to disable blank form fields, on submission, with:
<form method="GET" onsubmit="onsubmit1(this)">
...
<script type="text/javascript">
function onsubmit1(thiz) {
$(thiz).find(':input').each(
function() {
if (!$(this).val()) {
$(this).attr('disabled', true)
}
}
)
}
The problem is that the fields remain disabled, when the user selects to export a .CSV file, as the page doesn't refresh after the .CSV file is downloaded to the browser.
I would like the disabled input fields to be re-enabled, when the user selects to export a file.
Bonus points for solving this via the form's onsubmit handler, and not via the submit button's onclick handler as there are many submit buttons.

I have made demo please refer this Demo
See Demo
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="submit" value="Enabled" id="btn2">
<input type="submit" value="Disabled" id="btn1">
$('#btn1').on("click", function () {
alert($(this).val());
$('input:text').attr('disabled', true);
});
$('#btn2').on("click", function () {
alert($(this).val());
$('input:text').attr('disabled', false);
});

Related

Run onclick event only if Input was entered

I want to make a submit button which, once clicked on, will run a function I have made: disable() but I want to make it so it only runs the onclick event if the input above had text.
<form id="name">
<p7>Please enter a name for your plan: </p7> <input required>
<input type="submit" onclick="disable()">
</form>
So if the user typed the required input after the tags, and clicked on submit, it will run disable)
But if the user just clicks on submit without typing anything in the required input, disable() doesn't run
Thanks in advance
You can validate the input value at the beginning of the disable function, like so:
function disable() {
var myInput = document.getElementById("myInput");
if (!myInput.value.length) {
alert('empty');
return;
}
alert('fine');
}
<form id="name">
<p7>Please enter a name for your plan: </p7>
<input required id="myInput">
<input type="submit" onclick="disable()">
</form>
If you're want to use HTML5 validation, don't use click event of the button, use submit event of the form, as follows:
function disable(e) {
e.preventDefault() // Not needed, but for the snippet, for the form win't disappear
console.log('Inside disable().');
}
$('#name').submit(disable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7> <input id="input" required>
<input type="submit">
</form>
I you want to validate it inside JS, use code like the following, that determinates if there is a value inside the input field:
function disable() {
if (!$('#input').val()) {
return;
}
console.log('Inside disable().');
}
$('#button').click(disable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7> <input id="input" required>
<input type="button" id="button" value="Click Me!">
</form>
You could also disable the button itself as you don't need it when there is no input present.
You need to add disable function on input box field.
Added onkeyup event on inputbox to track changes.
disable()
function disable(){
if($("#input").val()!=""){
$("input[type=submit]").attr("disabled", false);
//your own code here!!
}
else{
$("input[type=submit]").attr("disabled", true);
return; //do nothing and return back.
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7>
<input onkeyup="disable()" value="" id="input" required>
<input onclick="disable()" id="submit" type="submit">
</form>

Button enabling for multiple file uploads - HTML

I have this code in my html where I'm to upload three files. The submit button for all the corresponding file uploads is disabled unless a file is selected.
$(document).ready(
function() {
$('input:file').change(
function() {
if ($(this).val()) {
$('input:submit').attr('disabled', false);
}
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<input type="file" name="fileInput1" id="fileInput1" />
<input type="submit" value="submit" disabled />
</form>
<form action="#" method="post">
<input type="file" name="fileInput2" id="fileInput2" />
<input type="submit" value="submit" disabled />
</form>
<form action="#" method="post">
<input type="file" name="fileInput3" id="fileInput3" />
<input type="submit" value="submit" disabled />
</form>
My concern is that, if I select a file for the first form, the submit button in the other forms too get enabled.
Option 1:
Regardless of the order of the elements, this will enable the wanted button:
$(document).ready(
function(){
$('form input:file').change(
function(){
if ($(this).val()) {
// Select button of this form
$(this).parent('form')
.children('input:submit')
.attr('disabled',false);
}
}
);
});
see this jsFiddle
Option 2: This will enable it in case Input-submit is always next to Input-File:
$(this).next().attr('disabled',false);
instead of this:
$('input:submit').attr('disabled',false);
see this jsFiddle
You need to use traversing, to find the right button within the right form.
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$(this).siblings('input[type=submit]').attr('disabled',false);
}
}
);
});
This will look only for inputs that are siblings of the file input, which means that they are within the same parent element (in your case, the same form).

Assigning Code to a specific button

I have three forms on a page with submit buttons in each, there is a code which is suppose to changes the value of a button in a particular form when clicked but when i click on that submit button all the values in the various forms buttons changes, but i want to change the value based on the form i click
<script language="javascript">
/**
* Disable submit button
*/
$(function(){
$('input:submit').click(function(){
$(this).val('Request Placed...');
$(this).attr('disabled', 'disabled');
$(this).parents('form').submit();
});
});
$(window).load(function(){
$('input:submit').removeAttr('disabled');
});
</script>
Use jQuery selector to select only form that you need, only input from form with id="form_2" will be supported
$(function(){
$('input:submit', '#form_2').click(function(){
$(this).val('Request Placed...');
$(this).attr('disabled', 'disabled');
});
});
jsfiddle: http://jsfiddle.net/krzysztof_safjanowski/sP2Zv/2/
I am not sure about your requirements. However, this demo might give you some ideas to resolve your issues.
HTML:
<form id="form1" action="action1">
<input type="text" id="txt1" />
<input type="submit" value="Submit" />
</form>
<form id="form2" action="action2">
<input type="text" id="txt2" />
<input type="submit" value="Submit" />
</form>
<form id="form3" action="action3">
<input type="text" id="txt3" />
<input type="submit" value="Submit" />
</form>
JavaScript:
(function () {
var $submitBtn,
$form,
submitBtnHandler = function (event) {
event.preventDefault();
var $self = $(this);
$self.val('Request Placed...');
$self.prop('disabled', true);
$self.parents('form').submit();
},
formSubmitHandler = function (event) {
event.preventDefault(); // Added this to stay in the same page when submit form. If you want to redirect to the action URL(action1, action2, action3 etc), please remove it.
alert("Hi, I am " + this.id);
},
resetSubmitBtnState = function () {
$submitBtn.removeAttr('disabled');
},
init = function () {
$submitBtn = $('input:submit');
$form = $('form');
$submitBtn.on('click', submitBtnHandler);
$form.on('submit', formSubmitHandler);
};
$(document).ready(init);
$(window).load(resetSubmitBtnState);
}());
JSFiddle Demo: http://jsfiddle.net/w3devjs/3Byb2/
In JavaScript you could do this,
document.getElementById("BUTTON'S ID").value = "TEXT HERE";
Just make that line an onclick one.
So, when the user clicks the button, an onclick event happens, that will change the button's vaule. Be sure that in the input tag, there is an id for the button as well as a value for it.
So, here's a little example I whipped up,
In HTML,
<form>
<input type="text" id="Input" />
<input type="button" id="BUTTON'S ID" value="TEXT HERE" onclick="Changetxt()" />
</form>
In JavaScript,
<script>
function Changetxt()
{
document.getElementById("BUTTON'S ID").value = "SOME OTHER TEXT";
}
</script>
So, when the user clicks the button, the button's text changes from TEXT HERE to SOME OTHER TEXT.

Problem with file submiting

<form method="POST" enctype="multipart/form-data" action="http://site.com/img">
File: <input type="file" name="file" id="abc" /><br/>
ID: <input type="text" name="someId" value="123"/>
<input id="submitFormButton" type="submit" value="Upload" name="Upload">
</form>
<input type="button" id="btnEditAvatar" value="fakeButton"/>
$("#btnEditAvatar").bind("click", function () { $("#abc").trigger("click"); });
$("#abc").change(function() { $("#submitFormButton").trigger("click"); });
Problem occurs in IE only.
When choose file by pressing on "abc" button it works(after closing file dialog, file is uploaded), but when I press on "btnEditAvatar" button, nothing is happened after closing file diaog.
I've tried to use "click" function instead of "change". I've tried to call it with "setTimeout" function and I also tried to use "onpropertychange" event handler.
http://jsfiddle.net/streamcode9/hAnbQ/
Instead if trying to click the submit button, why not just submit the form?
$("#abc").change(function() { $(this).closest('form').submit() });
try either of these:
$("#btnEditAvatar").bind("click", function () { $("#submitFormButton").trigger("click"); });
$("#abc").change(function() { $("#submitFormButton").trigger("click"); });
This binds it to submit.
$("#btnEditAvatar").bind("click", function () { $("#abc").trigger("change"); });
$("#abc").change(function() { $("#submitFormButton").trigger("click"); });
this binds it to change which triggers the submit click

Can I determine which Submit button was used in javascript?

I have a very simple form with a name field and two submit buttons: 'change' and 'delete'. I need to do some form validation in javascript when the form is submitted so I need to know which button was clicked. If the user hits the enter key, the 'change' value is the one that makes it to the server. So really, I just need to know if the 'delete' button was clicked or not.
Can I determine which button was clicked? Or do I need to change the 'delete' button from a submit to a regular button and catch its onclick event to submit the form?
The form looks like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
In the checkForm() function, form["submit"] is a node list, not a single element I can grab the value of.
Here's an unobtrusive approach using jQuery...
$(function ()
{
// for each form on the page...
$("form").each(function ()
{
var that = $(this); // define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit", that).bind("click keypress", function ()
{
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
// assign submit-event to all forms on the page
$("form").submit(function ()
{
/* retrieve the id of the input that was clicked, stored on
it's enclosing form */
var callerId = $(this).data("callerid");
// determine appropriate action(s)
if (callerId == "delete") // do stuff...
if (callerId == "change") // do stuff...
/* note: you can return false to prevent the default behavior
of the form--that is; stop the page from submitting */
});
});
Note: this code is using the id-property to reference elements, so you have to update your markup. If you want me to update the code in my answer to make use of the name-attribute to determine appropriate actions, let me know.
You could also use the onclick event in a number of different ways to address the problem.
For instance:
<input type="submit" name="submit" value="Delete"
onclick="return TryingToDelete();" />
In the TryingToDelete() function in JavaScript, do what you want, then return false if do not want the delete to proceed.
Some browsers (at least Firefox, Opera and IE) support this:
<script type="text/javascript">
function checkForm(form, event) {
// Firefox || Opera || IE || unsupported
var target = event.explicitOriginalTarget || event.relatedTarget ||
document.activeElement || {};
alert(target.type + ' ' + target.value);
return false;
}
</script>
<form action="update.php" method="post" onsubmit="return checkForm(this, event);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
For an inherently cross-browser solution, you'll have to add onclick handlers to the buttons themselves.
<html>
<script type="text/javascript">
var submit;
function checkForm(form)
{
alert(submit.value);
return false;
}
function Clicked(button)
{
submit= button ;
}
</script>
<body>
<form method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Change" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Delete" />
</form>
</body>
</html>
You could use the SubmitEvent.submitter property.
form.addEventListener('submit', event => console.log(event.submitter))
Give each of the buttons a unique ID such as
<input type="submit" id="submitButton" name="submit" value="Change" />
<input type="submit" id="deleteButton" name="submit" value="Delete" />
I'm not sure how to do this in raw javascript but in jquery you can then do
$('#submitButton').click(function() {
//do something
});
$('#deleteButton').click(function() {
//do something
});
This says that if submitButton is clicked, do whatever is inside it.
if deleteButton is clicked, do whatever is inside it
In jQuery you can use $.data() to keep data in scope - no need for global variables in that case.
First you click submit button, then (depending on it's action) you assign data to form. I'm not preventing default action in click event, so form is submitted right after click event ends.
HTML:
<form action="update.php" method="post"">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
JavaScript:
(function ($) {
"use strict";
$(document).ready(function () {
// click on submit button with action "Change"
$('input[value="Change"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Change");
});
// click on submit button with action "Delete"
$('input[value="Delete"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Delete");
});
// on form submit
$('form').on("submit", function () {
var $self = $(this);
// retrieve action type from form
// If there is none assigned, go for the default one
var action = $self.data("action") || "deafult";
// remove data so next time you won't trigger wrong action
$self.removeData("action");
// do sth depending on action type
if (action === "change") {
}
});
});
})(jQuery);
Right now you've got the same problem as you would a normal text input. You've got the same name on two different elements. Change the names to "Change" and "Delete" and then determine if either one of them were clicked by applying an event handler on both submits and providing different methods. I'm assuming you're using pure JavaScript, but if you want it to be quick, take a look at jQuery.
What you need is as simple as following what's on w3schools
Since you didn't mention using any framework, this is the cleanest way to do it with straight Javascript. With this code what you're doing is passing the button object itself into the go() function. You then have access to all of the button's properties. You don't have to do anything with setTimeout(0) or any other wacky functions.
<script type="text/javascript">
function go(button) {
if (button.id = 'submit1')
//do something
else if (button.id = 'submit2')
//do something else
}
</script>
<form action="update.php" method="post">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input id="submit1" type="submit" name="submit" value="Change" onclick="go(this);"/>
<input id="submit2" type="submit" name="submit" value="Delete" onclick="go(this);"/>
</form>
A click event anywhere in a form will be caught by a form's click handler (as long as the element clicked on allows it to propagate). It will be processed before the form's submit event.
Therefore, one can test whether the click target was an input (or button) tag of the submit type, and save the value of it (say, to a data-button attribute on the form) for processing in the form's submit handler.
The submit buttons themselves do not then need any event handlers.
I needed to do this to change a form's action and target attributes, depending upon which submit button is clicked.
// TO CAPTURE THE BUTTON CLICKED
function get_button(){
var oElement=event.target;
var oForm=oElement.form;
// IF SUBMIT INPUT BUTTON (CHANGE 'INPUT' TO 'BUTTON' IF USING THAT TAG)
if((oElement.tagName=='INPUT')&&(oElement.type=='submit')){
// SAVE THE ACTION
oForm.setAttribute('data-button',oElement.value);
}
}
// TO DO THE SUBMIT PROCESSING
function submit_form(){
var oForm=event.target;
// RETRIEVE THE BUTTON CLICKED, IF ONE WAS USED
var sAction='';
if(oForm.hasAttribute('data-button')){
// SAVE THE BUTTON, THEN DELETE THE ATTRIBUTE (SO NOT USED ON ANOTHER SUBMIT)
sAction=oForm.getAttribute('data-button');
oForm.removeAttribute('data-button');
}
// PROCESS BY THE BUTTON USED
switch(sAction){
case'Change':
// WHATEVER
alert('Change');
break;
case'Delete':
// WHATEVER
alert('Delete');
break;
default:
// WHATEVER FOR ENTER PRESSED
alert('submit: By other means');
break;
}
}
<form action="update.php" method="post" onsubmit="submit_form();" onclick="get_button();">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
<p id="result"></p>
Here is my solution:
Just add dataset in submit button like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" data-clicked="change" />
<input type="submit" name="submit" value="Delete" data-clicked="delete" />
</form>
In JS access it by:
$('body').on("submit", function(event){
var target = event.explicitOriginalTarget || event.relatedTarget || document.activeElement || {};
var buttonClicked = target.dataset['clicked'];
console.log(buttonClicked);
});
Name the delete button something else. Perhaps name one SubmitChange and name the other SubmitDelete.
I've been dealing with this problem myself. There's no built-in way to tell which button's submitting a form, but it's a feature which might show up in the future.
The workaround I use in production is to store the button somewhere for one event loop on click. The JavaScript could look something like this:
function grabSubmitter(input){
input.form.submitter = input;
setTimeout(function(){
input.form.submitter = null;
}, 0);
}
... and you'd set an onclick on each button:
<input type="submit" name="name" value="value" onclick="grabSubmitter(this)">
click fires before submit, so in your submit event, if there's a submitter on your form, a button was clicked.
I'm using jQuery, so I use $.fn.data() instead of expando to store the submitter. I have a tiny plugin to handle temporarily setting data on an element that looks like this:
$.fn.briefData = function(key, value){
var $el = this;
$el.data(key, value);
setTimeout(function(){
$el.removeData(key);
}, 0);
};
and I attach it to buttons like this:
$(':button, :submit').live('click', function () {
var $form = $(this.form);
if ($form.length) {
$form.briefData('submitter', this);
}
});

Categories