I already checked multiple sites and posts regarding this topic, but couldn't find an answer yet. I simply want to fire the following JS code if someone clicked a specific Checkbox in my form:
function updateRequirements() {
var escortWrapper = document.querySelector(".elementor-field-type-html .elementor-field-group .elementor-column .elementor-field-group-field_ceffa28 .elementor-col-100");
if (escortWrapper.style.display != 'none') {
document.getElementById('escort').required = true;
} else {
document.getElementById('escort').required = false;
}
}
You can check and test that for yourself on the following site:
Advelio Website
If you click on the second checkbox field, there is a field appearing where you can type in your name. And this field is currently optional, but I want to make this required if someone clicked the second checkbox.
You can do it like this:
function updateRequirements() {
const btn = document.getElementById('escort');
btn.required = !btn.required;
}
document.querySelector("#requireCheck").addEventListener('click', updateRequirements);
<form>
<input type="checkbox" id="requireCheck">
<label for="requireCheck">Should the the other input be required?</label>
<br>
<input type="text" id="escort">
<input type="submit" value="submit">
</form>
I simplified the function updateRequirements for the scope of this answer, but it can be changed to anything or any condition.
You have to have event listener for click event and if you dont have create one and wrote the function with logic what to do if is click
The idea is that when the user is presented with the What is your name box, if they don't fill it in they would get a pop up message saying "please enter your name".
I don't understand why the form does not return the pop-up as I am calling the correct getElementsByName method I believe and checking if a value has been entered. I have tried changing the elementsByName to ("name") and ("UserInfo") but nothing happens. Does anyone have any ideas what might be the issue? I know the submit button is missing from the form but that was intentional as otherwise I'd have to post more code than necessary.
The code snippet is attached. The function name in html is called validate();
ALSO, I CANNOT MAKE ANY CHANGES TO THE HTML, IT NEEDS TO REMAIN AS IS.
function Validate() {
alert(document.getElementsByName("UserInfo")[0].value);
if (name == "" || name == null) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" />
</div>
</fieldset>
You are checking for name to be empty or null but the variable name isn't defined hence its always executing the else part.
Below is the working model of your snippet.
I had assigned the input value to value and check for existence, do alert if not a valid input.
function Validate(){
const value = document.getElementsByName("UserInfo")[0].value;
if(!value) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<form onsubmit="Validate()">
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" required />
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
UPDATE:
Use required attribute.
Even better approach would be to wrap all the elements and submit button inside form and add required attribute to all required elements. Updated the answer.
Adding required will abort the submit itself.
I'm trying to create a script that keeps our main button disabled until specific field requriments are met.
jQuery(document).ready(function() {//check if all are filled else disable submit
var inputFields = jQuery('#list-item-cc input, #field_28_50 input,#field_28_18 input');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if (jQuery(this).val().length == 0) {
empty = true;
}
});
if (empty) {
jQuery('#gform_submit_button_28').attr('disabled', 'disabled');
} else {
jQuery('#gform_submit_button_28').removeAttr('disabled');
}
I'm having trouble thinking of a way to ensure my inputFields variable can be passed to my inputFields.each(function() in a way that would allow the loop.
We're not worried about all input fields. Just the specific inputs in our inputFields variable.
Is this an effective way to ensure a button is disabled if certain fields are not filled out and can I create the selector in the way that i did and use that in an each statement?
Looks like you are using gravity forms? In that case I would add a css class to each field that you want to validate. That way you don't have to go searching for ID's and change the code for multiple forms.
https://docs.gravityforms.com/css-ready-classes/
Here is a fiddle in which I pretend that I added "ensure-filled" to each item in the gravity forms builder
https://jsfiddle.net/dokLz4hm/3/
Also note that I added a .trim() to the value so that blank spaces aren't counted as input and made the submit button generic so it would work with any field in a form that contains the ensure-filled class
Html
<div>
<div id="arbitraty_id_1">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_2">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_3">
<input type="text" class="ensure-filled" />
</div>
<input type="submit" value="submit" disabled>
</div>
JS
$(document).ready(function() {
var inputFields = $('.ensure-filled');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if ($(this).val().trim().length == 0) {
empty = true;
}
});
$('input[type="submit"]').attr('disabled', empty);
})
})
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');
}
}
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