Change Background Of Div Once Contact Form 7 Is Submitted - javascript

So I'm trying to add a class to the container (.right-side-product-page) and the h2 on a contact 7 form. Here's a link:
https://nameplicity.com/domains/miningaid/
The goal is to change the class so the blue background and gray background become white, but only after an offer is submitted.
I've tried to add CSS and JavaScript, but can't seem to get anything working. Here is the code I've tried to use in the "Additional Settings" section under the Contact Form 7 plugin:
document.addEventListener( 'wpcf7submit', function( event ) {
if ( '19533' == event.detail.contactFormId ) {
var theDropDown = document.querySelector(".right-side-product-page");
theDropDown.classList.add("MyClass");
}, false );
Could anyone provide direction as to what I'm doing wrong?

There's an error in your code: you're missing one curly bracket in there.
Try this:
<script>
document.addEventListener( 'wpcf7submit', function( event ) {
if ( '19533' == event.detail.contactFormId ) {
var theDropDown = document.querySelector(".right-side-product-page");
theDropDown.classList.add("MyClass");
}
}, false );
</script>

Aside from the error which was mentioned above, you can further complete your solution based on the class added to the wpcp7-response-output block, upon successfully sending the message, the wpcf7-mail-sent-ok class is added. Knowing this, we can utilize these classes with a check, here's an example:
$( document ).ready(function() {
var outputBlock = $(".wpcf7-response-output");
var theDropDown = document.querySelector(".right-side-product-page");
$( ".wpcf7-submit" ).click(function() {
//Start an interval check after submit has been clicked
var intervalCheck = setInterval(function () {
if (outputBlock.hasClass("wpcf7-mail-sent-ok")) {
// The form has been submitted successfully, set the class to the block to change color
theDropDown.classList.add("MyClass");
// Stop running the interval checker after class has been added
clearInterval(intervalCheck);
}
},1000);
});
});

Try:
document.querySelector('.wpcf7-form').addEventListener('submit', function (ev) {
if(this['_wpcf7'].value == '19533') {
document.querySelector(".right-side-product-page").classList.add("MyClass");
}
});
or
document.querySelector('.wpcf7-form').addEventListener('wpcf7submit', function (ev) {
if(this['_wpcf7'].value == '19533') {
document.querySelector(".right-side-product-page").classList.add("MyClass");
}
}, false);
One of them should work. I believe the issue is that the event wpcf7submit you're listening to does not exist on document. It exists on document.querySelector('.wpcf7-form').

Got it!
Had to put it right under the submit button and encase it in tags. Thank you everyone for your help!!!

Related

Ajax / Javascript - Remove Links After 1 Link Has Been Clicked

I have the following script which fetches data (branch names) asynchronously via database:
$(document).ready(function () {
$("#pickup").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'modal/fetch_branch.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
// return false to prevent default action
return false;
});
}
});
});
});
HTML
<input type="text" class="form-control empty" name="keyword" id="pickup" placeholder=""/>
Everything is working perfectly, When user clicks link the data (branch name) gets added to the text input field, which is exactly what needs to happen, however...
My Problem
After user has clicked on desired link (branch name) I need the remaining links (data / branch names) to get removed...
As can be seen from above image Stellenbosch was selected, thus I need the other links to get removed...
Any advice how I can achieve the following greatly appreciated.
UPDATE
Here is the fetch_branch.php file as requested:
if(mysqli_num_rows($result) < 1 ) // so if we have 0 records acc. to keyword display no records found
{
echo '<div id="item">Ah snap...! No results found :/</div>';
} else {
while ($row = mysqli_fetch_array($result)) //outputs the records
{
$branch = $row['location'];
echo '<a style="cursor:pointer">'.$brach.'</a>';
echo'<br />';
}//while
}//else
}//if
I'm making a different assumption from the other answers here, because I can't understand why you'd want to remove the other links in the dropdown, after clicking one!
As can be seen from above image Stellenbosch was selected, thus I need the other links to get removed...
If that is indeed the case, you'll want to accept #acontell's answer.
However, if you'd like the clicked link to disappear from your list, you might try something like this in the click handler:
$("#results").on("click", "a", function() {
$this = $(this);
$("#pickup").val($this.text());
// Remove the linebreaks output by modal/fetch_branch.php
$this.next('br').remove();
// Remove the clicked <a> tag itself
$this.remove();
// return false to prevent default action
return false;
});
In case you'd like the whole dropdown to disappear when clicked, do this: (which, I think is common, no?)
$("#results").on("click", "a", function() {
$("#pickup").val($(this).text());
$("#results").slideUp();
return false;
});
try $(this).siblings().remove(); inside your click event. so your function should look like this,
$(document).ready(function () {
$("#pickup").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'modal/fetch_branch.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
//------------------
//only this line is newly added
//------------------
$(this).siblings().remove();
//------------------
// return false to prevent default action
return false;
});
}
});
});
});
After selecting the item and setting the text to input add the following code snippet
$(this).siblings().remove();
This removes all the sibling li s of the selected item
or
$( "#results a" ).not(this).remove();
If I'm not mistaken, I think it could be done with a little modification to your code:
...
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
// --MODIFICATION-- Remove all elements except this.
$("#results").html(this);
// return false to prevent default action
return false;
});
}
...
The idea is to substitute the html of the link container (it contains all the links) with the HTML of the clicked link. In essence, it will remove all and leave only the clicked one.
Here's a fiddle (without AJAX) that represents the idea. Hope it helps.
Please check this link for a working demo. Click Here
I used dummy data and use changed keyup event to focus for testing you can modify it more (if this helps).
I hope this will help you.
Thanks,
I don't understand you. However, if you mean hide result after link clicked, you can use
$("#results").slideUp('fast');
within onclick event.
Also you can remove other links and live clicked.
$("#results").on("click", "a", function() {
$("#pickup" ).val($(this).text());
$(this).addClass('selected');
$("#results a:not(.selected)").remove();
$(this).removeClass('selected');
return false;
});

How to make a tag description required

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');

How to: jQuery/JS Dialog box with checkbox on a link with click event (to go to that link)

I've been asked for a simple solution to add to links on a blog that would pop-up a warning before going to that link. Only if you agree do you go on to that link. The first solution works fine (and I got it here):
<script type="text/javascript">
function confirm_alert(node) {
return confirm("some message here");
}
</script>
Click Me
However, now I've been asked to have a checkbox in the pop-up that says something like "I understand" and then a button to continue. If it isn't checked or if they click outside the box (or the X close button if there is one), then it just goes back to the page they were on. If it IS checked and they click continue it goes to the URL on the link (as above).
Along with this, I need to set a browser cookie ONLY if the dialog is checked and continue hit. I've set cookie's in browser with JS before, but not attached to to an event like this, so I'm not sure how to do that either.
I've done many searches here and on the net in general and can't seem to find any examples that do this. I have found that there's no way to do this with a standard confirm dialog and would need to use jQuery and that's fine, but I still can't find an example.
Any help is much appreciated.
I haven't tested this code (I just free typed it here).
In the HTML:
<div id="agreeModal">
<input id="agree" type="checkbox" />
<button id="btnCancel">Cancel</button>
<button id="btnContinue">Continue</button>
</div>
JavaScript (in another file or in a <script> tag) :
document.addEventListener('DOMContentLoaded', function() {
var agreeUrl = '';
// Get the links on the page
var links = document.querySelectorAll('a');
links.addEventListener('click', function( event ){
event.preventDefault(); //stop it from following link
agreeUrl = this.getAttribute('href'); // get the url
document.getElementById('agreeModal').style.display='block'; //show Modal
});
var btnContinue = document.getElementById('btnContinue');
btnContinue.addEventListener('click', function( event ) {
event.preventDefault();
var cb = document.getElementById('agree');
if (cb.checked) { //if checkbox is checked goto url
location.href= agreeUrl;
}
});
var btnCancel = document.getElementById('btnCancel');
btnCancel.addEventListener('click', function( event ) {
event.preventDefault();
//hide Modal
document.getElementById('agreeModal').style.display='';
});
});
Same code in jQuery:
(function( $ ){
$(function(){
var agreeUrl='';
$('a').on('click', function( event ){
event.preventDefault(); //stop it from following link
agreeUrl = $(this).attr('href'); // get the url
$('#agreeModal').show(); //show Modal
});
$('#btnContinue').on('click', function( event ) {
event.preventDefault();
if ($('#agree').prop('checked')) { //if checkbox is checked goto url
location.href= agreeUrl;
}
});
$('#btnCancel').on('click', function( event ) {
event.preventDefault();
//hide Modal
$('#agreeModal').hide();
});
});
})( jQuery);
Hope that helps!

