.val stops form from working - php

I have this checkout page (you will have to add an item) Which uses the JavaScript / jQuery seen in this jsFiddle to show/hide some fields for a separate shipping address. When showing, I set the value of all fields to '' and when hiding I set the values of the fields to the same as their respective fields in the billing form.
When you submit the form you should be taken to the paypal login screen (try filling out the form without toggling the different shipping address and submitting) but if you toggle the shipping address it just comes back to the same page.
I have debugged enough to know that it is modifying the fields with .val() that is breaking the form. If I comment out those bits and manually toggle visibility with dev tools, or if I fill out the billing form and never show/hide the shipping (so .val() is never called), everything works fine.
If you are going to look at that page and give it a try, you know its successful if you get to the paypal screen, otherwise it is just coming back to the same page (the form's action is to the same page, but I can't find anything that processes the data - the full php page can be found here - it is a modified version of WPEC's shopping cart page
Here is (most of) the relevant JavaScript:
$('#reveal-shipping').click(function(){
if ( $('.wpsc_checkout_table.table-2').is(':animated') ) return;
if( $('.wpsc_checkout_table.table-2').css('display') == 'none' ){
$('.wpsc_checkout_table.table-2').slideToggle();
$('.wpsc_checkout_table.table-2').find('input, select, textarea').val('');
document.getElementById('reveal-shipping').innerHTML = 'Ship to my billing address ←';
} else {
for ( i=0; i < fields.length; i++ ){
thisval = $(fields[i][0]).val();
$(fields[i][1]).val( thisval );
}
$('.wpsc_checkout_table.table-2').slideToggle();
document.getElementById('reveal-shipping').innerHTML = 'Ship to a different address →';
}
});
You can find the rest on the jsFiddle and on the page itself
Thanks so much in advance for any help I'm really stuck on this!

I think the problem is that you are using display: none to hide the "different shipping adress". When a input field has display none, it will not be sent with your formular. And because of that it redirects you back to the checkout page.
You could use visibility: hidden, but then it would still take up space.
But i strongly recommend you do not do it this way, because if the user has turned javascript off it won't work. You should send all the field and in php, check whether the different adress fields have been submitted, and if they have, use them.
Edit: You could use position to place them outside of the window, like:
position:absolute;
top: -9999px;
visibility:hidden;

Related

Problem with recaptcha working correctly with a contact form 7

I'm currently using wordpress with contact form 7 together with recaptcha on two different kind of pages a customers site we are building.
Contact form: https://www.alvestadtanken.se/kontakt/ (working without problem)
Variable products without price: https://www.alvestadtanken.se/butik/dieseltankar/stationara-dieseltankar-1300-9000-liter/dieseltank-fm-5000-l/ (recaptcha dosnt load correctly and it wont submit because of missing values)
I have tried several different approaches and have boiled it down to the only difference is that on the page 2 we are loading the contact form 7 after the page is initialized trough a ajax request when the actual value (see pumpalternativ in image below) is choosen in a dropdown menu. What i think is that i need to reload/set the recaptcha after the contact form 7 is loaded, but i dont have any idea how to do this.
// Displays contact form for variations with no price(0kr) or add to cart button if price exists.
add_filter( 'woocommerce_available_variation', 'empty_and_zero_variation_prices_html', 10, 3);
function empty_and_zero_variation_prices_html( $data, $product, $variation ) {
if( '0' === $variation->get_price() || '' === $variation->get_price() || 0 == $variation->get_price() ){
$data['price_html'] = __('<div class="wpcf7-wrapper"><h5 class="text-primary font-weight-bold">Kontakta oss angående produkten</h5> ' . do_shortcode( '[contact-form-7 id="7336" title="Prisförfrågan"]' ) . '</div> ', 'woocommerce');
$data['is_purchasable'] = false;
} else {
$data['price_html'] .= __(do_shortcode( '[add_to_cart_button]' ));
}
return $data;
}
All ideas and help are welcome.
The way WordPress works, a shortcode can do more than just render markup in your code. Specifically it can call functions like wp_enqueue_script, which do things like render additional javascript in the footer that often provide code for loading forms added dynamically to a page or preparing Recaptcha.
In short, it's unlikely you're going to be able to easily achieve loading that form dynamically via AJAX. If you're expecting the form to render without any user interaction, then I would consider having the form render in a hidden div and then using your client-side javascript that is currently pulling in the form via AJAX simply set that div to display.
If you must keep your current approach of loading via AJAX, then you'll need to dig into the Contact Form 7 code (or perhaps manual) to see what options you might have either via hooks they provide or a javascript API that will allow you to load it on your own after you've retrieved the markup.

Woocommerce product addon (how to limit checkbox selections?)

Can somebody help me with a situation I am facing?
I'm using a woocommerce table plugin (wct) + woocommerce product addon. If you click on the button to select a pizza, it opens a lightbox popup with some ingredients options.
It's almost perfect, but the point is that i need the user to choose until three options (and not being able to mark all those options), but at least one (this part is solved, because it is a required field).
What if were 2 (min) and 4 (max) ingredients?
Do you know how can I solve that or even another plugin that does the job? I've checked a demo of a plugin, but it allows you to select how many checkboxes you want and only shows a error msg after you click on "buy" buttom. I guess that this method won't work within a lightbox, that it will just close the popup and show the msg at the top of the page.
Thank you so much for your attention.
ingredients lightbox options
You can use jQuery to count how many checkboxes have been checked. When the number is between 1 und 3, the submit button is clickable. If not, the button is disabled.
In my example your checkboxes have the class of check and your submit button the id of sbmBtn so we have access to the elements. Put this is the footer.php file of your theme or just where you want to place the javascript code in your theme files.
<script>
( function( $ ) {
window.updateCount = function() {
var checkcounter = $(".check:checked").length;
};
if(checkcounter == 1 || checkcounter >= 4) {
$("#sbmBtn").attr("disabled", true);
}
else { $("#sbmBtn").attr("disabled", false); }
}( jQuery ) );
</script>
This code will save the number of checked checkboxes in the variable called checkcounter. After that, we check if it has the value we want it to have and disable or enable the button in the different cases.

Magento show Address fields and validate registration form only under some conditions

I'm trying to customize the form for customer account creation and I would like to use the same form for different types of customers, i.e. private and companies.
What I want to achieve is using the same form for both and show different fields according to the choice of the user: if user choose 'private' he has to fill in some fields, if he chooses 'company', additional fields - for the address and VAT - are shown.
So i've enabled address fields in the local.xml and they're correctly shown or hidden, depending on which button (private or company) is chosen.
The problem is that if I simply hide the address fields, form is validated also on those fields, unless I put a
$this->setShowAddressFields(false);
just before the
if($this->getShowAddressFields()): ?
to hide address fields and suppress validation.
I've also put
<input type="hidden" name="create_address" value="0" />
to skip addresss fields validation.
So I've tried with jquery to change the setShowAddressFields whenever the user click the button to choose its type, something like
$('#choose-type button').click(function(){
if($(this).val() == 'private'){
$(this).addClass('selected');
$('#choose-type button').last().removeClass('selected');
$('.required-company').removeClass('visible');
<?php $addrEnabled = $this->setShowAddressFields(false) ?>
}else{
$(this).addClass('selected');
$('#choose-type button').first().removeClass('selected');
<?php $addrEnabled = $this->setShowAddressFields(true) ?>
$('.required-company').addClass('visible');
}
});
I've also tried to show two different forms, in the same template, one with $this->setShowAddressFields(false) and the other with $this->setShowAddressFields(true) and show/hide the right form, and validate with Varien the right form, like this
var dataForm = new VarienForm('form-validate', true);
var dataFormbis = new VarienForm('form-validate-bis', true);
but still no luck.
So it is possible to achieve something like this in the same template, or I have to forcedly create two different templates?
Dunno if it can be of help for someone, but I came up with my own solution (even though I don't really like it totally, and dunno if it is the correct way).
I finally succeeded with the last part of my question, thus creating 2 different forms and creating a validation for each of them.
The first form has the <?php $addrEnabled = $this->setShowAddressFields(false) ?>, whereas the second has it set to true.
Forms have different ids to identify them, one has id='form-private' and the other id='form-company'.
Then in my script I have
validateRegistration('private','company');
$('#choose-type button').click(function(){
($(this).val() == 'private') ? validateRegistration($(this).val(), 'company') : validateRegistration($(this).val(), 'private');
});
function validateRegistration(userType,userTypeBis){
$("#form-"+userType + "").css('display', 'block');
$("#form-"+userTypeBis + "").css('display', 'none');
var dataForm = new VarienForm('form-'+userType+'', true);
$("#form-"+userType + "").submit(function(e){
if(//some custom condition to avoid validation in case some custom fields are not in the way i need ) {
e.preventDefault();
}
else {
dataForm.validator && dataForm.validator.validate();
}
});
}
</script>
Please note that the submit() is called inside the dataForm.validator.validate() if the validation is passed, so my custom conditions should not be needed (the if-else), I think the important thing is to have two different forms with two different validations.
Hope this helps

Cannot change form data using getElementsByName

I am building an ecommerce site on Wordpress to be used by multiple agents. At present, the page uses a standard PayPal link which includes the line:
<input type="hidden" name="business" value="somewhere#this-site.com">
My theory WAS that I could use PHP to get new user's business email address from my site, and then use javascript to change the value. For test purposes, I 'faked' the former, and so used this code ...
<script language="javascript">
// alert(document.getElementsByName('business').value);
document.getElementsByName('business').value='changed#paypal_address.com';
alert(document.getElementsByName('business').value);
</script>
IN THEORY, the page should now have a revised "business" field - but it stayed the same. So I added the second commented out alert ... which - when the page was reloaded - came back as 'undefined'
I cannot check data via forms as there are several (un-named) forms on the page, (such as form buttons with no action field that are used as delete items from cart buttons, and the PayPal webscr form which is also un-named)
Although the code is in a footer widget, I know it's loading / running as I get the alert pop ups. It also executes PHP code within the footer as it loads the page.
Is there a restriction whereby "hidden" fields cannot be found, or altered dynamically? If so, is there any work around?? (If all else fails, will have to contact the UltraCart pugin team to see if the business name can be set at source)
Try this:
function setValueForElementsByName(name, value) {
var elements = document.getElementsByName(name);
for(var e in elements) {
elements[e].value = value;
}
}
setValueForElementsByName('business', 'changed#paypal_address.com');
getElementsByName returns a NodeList. Therefore, you need to access individual items by index like
document.getElementsByName('business')[0].value
If you wish to modify multiple elements with the same name, simply iterate over them like
var elements = document.getElementsByName('business');
for(var i=0; i < elements.length; i++){
elements[i].value = ...;
}
document.getElementsByName('business')[0].value='changed#paypal_address.com';
alert(document.getElementsByName('business')[0].value);
<input type="hidden" name="business" value="somewhere#this-site.com">

jQuery show/hide fields doesn't pass php validation

I've a jQuery code which show/hide some disabled fields, based on an user select option:
$('.fieldcontent').not('.info').hide();
$('#selector_cs').change(function() {
$('.fieldcontent').customFadeOut(100);
$('.' + $(this).val()).customFadeIn(900);
$('input').prop('disabled',false);
$('textarea').prop('disabled',false);
$('select').prop('disabled',false);
});
});
The big headache is: if one or more fields are fading in, these fields doesn't pass my php validation, nor submitting the form.
If javascript is disabled on all browsers, the form works perfectly.
PHP validation is
if(!isset($_POST['products'])) {
$products[2] = clean_var($_POST['products']);
}
else {
$error = 1;
$products[3] = 'color:#FF0000;';
}
for all fields
Is there any php /jquery solution (no ajax please, 'cause i won't make the whole form again, and don't know anything about ajax)?
Thanks in advance for help
EDIT: Just detected another error: If the jquery script fadein another section of the form, PHP doesn't validate it anymore. Why? Never had problems like this with php-jquery.
If you leave them enabled, but change the property type to hidden then PHP should see the fields when you submit them.
Update
How about the following scenario:
5 fields shown
start-hiding two fields (A+B)
'add' two type=hidden fields with the same name as A+B and copy their current value from A+B to `A+`B
PHP should see these two hidden fields instead of the fields that are currently fading out.
If the user did not submit while fading out, then when the fields have faded out remove the `A+`B fields and set the property of the two faded fields to hidden
Inverse this for showing them fields again.
Do take note that this is not a problem caused by PHP but caused by how/when a browser interprets a form field to be a valid form field to be send when submitting the form

Categories