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
Related
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);
})
})
html:
<label>Label1</label><br>
<input type="text" name="first" onclick="somefunc()"><br>
<label>Label2</label><br>
<input type="text" name="second"><br>
Javascript:
function somefunc() {
var second = document.getElementsByName('second')[0];
second.disable = true;
}
When I click the first input the second is disabled (that was what I want), but when I type something into the first input field, then delete it, the second is still disabled. Is there a way so I can enable it again?
I couldn't find an other event which can solve this.
You can listen to the keyup event on the first input box and check the value of first input box for enabling or disabling second input.
<label>Label1</label><br>
<input type="text" name="first" onkeyup="somefunc()"><br>
<label>Label2</label><br>
<input type="text" name="second"><br>
<script>
function somefunc() {
var first = document.getElementsByName('first')[0];
var second = document.getElementsByName('second')[0];
if(first.value){
second.disabled = true;
}else{
second.disabled = false;
}
}
</script>
Seems you have missed enabling textbox here. If you can see in previous reply, you just need to re-enable textbox into same state as it was before.
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');
}
}
Using the TokenInput plugin and using AngularJS built-in formController validation.
Right now I'm trying to check if the field contains text, and then set field to valid if it does. The issue with using the plugin is it creates it's own input and then a ul+li for stlying.
I have access to addItem (formname) and my capablities in the controller, I just need to set it to $valid.
Markup.
<form class="form-horizontal add-inventory-item" name="addItem">
<input id="capabilities" name="capabilities" token-input data-ng-model="inventoryCapabilitiesAutoComplete" data-on-add="addCapability()" data-on-delete="removeCapability()" required>
<div class="required" data-ng-show="addItem.capabilities.$error.required" title="Please enter capability."></div>
</form>
JS.
$scope.capabilityValidation = function (capability) {
if (capability.name !== "") {
addItem.capabilities.$valid = true;
addItem.capabilities.$error.required = false;
} else {
addItem.capabilities.$valid = false;
addItem.capabilities.$error.required = true;
}
};
I'm running the capabilityValidation function when TokenInput has something entered and passing in the object.
EDIT:
Found out ng-model on my input does stuff and gets the autocomplete results, which is why I can't get ng-valid to work since it's based on the model.
$scope.inventoryCapabilitiesAutoComplete = {
options: {
tokenLimit: null
},
source: urlHelper.getAutoComplete('capability')
};
I didn't write this autocomplete implementation, is there another way to do this where I would have access to the ng-model attr and move the model function somewhere else?
You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.
What you should do is to set the validity of the input element. Like so;
addItem.capabilities.$setValidity("youAreFat", false);
Now the input (and so the form) is invalid.
You can also see which error causes invalidation.
addItem.capabilities.errors.youAreFat == true;
The answers above didn't help me solve my problem. After a long search I bumped into this partial solution.
I've finally solved my problem with this code to set the input field manually to ng-invalid (to set to ng-valid set it to 'true'):
$scope.myForm.inputName.$setValidity('required', false);
I came across this post w/a similar issue.
My fix was to add a hidden field to hold my invalid state for me.
<input type="hidden" ng-model="vm.application.isValid" required="" />
In my case I had a nullable bool which a person had to select one of two different buttons. if they answer yes, an entity is added to the collection and the state of the button changes. Until all of the questions get answered, (one of the buttons in each of the pairs has a click) the form is not valid.
vm.hasHighSchool = function (attended) {
vm.application.hasHighSchool = attended;
applicationSvc.addSchool(attended, 1, vm.application);
}
<input type="hidden" ng-model="vm.application.hasHighSchool" required="" />
<div class="row">
<div class="col-lg-3"><label>Did You Attend High School?</label><label class="required" ng-hide="vm.application.hasHighSchool != undefined">*</label></div>
<div class="col-lg-2">
<button value="Yes" title="Yes" ng-click="vm.hasHighSchool(true)" class="btn btn-default" ng-class="{'btn-success': vm.application.hasHighSchool == true}">Yes</button>
<button value="No" title="No" ng-click="vm.hasHighSchool(false)" class="btn btn-default" ng-class="{'btn-success': vm.application.hasHighSchool == false}">No</button>
</div>
</div>
It is very simple. For example :
in you JS controller use this:
$scope.inputngmodel.$valid = false;
or
$scope.inputngmodel.$invalid = true;
or
$scope.formname.inputngmodel.$valid = false;
or
$scope.formname.inputngmodel.$invalid = true;
All works for me for different requirement. Hit up if this solve your problem.
to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.
delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);
I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});