Skip to content

Instantly share code, notes, and snippets.

@WillBrubaker
Last active August 29, 2015 14:12
Show Gist options
  • Save WillBrubaker/3c9dd88ef85cce645bb2 to your computer and use it in GitHub Desktop.
Save WillBrubaker/3c9dd88ef85cce645bb2 to your computer and use it in GitHub Desktop.
WooCommerce Name Your Price - disable input
jQuery(document).ready(function($) {
//re-assign the error message variable - keep the minimum acceptable price concealed
if ( 'undefined' != typeof woocommerce_nyp_params ) {
woocommerce_nyp_params.minimum_error = 'Offer rejected';
}
//initially disable the price input
$('input#nyp').prop('disabled', true)
// WooCommerce outputs the product id in a hidden element within the add to cart form.
var productId = $('input[name="add-to-cart"]').val()
//need to use 'numeral' to account for prices with decimals - parseFloat hasn't got very wide browser support
var originalPrice = numeral( $('div.nyp').data('price') ).format('0.00')
var newPrice = originalPrice;//two values will be compared later, make them equal for now
//if there is a cookie set for this product, its name is 'haggledon-' plus the product id. Uses the cookie jQuery extension
var cookie = $.cookie('haggledon-' + productId)
if (cookie == null) {//there's no cookie, is there a transient?
// WooCommerce sets the admin-ajax url, so just borrow that
$.post(wc_add_to_cart_params.ajax_url, {
//In a php file, there's a call to add_action( wp_ajax_nopriv_haggle_transient. The action paramater
//is how admin-ajax knows how to route this call
action: 'haggle_transient',
pid: productId
}, function(data) {
if (!data.success) {
$('input#nyp').prop('disabled', false)//no cookie, no transient, ok to enable
}//if there was a transient, the input remains disabled
})
}//if there was a cookie, the input remains disabled
$('input#nyp').on('blur', function() {//bind a listner to the 'blur' event
//get the value that was input
newPrice = numeral($('input#nyp').val()).format('0.00')
if (newPrice < originalPrice) {//the price someone offered to pay is less than the suggested price
$('input#nyp').prop('disabled', true)//disable the input
//set a transient
$.post(wc_add_to_cart_params.ajax_url, {
action: 'haggle_transient',
pid: productId,
set: true//passing a third paramater to the AJAX handler this time - tell it to set a transient
})
if (null == cookie) {//set a cookie
$.cookie('haggledon-' + productId, 'true', {expires:1})
}
}
})
//enable the input on submit or things will fail
$('form.cart').on('submit', function() {
$('input#nyp').prop('disabled', false)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment