HTML Form reset does not restore disabled properties - javascript

When some elements in a HTML form are initially disabled, but get enabled and their value changed afterwards, if user clicks the form's reset button, the values of those elements get restored to their initial values, but they're still enabled although they were disabled originally. Why is it so, and how can I ensure that form reset resets those elements to be disabled?
JSfiddle here: http://jsfiddle.net/d872N/
Code example here:
<html>
<head>
<script>
function enableDisable()
{
var combo1 = document.getElementById("a");
var combo2 = document.getElementById("b");
if (combo1.value == 1)
combo2.disabled = true;
else
combo2.disabled = false;
}
</script>
</head>
<body>
<form name="form" action="dummy">
<select id="a" onchange="enableDisable();">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select disabled id="b">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" value="submit" />
<input type="reset" value="reset" />
</form>
</body>
</html>

The reset() method only restores a form elements default values and will not change the disabled state.
Read some documentation here https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.reset
I would suggest that you need to write your own reset method which calls HTMLFormElement.reset() and then resets the disabled state.
e.g.
New JavaScript code:
var hardReset = function(){
document.forms["form"].reset();
document.getElementById("b").setAttribute("disabled","disabled");
};
New HTML:
<input type="button" value="reset" onclick="hardReset();" />
Please see an update of your jsFiddle

A form element's disabled status, like other form-only attributes such as pattern, required, etc, is not part of the form's input data, which is the only aspect of form state which the reset method affects.
I came up against a similar problem a while back and decided to build a tool which would save states of DOM elements to revert them at will, thus keeping the DOM 'versioned'.
It's called a jQuery plugin called reverter and may help you out:
$( function form(){
// Save state on load
var initial = $( 'form *' ).commit( { attributes : 'disabled' } );
$( 'form' ).on( 'reset', function(){
// Revert it on reset!
$( 'form *' ).revert( { changeset : initial } );
} );
} );

Related

Why The Validation is not working for the provided html/ js code

I want the to get the required in the html page if none is selected.
function validation() {
var country = getElementById("country");
if (country.value = "") {
documnet.getElementById("countryy").innerHTML = "Required";
return false;
} else
return true;
}
<form onsubmit="return validation();">
<select id="country"><span id="countryy"></span>
</select><br>
<input type="submit" name="Submit" value="Submit">
</form>
Why The Validation is not working for the provided html/ js code. I want the to get the required in the html page if none is selected. I am new to js learning.
Several issues
Spelling mistake in the document.getElementById
missing document on the other document.getElementById
No preventDefault which will submit the form if any JS errors
= is assignment - you need == or === to compare
span needs to be outside the select
You did not use value="Default" in the "NONE" options
It is not recommended to have inline event handlers. Here is a better version
Note I added a class to toggle the required in case the user changes the select to conform
window.addEventListener("load", function() {
const errorSpan = document.getElementById("countryy"); // cache the elements
const country = document.getElementById("country");
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = country.value; // get the value
if (val === "") {
e.preventDefault(); // stop submit
}
errorSpan.classList.toggle("hide",val); // hide if value
})
country.addEventListener("change",function() { // if user changes the select
errorSpan.classList.toggle("hide",this.val); // hide if value
})
})
.hide { display : none; }
<form id="myForm">
<select id="country">
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select> <span id="countryy" class="hide">Required</span><br>
<input type="submit" name="Submit" value="Submit">
</form>
HOWEVER you could remove all the script and just add required attribute to the select and keep the empty default
<form id="myForm">
<select id="country" required>
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select><span id="countryy"></span><br>
<input type="submit" name="Submit" value="Submit">
</form>
Use required attribute in the select tag. It will considered in html 5 validation.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required

Event triggered on any modification on my form

