I have a form with a class="myfrm" and contains a fieldset made up of input fields. After the fieldset tag I have a div tag and assigned class="ack-msg" which contains an acknowledgement message.
In CSS I have
.myfrm.submitted fieldset {
display: none;
}
.myfrm.submitted .ack-msg {
display: block;
}
When the form is submitted the fieldset is replaced by the acknowledgement.
This works fine when the form is completed as expected but when the form validation fails a message is displayed but the acknowldgement class="ack-msg" kicks in and replaces the fieldset as if it passed.
The validation is carried out by a javascript function called by the onSubmit on the form. The javascript is listed below and to keep things simple I have a shorted version of the script that only passes the validation if the provided parameter value = 24.
function validateForm(v)
{
if(v.value != '24')
{
alert("Oops! Try agan!");
return false;
} else {
return true;
}
}
Also, if I inspect the page after validation fails and acknowledgement gets diaplayed form declaration has been updated from
class="my-frm"
to
class="my-frm submitted"
If I should be listing other details please let me know.
Any help welcome on this.
Thanks in advance,
Ned
Try to remove the submitted class using javascript, right after the alert.
If you have jQuery:
function validateForm(v)
{
if(v.value != '24')
{
alert("Oops! Try agan!");
$.(".my-frm").removeClass("submitted");
return false;
} else {
return true;
}
}
Related
I'm pretty new to WordPress, but basically what I'm trying to achieve is to make a tag's description a required field on my custom theme for WordPress 4.5.2
I've tried three approaches, but all of them failed so if anyone WordPress expert out there could guide me would be nice.
Approach #1
functions.php
I've tried to 'edit' the hook when the edit_tag_form_fields and add_tag_form hook is called, then modify via Javascript
function require_category_description(){
require_once('includes/require_category_description.php');
}
add_action('edit_tag_form_fields', 'require_category_description');
add_action('add_tag_form', 'require_category_description');
require_category_description.php
<script>
jQuery(document).ready(function(){
var description = jQuery('#tag-description');
if(!description) description = jQuery('#description');
if(description){
description.parents('form').submit(function(){
if(description.val().trim().length < 1){
console.log('Please enter a description...');
return false;
}
});
}
});
</script>
It was not working, the form was submitting even though the description field was empty, and above all, the console.log inside the event listener never happened. I've tried to log the description variable to make sure it's going inside the if case. Therefore, I assumed the form was never submitting, and the whole 'submission' is done via Ajax, on the button click.
Approach #2
The functions.php remains the same as approach #1, but I've made some changes Javascript wise to target the button click event instead of the form submit event.
require_category_description.php
<script>
jQuery(document).ready(function(){
var description = jQuery('#tag-description');
if(!description) description = jQuery('#description');
if(description){
var button = description.parents('form').find('#submit');
button.on('click', function(e){
if(description.val().trim().length < 1)
console.log('Please enter a description...');
e.preventDefault();
return false;
});
}
});
</script>
The form is however still submitting, but this time, I see the console log message.
Please enter a description...
My theory is that WordPress is binding an event to the button's click before my event, so it's processing the built-in event with Ajax before going to my custom click event.
Approach #3
require_category_description.php
I've tried to unbind the click events from my button before adding my own click event.
<script>
jQuery(document).ready(function(){
var description = jQuery('#tag-description');
if(!description) description = jQuery('#description');
if(description){
var button = description.parents('form').find('#submit');
button.unbind('click');
button.on('click', function(e){
if(description.val().trim().length < 1)
console.log('Please enter a description...');
e.preventDefault();
return false;
});
}
});
</script>
The result is the same as approach #2. The form is still submitting, but I see the console log message.
Edit tag:
When editing tag, WordPress call wp_update_term. But there're no filters or AJAX call, so we must use get_term() which is called by wp_update_term():
add_filter('get_post_tag', function($term, $tax)
{
if ( isset($_POST['description']) && empty($_POST['description']) ) {
return new \WP_Error('empty_term_name', __('Tag description cannot be empty!', 'text-domain'));
} else {
return $term;
}
}, -1, 2);
We also need to update term_updated_message to make the error clear:
add_filter('term_updated_messages', function($messages)
{
$messages['post_tag'][5] = sprintf('<span style="color:#dc3232">%s</span>', __('Tag description cannot be empty!', 'text-domain'));
return $messages;
});
Because WordPress hardcoded the notice message div, I used inline css to make the error look like a waring. Change it to your preference.
Add new tag:
The AJAX request calls wp_insert_term so we can use pre_insert_term filter. Try this in your functions.php
add_filter('pre_insert_term', function($term, $tax)
{
if ( ('post_tag' === $tax) && isset($_POST['description']) && empty($_POST['description']) ) {
return new \WP_Error('empty_term_name', __('Tag description cannot be empty!', 'text-domain'));
} else {
return $term;
}
}, -1, 2);
Here I used the built-in empty_term_name error to show notice message but you should register your own one.
Also, take a look at wp_ajax_add_tag to fully understand what we're doing.
Demo:
It's Ajax so you cannot rely on submit event, here is a solution, how you can do.
All you want to do is include form-required class to the parent tag of the particular element, but there is kick on it. their validateForm check only on input tags not on textarea so I have implemented an idea, it works.
Try this
function put_admin_script() { ?>
<script>
jQuery(document).ready(function(){
var description = jQuery('#tag-description');
if( !description ) {
description = jQuery('#description');
}
if( description ) {
description.after( $('<p style="visibility:hidden;" class="form-field form-required term-description-wrap"><input type="text" id="hidden-tag-desc" aria-required="true" value="" /></p>') );
}
description.keyup(function(){
$("#hidden-tag-desc").val( $(this).val() );
});
jQuery("#addtag #submit").click(function(){
console.log("Not empty"+description.val().trim().length);
if( description.val().trim().length < 1 ) {
description.css( "border", "solid 1px #dc3232" );
} else {
description.css( "border", "solid 1px #dddddd" );
}
});
});
</script>
<?php
}
add_action('admin_footer','put_admin_script');
I'm trying to use angular to change the css class of an element when a user inputs data, both after a button click and in real time as the user is typing in data.
HTML:
<input type="text" class="defaultClass" ng-class="{true: 'errorClass',
false:'defaultClass'}[updateInput()]" ng-model="inputOne">
CSS:
.defaultClass {border: 1px solid #ccc;}
.errorClass {border: 1px solid #FF0000;}
After a button is pressed, the controller checks if the model of the element is blank and if so, makes the function return true and therefore changes the css class in the ng-class to show an error.
$scope.calcButton = function (){
if ($scope.inputOne === "" || $scope.inputOne === undefined) {
$scope.updateInput = function() {
return true;
};
} else {
$scope.updateInput = function() {
return false;
};
}
};
Outside of the button click function, I have the following code in the same controller that should be watching the status of $scope.inputOne and returning true or false based upon the status of the input:
$scope.updateInput = function() {
if ($scope.inputOne === "") {
return true;
} else {
return false;
}
};
And it works fine as long as I don't click the button, but once the value is changed by the button press the controller stops checking if the input field is empty or filled.
This is a problem because I want to have the error messages fade away as the user types in data after a button press that threw errors, but I can't change the css by user input at this point.
Why does it do this? How can I ensure that the controller still keeps track of what's going on in the input field after the button click?
Try like this
ng-class="{'errorClass' : !inputOne,'defaultClass': inputOne }"
or like this
ng-class="!inputOne ? 'errorClass' : 'defaultClass'"
'',null,NaN,undefined,0 etc considered false in JavaScript.
just check model has value or not.
It'll work through two way binding . don't need method for this to check
I have a phpwebsite that includes a header and footer on every page. On one of my pages I have a form called "orderForm" and onSubmit is equal to "return(validate())". In my header (which gets included on that page) I have a function called function validate().
My problem is trying to validate the order form from my header file. I know it partly works when my validate function consists of:
alert("Test");
return false;
As I get an alert when I submit the form.
But when I try something like:
if (document.orderForm.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
return false;
}
It doesn't validate it, despite orderForm and postcode being the correct names of the form fields. Is this because I am including the header file while having the form in a different file?
Cheers
If you want to test by name you can do this, assuming no other onload code in the page. The main point is to wait with assigning the validation until after the form exists on the page.
window.onload=function() {
document.orderForm.onsubmit=function() {
if (this.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
return false; //cancel submission
}
return true; // allow submission
}
}
To use preventDefault with my code you can try
window.onload=function() {
document.orderForm.onsubmit=function(e) {
var event=e?e:window.event;
if (this.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
event.preventDefault();
}
}
}
You need to add the «name» attribute in the form and the input tag.
In this scenario you must ensure that the fields are loaded on the page with window.onload.
You can assign a submit event to your form. In this context you can run your script to validate your field.
You must prevent the default action of the form with preventDefault().
This is the solution:
window.onload = function() {
var form = document.getElementById("orderForm");
form.addEventListener("submit", function(e) {
if (document.orderForm.postcode.value.length < 1) {
e.preventDefault(); // This prevents the default action to submit the form to the server.
alert("Postcode field cannot be empty.");
}
});
};
<form id="orderForm" name="orderForm">
<input id="postcode" name="postcode" type="text" />
</form>
I need to validate that both the domain field is correct and that the placeholder field has a value. Once both are true, the Submit button will show. Using jQuery validate, I can check that the domain is correct, but its not validating the placeholder field. The playerClass rule is not being applied:
$(function() {
$("#form").validate({
rules: {
playerClass: {
required: true
}
},
submitHandler: function() {
$("body").append("<p>Validation Complete!</p>");
}
});
});
jQuery.validator.addMethod("domainChk", function(value, element, params) {
$(".submit").show();
if (this.optional(element)) return true;
var regExp = new RegExp("^(?!www\\.|http:\/\/www\.)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
return regExp.test(value);
},
function errmess(params, element) {
$(".submit").hide();
return "Valid hostname required for player code";
});
jQuery.validator.addClassRules({
domainChk: {
domainChk: true
}
});
jsFiddle: Link
The playerClass rule is not being applied
Your second field, with name="playerClass" is not being validated because you've applied no validation rules to it. There is no such rule called playerClass in your jsFiddle or in your OP, and you've applied no rules to the playerClass field in your jsFiddle.
Even if playerClass was a custom rule, the form is considered valid because the playerClass field is optional in your jsFiddle. Without the required rule, when the field is left blank, it's valid.
You've also failed to close your <form> element in the jsFiddle. There is no </form> tag.
EDIT:
As per documentation, any ajax() should go inside the submitHandler function within the .validate() method.
In other words, you are breaking the validation plugin with your click handler.
I need to validate that both the domain field is correct and that the placeholder field has a value. Once both are true, the Submit button will show.
Then why are you showing the submit button from within the domainChk rule? Once this rule is passed, you're showing the button with $(".submit").show().
You would typically use the .valid() method to test the form and show/hide the button.
$('input[type="text"]').on('click keyup blur', function() {
if ($('#form').valid()) {
$(".submit").show();
} else {
$(".submit").hide();
}
});
This is much closer to how it should be: http://jsfiddle.net/e04rca0t/2/
I didnt know how to properly name my question, but here goes.
In my html i have a "form" but not
<form></form>
.It is just a couple of selects, radio buttons and text inputs.
I enter, check and select values and according to these values, some computation is done. This "form" is computing on every keydown, blur, change. So when I change one value it will immediately recalculate the results with new value.
I would like to alert the user, when he didnt fill any of the necessary inputs. Here is how it works now (this is in a separate .js file)
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
}
$(function () {
$('select, input').on('keydown blur change', calculator);
});
I tried to put a if statement inside of my calculator function:
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
if (val1 == '' && sadzba == '' && viem == '' && ...) {
alert('You have to fill all necessary fields!')
}
}
This obviously caused, that the alert was popped every time I enter / choose new value, because at the beginning all variables are empty / with no value.
So how can I achieve, this situation: User fills in the "form" except of (for example)one value and only then will the alert pop up.
Than you.
I suggest to do the check on submit and return false if one of the fields is empty, preventing the form to be submitted.
$('form').on('submit', function () {
if (val1 == '' || sadzba == '' || viem == '') {
alert('You have to fill all necessary fields!');
return false;
} else { return true; }
});
Use a different event handler for the onblur event since that's when the cursor has left the input box. (It also prevents the event handler from firing all the time. That's a pretty expensive process and it can slow your page down)
$('select, input').on('blur', didTheyLeaveTheFieldEmpty);
Hope I understood you right, you can try this:
function calculator(event) {
if ( $(event.target).val().length == 0 ) {
alert('fill the field');
}
}
$('select, input').on('keyup', calculator);
even if you don't want a form with a submit buton you can create a button
and trigger your code on it's click
<input type="button" class="calculate">
$(function () {
$('.calculate').on('click', calculator);
});