I have this form when information is being store into DB. I have a checkbox and a text field. Either one are required, but if the text field isn't empty, there's a good chance the checkbox should be checked. So I'd like to display an Alert if the Text Field has a value in it, and the checkbox isn't checked. I'd like this alert to appear when hitting the Submit button. Here's my form:
<form id="form" name="form" action=?post=yes" method "post">
<input type="checkbox" name="close" id="close" value="Yes"><label for="close" title="Close this RMA">Close this RMA</label>
<label><input type="text" name="dateshipped" id="dateshipped"/></label>
<button type="submit">Save and Continue</button>
</form>
So if checkbox "close" IS NOT checked AND "dateshipped" IS NOT NULL, then display alert when click Submit.
Thank you.
you can do a javascript function to be called on the onclick event in the submit button , like this
<button type="submit" onclick="callAfunction();">Save and Continue</button>
and define the function
callAfunction()
{
//do the checks with: document.getElementById('close').value
// display an alert("a message");
}
Would something like this work?
onsubmit="return validate();" // add to your form tag
function validate() {
checkbox = document.getElementById('myCheckbox').value;
if (!checkbox) {
alert('checkbox is empty');
return false;
} else {
return true;
}
}
Something like this perhaps?
Button for submitting. It runs validateSubmit. It only submits if the function is true.
<input type="button" value="submit" onsubmit="return validateSubmit();" />
Here's the validate function. It gets the value of the checkbox and the text. If they're both falsy then it sets valid to a confirm box. The confirm box allows the user to select ok or cancel and returns true or false based on that.
function validate() {
var valid = true;
var checkbox = document.getElementById('checkboxID').value;
var text = document.getElementById('textBox').value;
if(!(checkbox || text))
valid = confirm("Checkbox and text are empty. \n Continue?");
return valid;
}
The condition could be written as (!checkbox && !text), however I find it simpler to read to only use one ! if I can. The rule is called De Morgan's law if you're interested.
If you're using jQuery, things become easier.
var checkbox = $('#checkboxID').prop( "checked" );
var text =$('#textBox').val();
Plus you can attach even handlers like this:
$(document).ready(function() {
$('#btnSubmit').on('click', validate);
});
Let me know if you have any questions.
** Following code working for me, At first you need to add a onclick="functionName();" then do the following code**
function myCkFunction() {
var checkBox = document.getElementById("close");
if (checkBox.checked == true){
alert('checked');
} else {
alert('Unchecked');
}
}
Related
I am trying to check if all form fields are filled on click a button & if valid then i am trying to add a check an alert using jquery.
jQuery("button#btn_place_order").click(function(event){
jQuery("form").validate({
submitHandler: function(form) {
alert('ok');
}
});
});
This is what i have tried but its not working, i just want to check if all fields are ok valid & filled & there is no form related error then just console or alert to check. Webpage has two or more html forms. Is their any way we can check using jquery ?
Thanks
First of you will have to prevent the default behavior of a form submit. Afterwards add a event listener to your button and check for validation of each input. (whatever that means for you). Is this what you wanted?
var el = document.getElementById("form");
el.addEventListener("submit", function(event) {
event.preventDefault();
}, true);
document.getElementById("btn").addEventListener("click", validate);
function validate(){
let valid = true;
[...document.getElementById("form").elements].forEach((input) => {
if(input.value.length == 0){
valid = false;
}
});
if(valid) alert("valid");
}
<form id="form">
<input type="text" name="TEST" id="test">
</form>
<button class="button" name="Send" value="Send" id="btn">Check</button>
I have one submit button, on click of which normal submission of a form should work.
I have another element, a check box on click of which I need to submit the form.
Is it possible?
If yes, how?
Javascript:
var checkbox = document.yourForm.yourCheckbox; // getting yourCheckbox
checkbox.onclick = function() { // a function that is executed when the checkbox is clicked
if (checkbox.checked == true) { // if checkbox is checked:
document.yourForm.submit(); // submit the form
}
};
HTML:
<form name="yourForm">
<input type='checkbox' name='yourCheckbox'>
</form>
http://www.w3schools.com/jsref/met_form_submit.asp
You can do something like below
<input type='checkbox' onclick='handleClick(this);'>Checkbox
function handleClick(cb) {
if(cb.checked)
{
document.getElementById("myForm").submit();
}
}
Hope this helps you.
I am checking the textbox value in javascript. and saving to database. where as my save is of submit type. I want if textbox value is greater than 100 then it should alert. and after alert , page should not submit.
Firstly, bind the click event of that button to a function. Secondly, use event.prevent default to stop that button from submitting the form. Thirdly, validate the value you want. If validated, use form id to submit the form. Something like this:
$("#ButtonId").on("click", function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
if ($("#InputBoxID").val() < 100) {
$("#FormId").submit();
}
else {
alert("your message");
}
});
Above code is in jQuery, so do not forget to add the reference to jQuery.
I think you're looking for something like:
<form id="myForm" onsubmit="return validateForm();">
<input type="text" id="textfield"/>
<button type="submit">submit</button>
</form>
<script>
function validateForm(){
var value=parseInt(document.getElementById('textfield').value);
if(value>100){
alert('value is no good. larger then 100');
return false;
}
}
</script>
If you can show me your code I'd be happy to help you implementing such a feature.
Here you have an example of how to do it. I used a limit of 10 characters to make the test easier: Try if yourself
HTML:
<input type="text" id="myTextBox" onkeyup="checkValue(this)" maxlength="10"></input>
<input id="sendButton" type="submit" value="SEND"></inpu
JAVASCRIPT:
function checkValue(textbox) {
if (textbox.value.length > 10) {
alert("TEXT TOO LONG");
document.getElementById("sendButton").disabled = true;
}
else
document.getElementById("sendButton").disabled = false;
}
I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2
This question already has answers here:
Resetting a multi-stage form with jQuery
(31 answers)
Closed 9 years ago.
I am looking for a jQuery function that will clear all the fields of a form after having submitted the form.
I do not have any HTML code to show, I need something generic.
Can you help?
Thanks!
Note: this answer is relevant to resetting form fields, not clearing fields - see update.
You can use JavaScript's native reset() method to reset the entire form to its default state.
Example provided by Ryan:
$('#myForm')[0].reset();
Note: This may not reset certain fields, such as type="hidden".
UPDATE
As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger():
$('#myForm').trigger("reset");
UPDATE
If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.
To reset form (but not clear the form) just trigger reset event:
$('#form').trigger("reset");
To clear a form see other answers.
Something similar to $("#formId").reset() will not clear form items that have had their defaults set to something other than "". One way this can happen is a previous form submission: once a form has been submitted reset() would "reset" form values to those previously submitted which will likely not be "".
One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms():
function clearForms()
{
$(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(':checkbox, :radio').prop('checked', false);
}
If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId")):
function clearForm($form)
{
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.
Note that this will not clear placeholder text.
Set the val to ""
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />
You could also try something like this:
function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
More info here and here
<form id="form" method="post" action="action.php">
<input type="text" class="removeLater" name="name" /> Username<br/>
<input type="text" class="removeLater" name="pass" /> Password<br/>
<input type="text" class="removeLater" name="pass2" /> Password again<br/>
</form>
<script>
$(function(){
$("form").submit(function(e){
//do anything you want
//& remove values
$(".removeLater").val('');
}
});
</script>
You can simply use the reset button type.
<input type="text" />
<input type="reset" />
jsfiddle
Edit: Remember that, the reset button, reset the form for the original values, so, if the field has some value set on the field <input type="text" value="Name" /> after press reset the field will reset the value inserted by user and come back with the word "name" in this example.
Reference: http://api.jquery.com/reset-selector/
I use following solution:
1) Setup Jquery Validation Plugin
2) Then:
$('your form's selector').resetForm();
function reset_form() {
$('#ID_OF_FORM').each (function(){
this.reset();
});
}
the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.
$.fn.resetForm = function() {
return this.each(function(){
this.reset();
});
}
Then just call it something like this
$('#divwithformin form').resetForm();
or
$('form').resetForm();
and of course you can still use it in the chain
$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')
Would something like work?
JQuery Clear Form on close
HTML
<form id="contactform"></form>
JavaScript
var $contactform = $('#contactform')
$($contactform).find("input[type=text] , textarea ").each(function(){
$(this).val('');
});
Simple and short function to clear all fields