modal popup displays different text depending on input

So I am attempting to have a modal popup that displays two messages depending on what the user types into the text box. I want the script to check whether the input contains one of two strings, either ME, or TN (as I am looking at doing a postcode checker).
no matter what i try I can't get the popup to display two messages depending on the input. I don't want the form to submit, I just want to grab the contents of what has been typed.
Here's a link to what I have so far (imagine the close icon is in the top right)..
$(document).ready(function () {
var formResult = $('#postcode-form')
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
http://www.muchmorecreative.co.uk/modal_test/basic-modal-testing-jquery-conditions/
try this:
$(document).ready(function() {
var formResult = $('#postcode-form')
var postcodeMe= /^[me]+$/;
$( "#postcode-form" ).click(function(e) {
e.preventDefault();
if ($(this).val().contains(postcodeMe)){
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
The problem is you're setting formResult as a 'global' variable (sorta). It gets its value when the page loads and never changes. You should change your code to get the value when you actually need it, not immediately after page load.
$(document).ready(function () {
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
//move it to here so that you get the value INSIDE the click event
var formResult = $('#postcode-form')
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
A few other minor things to consider:
indexOf returns a number. You should probably do indexOf(postcodeMe) >= 0
You can look at index of HERE
Have tried these two but not happening, played around with it and found a solution..
$(document).ready(function() {
var formResult = $('#postcode-input')
$( "#postcode-button" ).click(function(e) {
e.preventDefault();
if ($('#postcode-input').val().indexOf("ME")!==-1 || $('#postcode- input').val().indexOf("me")!==-1 ){
// perform some task
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
Thanks for the help though!

Removing a class from all input elements

I want to remove a class from my input elements.I'm using Data Annotations in MVC and unobtrusive javascript for validation,anyway, when user clicks submit button I want to remove valid class from all input elements, because it change all unnecessary input's (non-required) valid (green border color) and it's not looking good.Anyway, I try this:
$("#submitBtn").click(function () {
if ($(".input-validation-error").length == 0) { // if there is no error
$(this).button('loading');
} else {
$("input").each(function () {
$(this).removeClass("valid");
});
}
And it didn't work, also tried:
$("input").removeClass("valid");
It didn't work either.And I thought maybe it's working before the validation and valid class adding after the click event automatically.So I try this:
setInterval(function() {
$("input").each(function() {
$(this).removeClass("valid");
});
}, 1000);
But still no success. I don't know jQuery very well, probably I'm missing something simple.What is the problem?
if the class is attached to the input element then it should be as simple as
$("input.valid").removeClass('valid')
As it turned out OP didn't want the valid highlight to be applied so setting the validClass to '' fixed it
For the page the default validClass was set using
jQuery.validator.setDefaults({ validClass: '' });
Try to wrap your code inside DOM ready:
$(document).ready(function() {
$("#submitBtn").click(function () {
if ($(".input-validation-error").length == 0) { // if there is no error
$(this).button('loading');
} else {
$("input").each(function () {
$(this).removeClass("valid");
});
}
})
Check out this fiddle:
http://jsfiddle.net/dwQb4/1/
$("input").removeClass("valid");
There are 3 inputs with class="valid" that turns them green and some jquery to remove the class
this may help you

Categories

Resources