I made a form with an imput text and a select.
To submit the form i want the user to click a verify button in order to check if all fields are correctly filed.
If it is then the button submit who was initialy disabled is now enable.
Here is the problem, i'd like that if the user modify anything in the form again then the button turn back to disable so that he must verify again to submit.
To do so i'd like to find a jQuery event that triggers on any event on my form to turn back the submit button to disable again.
Any idea of how could i do ?
You can use the form (delegateTarget) then from that select the input types (https://stackoverflow.com/a/3165569/125981) that you wish to be in scope to attach event hanlders, and disable those desired by there type. Since it IS possible to have multiple I have included and example with two submit buttons that are and a reset button that is NOT disabled. To reverse that, you would need to have some way to clear them out so I added an example of a custom event.
Added a reset event handler since it may come into play here.
$('#myform').on('change keyup', 'input[type="text"], select', function(event) {
$(event.delegateTarget).find('input[type="submit"]').each(function() {
console.log("disable:", this);
this.disabled = true;
});
})
.on('all-clear', function(event) {
$(event.delegateTarget).find('input[type="submit"]').each(function() {
this.disabled = false;
});
})
.on('click', '#allclear', function(event) {
$(event.delegateTarget).trigger('all-clear');
})
.on('reset', function(event){
// do whatever is desired on the reset of the form
});
.find('input[type="text"]').trigger('change'); //IF you want disabled initially
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form id="myform">
<input type="text" value="text stuff" />
<select>
<option value="option1" selected="selected">First Option</option>
<option value="option2">Another Option</option>
</select>
<input type="submit" value="Submit" />
<input type="submit" value="Possible Submit" />
<input type="reset" value="Reset" />
<button id="allclear" type="button">All clear</button>
</form>
You need to trigger the event with the on Change function of jQuery. You have to assign it to every input field / Select or whatever, or give them all the same class.
Here is a Doc
Example:
<form>
<input class="target" type="text" value="Field 1">
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div id="other">
Trigger the handler
</div>
Script:
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
If you provide any sample Code, we'd be able to help you even more.

Monitoring form fails with Ajax

I have a large form that I want to monitor for changes. I found example code for that in this post. When I run the code as posted, it works fine. But my form is using Ajax and it doesn't work for some reason. Here's my jsfiddle. I added a second monitor near the bottom but it isn't working either.
When the monitoring code is in the doc ready function, even the first "hello" update doesn't work. But this may be something to do with jsfiddle since I can get past that point locally. But even then, the origForm data is not seen more than once because, I think, the doc ready function is only called the one time when Ajax loads it.
Is there a way to monitor all of the fields when using Ajax?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="saved_form"></div>
<div id="changed"></div>
<div id="showform"></div>
<script>
$(document).ready(function() {
ShowForm();
$("#saved_form").text("hello");
var $form = $("form"),
origForm = $form.serialize();
$("#saved_form").text(origForm);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
});
function ShowForm () {
$.ajax({
url: 'ajax3.php',
success: function(data) {
$("#showform").html(`
<form>
<div>
<textarea name="description" cols="30" rows="3"></textarea>
</div>
<div>Username: <input type="text" name="username" /></div>
<div>
Type:
<select name="type">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div>
Status: <input type="checkbox" name="status" value="1" /> 1
<input type="checkbox" name="status" value="2" /> 2
</div>
</form>
`);
}
});
};
var $form2 = $("form"),
origForm2 = $form2.serialize();
$("#saved_form").text(origForm2);
$("form :input").on("change input", function() {
$("#changed").text("A change was made");
});
</script>
You are dynamically adding the form to your page. The selector will not pick up the change event. Also the event and selector in the on method are defined properly. more information about the on method can be found here http://api.jquery.com/on/
Try this:
$(document).on("change", "input, textarea", function() {
$("#changed").text("A change was made");
});
You can use .promise() after using .html() to render your form. This callback is launched right after form has been populated. Then you can use $("#showform form :input") to monitor events just on this eactly form. It costs less in performance than doing with $(document).on(...)
In your code:
function ShowForm () {
$.ajax({
url: 'test',
success: function(data) {
$("#showform").html(`
// <--- All your previous html -->
`).promise().done(function(){
// <--- Execute your monitor after rendering new form -->
$("#showform form :input").on("change input", function() { $("#changed").text("A change was made");
});
});
}
});
};
Look at the updated jsfiddle
To know more about .promise() here-jquery-promises

How to make the chosen value of select list visible

How I can make the selected choice still visible until I re-choose another one?The list may contain more than 10 options
=====
<form method="get" action="Chairman.php" >
<select name="courses" id="courses" class="styled-select" >
<option value="courses"><--Courses--></option>
<option value="PHYS220">Physics for Engineers</option>
<option value="MATH210">Calculus II</option>
<option value="MATH225">Linear Algebra with Applications</option>
</select>
<input type="submit" value="Search Instructor"
onClick="checkDropdown()"></input>
<div id="error" style="color:red"></div>
=====
Also when I am trying to validate the select list,The error is displayed and then quickly it disappears
<script>
function checkDropdown () {
var courses = document.getElementById('courses');
if(courses.value==="courses") {
document.getElementById('error').innerHTML="PLEASE selecttt";
return false;
}
}
</script>
The select is reset and the error disappears because the form is still posted. The value that you return from the function doesn't stop the submission.
You should use the onsubmit event on the form instead of onclick on the button. Use return in the event code to convey the value from the function back to the event:
<form method="get" action="Chairman.php" onsubmit="return checkDropdown()">

Two forms on the same page needs the value of the same element

I have two forms on a php page. They post to different pages when they are submitted. Both forms need the value of a dropbox that is inside form A. How do I get this value posted when form B is submitted?
Create a hidden input in form B and put a change event on the dropdown in form A which copies it's value to that.
Example (using jQuery - if you want to do it with another library or plain javascript you'll need to adapt it).
<script type="text/javascript">
$(function(){
$('#copy-src').change(function(){
$('#copy-target').val( $(this).val() );
}).change();
});
</script>
<form id="a" action="/a">
<input type="text" name="a_only" />
<select id="copy-src" name="also_b">
<option value=""></option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
<button type="submit">Submit</button>
</form>
<form id="b" action="/b">
<input type="text" name="b_only" />
<input type="hidden" name="also_a" id="copy-target" />
<button type="submit">Submit</button>
</form>
The .change(function(){}) creates a change event to copy the value while the final .change() triggers that event (on page load) to ensure the value is right initially.
You can copy dropbox value to Form B while submitting;
On formB;
<form onsubmit="getDropdownValue()">
.....
</form>
And in function;
function getDropdownValue() {
var formB = document.getElementById("formB");
// Get selected value from FormA
var e = document.getElementById("formADropdown");
var value = e.options[e.selectedIndex].value;
// Append it to formB
var input = document.createElement("input");
input.type = "hidden";
input.name = "dropdownValue";
formB.appendChild(input);
}
You can see demo: Demo . I demo when you click submit, you will see dropdownvalue from form A will be copied to formB before submit

Categories

Resources