Drupal disable button after clicking 3 times in drupal custom module - javascript

I'm new to Drupal
I built custom module similar to webform
my module page contains two submit buttons and 2 textbox as below :
function contact_request($form, &$form_state) {
$form ['info'] =array(
'#markup' => "<div id='pageRequestDiv'>",
);
$form['number'] = array(
'#prefix' => '<div class="webform-container-inline2">',
'#suffix' => '</div>',
'#type' => 'textfield',
'#title' => t('Number'),
'#size' => 20,
'#maxlength' => 255,
'#attributes'=>array('class'=>array('txtli')),
'#required'=>true,
);
$form['send_vcode'] = array(
'#prefix' => '<div style="margin-top:30px;">',
'#suffix' => '</div><br/><br/>',
'#type' => 'submit',
'#value' => t('Send Verification Code'),
'#ajax' => array(
'callback' => 'send_Verification_code_callback',
'wrapper' => 'ContactUsMsgDiv',
'method'=>'replace',
'effect'=>'fade',
),
);
$form['verification_code'] = array(
'#prefix' => '<div class="webform-container-inline2">',
'#suffix' => '</div>',
'#type' => 'textfield',
'#title' => t('Verification Code'),
'#size' => 20,
'#maxlength' => 255,
'#attributes'=>array('class'=>array('txtli')),
'#required'=>true,
);
$form['sendmail'] = array(
'#prefix' => '<div style="margin-top:30px;">',
'#suffix' => '</div></div>',
'#type' => 'submit',
'#value' => t('Send Request'),
'#ajax' => array(
'callback' => 'get_contact_us_callback',
'wrapper' => 'ContactUsMsgDiv',
'method'=>'replace',
'effect'=>'fade',
),
);
return $form;
}
the user enter number then first button send him sms to mobile after that he typed sms in second text box then click send.
I want to disable first button after user clicking it 3 times.
I tried the JS below but it's disable both buttons after one click. I want to disable first button only after 3 clicks
Drupal.behaviors.hideSubmitButton = {
attach: function(context) {
$('form.node-form', context).once('hideSubmitButton', function () {
var $form = $(this);
$form.find('input.form-submit').click(function (e) {
var el = $(this);
el.after('<input type="hidden" name="' + el.attr('name') + '" value="' + el.attr('value') + '" />');
return true;
});
$form.submit(function (e) {
if (!e.isPropagationStopped()) {
$('input.form-submit', $(this)).attr('disabled', 'disabled');
return true;
}
});
});
}
};
Updated code :
function send_Verification_code_callback($form, &$form_state){
some code to send sms
return $form;
}
function contact_us_request($form, &$form_state) {
$form['#prefix'] = '<div id="my-form-wrapper">';
$form['#suffix'] = '</div>';
$form ['info'] =array(
'#markup' => "<div id='pageAbiliRequestDiv'>",
);
$form['contact_number'] = array(
'#prefix' => '<div class="webform-container-inline2">',
'#suffix' => '</div>',
'#type' => 'textfield',
'#title' => t('Contact Number'),
'#size' => 20,
'#maxlength' => 255,
'#attributes'=>array('class'=>array('txtabili')),
'#required'=>true,
);
$form['verification_code'] = array(
'#prefix' => '<div class="webform-container-inline2">',
'#suffix' => '</div>',
'#type' => 'textfield',
'#title' => t('Verification Code'),
'#size' => 20,
'#maxlength' => 255,
'#attributes'=>array('class'=>array('txtabili')),
'#required'=>true,
);
$form['send_vcode'] = array(
'#prefix' => '<div style="margin-top:30px;">',
'#suffix' => '</div><br/><br/>',
'#type' => 'submit',
'#value' => t('Send Verification Code'),
'#ajax' => array(
'callback' => 'send_Verification_code_callback',
'wrapper' => 'my-form-wrapper',
'method'=>'replace',
'effect'=>'fade',
),
);
$form['sendmail'] = array(
'#prefix' => '<div style="margin-top:30px;">',
'#suffix' => '</div></div>',
'#type' => 'submit',
'#value' => t('Send Request'),
'#ajax' => array(
'callback' => 'get_contact_us_callback',
'wrapper' => 'ContactUsMsgDiv',
'method'=>'replace',
'effect'=>'fade',
),
);
$form['clicks'] = array(
'#type' => 'value',
);
if (isset($form_state['values']['clicks'])) {
if ($form_state['values']['clicks'] == 3) {
$form['send_vcode']['#disabled'] = TRUE;
} else {
$form['clicks']['#value'] = $form_state['values']['clicks'] + 1;
}
} else {
$form['clicks']['#value'] = 0;
}

I'd use AJAX callback rather than JavaScript check.
Wrap the whole form with some div:
$form['#prefix'] = '<div id="my-form-wrapper">';
$form['#suffix'] = '</div>';
and set
$form['send_vcode'] = array(
...
'#ajax' => array(
'wrapper' => 'my-form-wrapper',
...
(and also include your message area into the form). In your send_Verification_code_callback function return the whole form.
The trick is then to add value component to the form which will contain number of clicks:
$form['clicks'] = array(
'#type' => 'value',
);
if (isset($form_state['values']['clicks'])) {
if ($form_state['values']['clicks'] == 3) {
$form['send_vcode']['#disabled'] = TRUE;
} else {
$form['clicks']['#value'] = $form_state['values']['clicks'] + 1;
}
} else {
$form['clicks']['#value'] = 0;
}
After 3 clicks on send_vcode button it will be disabled.
=== UPDATE ===
Here is working code (without all unnecessary stuff), which shows amount of clicks left in the pageAbiliRequestDiv div:
function contact_us_request($form, &$form_state) {
$form['#prefix'] = '<div id="my-form-wrapper">';
$form['#suffix'] = '</div>';
$form['clicks'] = array(
'#type' => 'value',
);
$clicks_max = 3;
if (isset($form_state['values']['clicks'])) {
$form['clicks']['#value'] = $form_state['values']['clicks'] + 1;
$clicks_left = $clicks_max - 1 - $form_state['values']['clicks'];
} else {
$form['clicks']['#value'] = 0;
$clicks_left = $clicks_max;
}
$form ['info'] =array(
'#markup' => '<div id="pageAbiliRequestDiv">'
. t('Clicks left: #clicks_left', array('#clicks_left' => $clicks_left))
. '</div>',
);
$form['send_vcode'] = array(
'#prefix' => '<div style="margin-top:30px;">',
'#suffix' => '</div><br/><br/>',
'#type' => 'button',
'#value' => t('Send Verification Code'),
'#ajax' => array(
'callback' => 'send_Verification_code_callback',
'wrapper' => 'my-form-wrapper',
'method'=>'replace',
'effect'=>'fade',
),
);
if ($clicks_left == 0) {
$form['send_vcode']['#disabled'] = TRUE;
}
return $form;
}
function send_Verification_code_callback($form, &$form_state) {
return $form;
}

Related

php Redirect url to a Ifram

Please accept my apology in advance if my question is long.
I am using a payment gateway of woocommerce.
When click on checkout it goes to an external link. Then there We have button to click and Then It goes to another link which make it enable to pay via cards.
Now What I want to do is that.
I want to minimize some step.
1- If possible I want to bypass detail page which appears after click on Checkout button.
2- Is this possible to hide amount on detail page. As my website currecny is different and this payment gateway the show in different.
3- If above 1,2 not possible. Can simply put external pages in a iframe.
So if user click on check out. It should show a ifram on new page current page with redirected link.
Below code is from gateway plugin.
<?php
add_action( 'plugins_loaded', 'init_pp_woo_gateway');
function mib_ppbycp_settings( $links ) {
$settings_link = 'Setup';
array_push( $links, $settings_link );
return $links;
}
$plugin = plugin_basename( __FILE__ );
add_filter( "plugin_action_links_$plugin", 'mib_ppbycp_settings' );
function init_pp_woo_gateway(){
if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;
class WC_Gateway_MIB_PayPro extends WC_Payment_Gateway {
// Logging
public static $log_enabled = false;
public static $log = false;
var $merchant_id;
var $merchant_password;
var $test_mode;
var $plugin_url;
var $timeout;
var $checkout_url;
var $api_url;
var $timeout_in_days;
public function __construct(){
global $woocommerce;
$this -> plugin_url = WP_PLUGIN_URL . DIRECTORY_SEPARATOR . 'woocommerce-paypro-payment';
$this->id = 'mibwoo_pp';
$this->has_fields = false;
$this->checkout_url = 'https://marketplace.paypro.com.pk/';
$this->icon = 'https://thebalmainworld.com/wp-content/uploads/2020/10/Credit-Card-Icons-copy-1.png';
$this->method_title = 'Paypro';
$this->method_description = 'Pay via Debit/Credit card.';
$this->title = "Paypro";
$this->description = "Pay via Debit/Credit card.";
$this->merchant_id = $this->get_option( 'merchant_id' );
$this->merchant_password = trim($this->get_option( 'merchant_password' ));
$this->merchant_secret = $this->get_option( 'merchant_secret' );
$this->test_mode = $this->get_option('test_mode');
$this->timeout_in_days = $this->get_option('timeout_in_days');
$this->debug = $this->get_option('debug');
$this->pay_method = "Paypro";
if($this->timeout_in_days==='yes'){
$this->timeout = trim($this->get_option( 'merchant_timeout_days' ));
}
else{
$this->timeout = trim($this->get_option( 'merchant_timeout_minutes' ));
}
if($this->test_mode==='yes'){
$this->api_url = 'https://demoapi.paypro.com.pk';
}
else{
$this->api_url = 'https://api.paypro.com.pk';
}
$this->init_form_fields();
$this->init_settings();
self::$log_enabled = $this->debug;
// Save options
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// Payment listener/API hook
add_action( 'woocommerce_api_wc_gateway_mib_paypro', array( $this, 'paypro_response' ) );
}
function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Yes', 'woocommerce' ),
'default' => 'yes'
),
'merchant_id' => array(
'title' => __( 'Merchant Username', 'woocommerce' ),
'type' => 'text',
'description' => __( 'This Merchant Username Provided by PayPro', 'woocommerce' ),
'default' => '',
'desc_tip' => true,
),
'test_mode' => array(
'title' => __( 'Enable Test Mode', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Yes', 'woocommerce' ),
'default' => 'yes'
),
'merchant_password' => array(
'title' => __( 'Merchant Password', 'woocommerce' ),
'type' => 'password',
'description' => __( 'Merchant Password Provided by PayPro', 'woocommerce' ),
'default' => __( '', 'woocommerce' ),
'desc_tip' => true,
),
'merchant_secret' => array(
'title' => __( 'Secret Key', 'woocommerce' ),
'type' => 'password',
'description' => __( 'Any Secret Key Or Word with No Spaces', 'woocommerce' ),
'default' => __( rand(), 'woocommerce' ),
'desc_tip' => true,
),
'merchant_timeout_minutes' => array(
'title' => __( 'Timeout (In Minutes)', 'woocommerce' ),
'type' => 'number',
'description' => __( 'Timeout Before order expires it can be between 5 to 30 minutes', 'woocommerce' ),
'default' => __( 5, 'woocommerce' ),
'desc_tip' => true,
'custom_attributes' => array(
'min' => 5,
'max' => 30
)
),
'timeout_in_days' => array(
'title' => __( 'Enable Timeout in days', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Yes', 'woocommerce' ),
'default' => 'no'
),
'merchant_timeout_days' => array(
'title' => __( 'Timeout (In Days)', 'woocommerce' ),
'type' => 'number',
'description' => __( 'Minimum 1 day Max 3 Days. Remember, It works as due date you\'ve selected 1 day the expiration date of the PayPro id will be set as the day after today.', 'woocommerce' ),
'default' => __( 1, 'woocommerce' ),
'desc_tip' => true,
'custom_attributes' => array(
'min' => 1,
'max' => 3
)
),
'debug' => array(
'title' => __( 'Debug Log', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable logging', 'woocommerce' ),
'default' => 'no',
'description' => sprintf( __( 'Debug Information <em>%s</em>', 'woocommerce' ), wc_get_log_file_path( 'paypro' ) )
),
);
}
/**
* Logging method
* #param string $message
*/
public static function log( $message ) {
if ( self::$log_enabled ) {
if ( empty( self::$log ) ) {
self::$log = new WC_Logger();
}
$message = is_array($message) ? json_encode($message) : $message;
self::$log->add( 'paypro', $message );
}
}
/**
* Process the payment and return the result
*
* #access public
* #param int $order_id
* #return array
*/
function process_payment( $order_id ) {
$order = new WC_Order( $order_id );
$paypro_args = $this->get_paypro_args( $order );
$paypro_args = http_build_query( $paypro_args, '', '&' );
$this->log("========== Payment Processing Started: args =========");
$this->log($paypro_args);
//if demo is enabled
$checkout_url = $this->checkout_url;;
return array(
'result' => 'success',
// 'redirect' => 'http://localhost:8000/secureform?'.$paypro_args
'redirect' => 'https://marketplace.paypro.com.pk/secureform?'.$paypro_args
);
}
/**
* Get PayPro Args for passing to PP
*
* #access public
* #param mixed $order
* #return array
*/
function get_paypro_args( $order ) {
global $woocommerce;
$order_id = $order->get_id();
//Encrypting the username and password
$token1 = $this->merchant_id;
$token2 = $this->merchant_password;
$cipher_method = 'aes-128-ctr';
$secret_word = md5($this->merchant_secret);
$enc_key = openssl_digest($secret_word.date('d/m/y'), 'SHA256', TRUE);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token1 = openssl_encrypt($token1, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
$crypted_token2 = openssl_encrypt($token2, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
unset($token, $cipher_method, $enc_key, $enc_iv);
// PayPro Args
$paypro_args = array(
'mid' => $crypted_token1,
'mpw' => $crypted_token2,
'secret_public' => base64_encode($this->merchant_secret),
'is_encrypted' => 1,
'mode' => $this->test_mode,
'timeout_in_days' => $this->timeout_in_days,
'merchant_order_id' => $order_id,
'merchant_name' => get_bloginfo( 'name' ),
'request_is_valid' => 'true',
'request_from' => 'woocommerce',
// Billing Address info
'first_name' => $order->get_billing_first_name(),
'last_name' => $order->get_billing_last_name(),
'street_address' => $order->get_billing_address_1(),
'street_address2' => $order->get_billing_address_2(),
'city' => $order->get_billing_city(),
'state' => $order->get_billing_state(),
'zip' => $order->get_billing_postcode(),
'country' => $order->get_billing_country(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone(),
);
if (!function_exists('is_plugin_active')) {
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
if(is_plugin_active( 'custom-order-numbers-for-woocommerce/custom-order-numbers-for-woocommerce.php' )){
$paypro_args['paypro_order_id'] = time().'-'.get_option( 'alg_wc_custom_order_numbers_counter', 1 );
}
else{
$paypro_args['paypro_order_id'] = time().'-'.$order_id;
}
// Shipping
if ($order->needs_shipping_address()) {
$paypro_args['ship_name'] = $order->get_shipping_first_name().' '.$order->get_shipping_last_name();
$paypro_args['company'] = $order->get_shipping_company();
$paypro_args['ship_street_address'] = $order->get_shipping_address_1();
$paypro_args['ship_street_address2'] = $order->get_shipping_address_2();
$paypro_args['ship_city'] = $order->get_shipping_city();
$paypro_args['ship_state'] = $order->get_shipping_state();
$paypro_args['ship_zip'] = $order->get_shipping_postcode();
$paypro_args['ship_country'] = $order->get_shipping_country();
}
$paypro_args['x_receipt_link_url'] = $this->get_return_url( $order );
$paypro_args['request_site_url'] = get_site_url();
$paypro_args['request_site_checkout_url'] = wc_get_checkout_url();
$paypro_args['return_url'] = $order->get_cancel_order_url();
$paypro_args['issueDate'] = date('d/m/Y');
$paypro_args['cartTotal'] = $order->get_total();
$paypro_args['store_currency'] = get_woocommerce_currency();
$paypro_args['store_currency_symbol'] = get_woocommerce_currency_symbol();
//Getting Cart Items
$billDetails= array();
$flag = 0;
foreach ($order->get_items() as $item => $values){
// Get the product name
$product_name = $values['name'];
// Get the item quantity
$item_quantity = $order->get_item_meta($item, '_qty', true);
// Get the item line total
$item_total = $order->get_item_meta($item, '_line_total', true);
$price = $item_total/$item_quantity;
$billDetails[$flag]['LineItem'] = esc_html($product_name);
$billDetails[$flag]['Quantity'] = $item_quantity;
$billDetails[$flag]['UnitPrice'] = $price;
$billDetails[$flag++]['SubTotal'] = $item_total;
}
$paypro_args['cartItemList'] = urlencode(json_encode($billDetails));
////
//setting payment method
if ($this->pay_method)
$paypro_args['pay_method'] = $this->pay_method;
//if test_mode is enabled
if ($this -> test_mode == 'yes'){
$paypro_args['test_mode'] = 'Y';
}
//if timeout_in_days is enabled
if ($this -> timeout_in_days == 'yes'){
$paypro_args['timeout'] = $this->timeout;
}
else{
$paypro_args['timeout'] = $this->timeout*60;
}
$paypro_args = apply_filters( 'woocommerce_paypro_args', $paypro_args );
return $paypro_args;
}
/**
* this function is return product object for two
* different version of WC
*/
function get_product_object(){
return $product;
}
/**
* Check for PayPro IPN Response
*
* #access public
* #return void
*/
function paypro_response() {
global $woocommerce;
// woocommerce_log($_REQUEST);
$this->log(__("== INS Response Received == ", "PayPro") );
$this->log( $_REQUEST );
$wc_order_id = '';
if( !isset($_REQUEST['merchant_order_id']) ) {
if( !isset($_REQUEST['vendor_order_id']) ) {
$this->log( '===== NO ORDER NUMBER FOUND =====' );
exit;
} else {
$wc_order_id = $_REQUEST['vendor_order_id'];
}
} else {
$wc_order_id = $_REQUEST['merchant_order_id'];
}
$this->log(" ==== ORDER -> {$wc_order_id} ====");
// echo $wc_order_id;
$wc_order_id = apply_filters('woocommerce_order_no_received', $wc_order_id, $_REQUEST);
$this->log( "Order Received ==> {$wc_order_id}" );
// exit;
$wc_order = new WC_Order( absint( $wc_order_id ) );
$this->log("Order ID {$wc_order_id}");
$this->log("WC API ==> ".$_GET['wc-api']);
// If redirect after payment
if( isset($_GET['key']) && (isset($_GET['wc-api']) && strtolower($_GET['wc-api']) == 'wc_gateway_mib_paypro') ) {
$this->verify_order_by_hash($wc_order_id);
exit;
}
$message_type = isset($_REQUEST['message_type']) ? $_REQUEST['message_type'] : '';
$sale_id = isset($_REQUEST['sale_id']) ? $_REQUEST['sale_id'] : '';
$invoice_id = isset($_REQUEST['invoice_id']) ? $_REQUEST['invoice_id'] : '';
$fraud_status = isset($_REQUEST['fraud_status']) ? $_REQUEST['fraud_status'] : '';
$this->log( "Message Type/Fraud Status: {$message_type}/{$fraud_status}" );
switch( $message_type ) {
case 'ORDER_CREATED':
$wc_order->add_order_note( sprintf(__('ORDER_CREATED with Sale ID: %d', 'woocommerce'), $sale_id) );
$this->log(sprintf(__('ORDER_CREATED with Sale ID: %d', 'woocommerce'), $sale_id));
break;
case 'FRAUD_STATUS_CHANGED':
if( $fraud_status == 'pass' ) {
// Mark order complete
$wc_order->payment_complete();
$wc_order->add_order_note( sprintf(__('Payment Status Clear with Invoice ID: %d', 'woocommerce'), $invoice_id) );
$this->log(sprintf(__('Payment Status Clear with Invoice ID: %d', 'woocommerce'), $invoice_id));
add_action('woocommerce_order_completed', $order, $sale_id, $invoice_id);
} elseif( $fraud_status == 'fail' ) {
$wc_order->update_status('failed');
$wc_order->add_order_note( __("Payment Declined", 'woocommerce') );
$this->log( __("Payment Declined", 'woocommerce') );
}
break;
}
exit;
}
function verify_order_by_hash($wc_order_id) {
global $woocommerce;
#ob_clean();
$paypro_id = $_REQUEST['paypro_id'];
$tpaycode = $_REQUEST['tpaycode'];
$order_id = $_REQUEST['merchant_order_id'];
$wc_order = wc_get_order( $wc_order_id );
// $order_total = isset($_REQUEST['total']) ? $_REQUEST['total'] : '';
$order_total = $wc_order->get_total();
$compare_string = $this->merchant_id . $paypro_id . $order_total;
$compare_hash1 = strtoupper(md5($compare_string));
$this->log("Compare String ===>" .$compare_string);
$compare_hash2 = $_REQUEST['key'];
if ($compare_hash1 != $compare_hash2) {
$this->log("Hash_1 ==> {$compare_hash1}");
$this->log("Hash_2 ==> {$compare_hash2}");
wp_die( "PayPro Hash Mismatch... check your secret word." );
} else {
//Curl Request
$url = $this->api_url.'/cpay/gos?userName=' . $this->merchant_id . '&password=' . $this->merchant_password . '&cpayId=' . $tpaycode;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
// Submit the GET request
$result = curl_exec($ch);
if (curl_errno($ch)) //catch if curl error exists and show it
echo 'Curl error: ' . curl_error($ch);
else {
//Check if the order ID passed is the same or fake
$res = json_decode($result, true);
$returnedOrderID = explode('-',$res[1]['OrderNumber']);
if ($returnedOrderID[1]===$order_id) {
if (strtoupper($res[1]['OrderStatus']) == "PAID") {
$wc_order->add_order_note( sprintf(__('Payment completed via PayPro Order Number %d', 'paypro'), $tpaycode) );
// Mark order complete
$wc_order->payment_complete();
// Empty cart and clear session
$woocommerce->cart->empty_cart();
$order_redirect = add_query_arg('paypro','processed', $this->get_return_url( $wc_order ));
// Close cURL session handle
curl_close($ch);
wp_redirect( $order_redirect );
exit;
} elseif (strtoupper($res[1]['OrderStatus']) == "BLOCKED") {
$wc_order->add_order_note( sprintf(__('Error processing the payment of Order Number %d', 'paypro'), $tpaycode) );
$order_redirect = add_query_arg('paypro','canceled', $wc_order->get_cancel_order_url());
// Close cURL session handle
curl_close($ch);
wp_redirect( $order_redirect );
exit;
}
elseif (strtoupper($res[1]['OrderStatus']) == "UNPAID") {
$wc_order->add_order_note( sprintf(__('Error processing the payment of Order Number %d', 'paypro'), $tpaycode) );
$order_redirect = add_query_arg('paypro','pending', $wc_order->get_cancel_order_url());
// Close cURL session handle
curl_close($ch);
wp_redirect( $order_redirect );
exit;
}
}
}
}
}
function get_price($price){
$price = wc_format_decimal($price, 2);
return apply_filters('mib_get_price', $price);
}
}
}
function add_mib_payment_gateway( $methods ) {
$methods[] = 'WC_Gateway_MIB_PayPro';
return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'add_mib_payment_gateway' );
function payproco_log( $log ) {
if ( true === WP_DEBUG ) {
if ( is_array( $log ) || is_object( $log ) ) {
$resp = error_log( print_r( $log, true ), 3, plugin_dir_path(__FILE__).'payproco.log' );
} else {
$resp = error_log( $log, 3, plugin_dir_path(__FILE__).'payproco.log' );
}
var_dump($resp);
}
}

how to link Javascript function with wordpress' customize control

I have added a new section in customize section
function select_theme_stylesheet( $wp_customize ){
$wp_customize->add_section( 'theme_stylesheet_selector', array(
'title' => 'Select Color',
'priorty' => 50
));
$wp_customize->add_setting( 'theme_stylesheet_settings', array(
'default' => 'green',
'transport' => 'postMessage'
));
$wp_customize->add_control( new WP_Customize_Control( $wp_customize,'theme_stylesheet_control',array(
'type' => 'radio',
'label' => 'Theme Scheme',
'section' => 'theme_stylesheet_selector',
'settings' => 'theme_stylesheet_settings',
'choices' => array(
'green',
'blue'
),
'selection' => 'colors',
'priorty' => 9
) ));
}
add_action('customize_register', 'select_theme_stylesheet');
And I have the following function in 'customize.preview.js'
wp.customize( 'theme_stylesheet_control', function( value ) {
value.bind( function( newval ) {
alert("hello" + newval);
} );
} );
BUT It's not triggering. Can anyone please tell me what I'm missing.

yii cgridview update depending on dropdownlist

I'm newbie with Yii.
I have a CGridview with a cutom dataprovider which takes a parameter $select:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'beneficiary-grid',
'dataProvider' => $model->searchForVoucherAssignment($select),
'filter' => $model,
'columns' => array(
'id',
'registration_code',
'ar_name',
'en_name',
'family_member',
'main_income_source',
'combine_household',
array( 'class'=>'CCheckBoxColumn', 'value'=>'$data->id', 'selectableRows'=> '2', 'header' => 'check',
),
),
));
That parameter $select takes its values from dropdownlist:
$data = CHtml::listData(Distribution::model()->findAll(array("condition"=>"status_id = 2")), 'id', 'code');
$select = key($data);
echo CHtml::dropDownList(
'distribution_id',
$select, // selected item from the $data
$data,
array(
)
);
So I defined a script to update the CGridview depending on the value of dropdownlist
Yii::app()->clientScript->registerScript('sel_status', "
$('#selStatus').change(function() {
$.fn.yiiGridView.update('beneficiary-grid', {
data: $(this).serialize()
});
return false;
});
");
My model:
public function searchForVoucherAssignment ($distribution_id = 0) {
$criteria = new CDbCriteria;
if ($distribution_id != 0) {
$criteria->condition = "Custom Query...!!";
}
$criteria->compare('id', $this->id);
//Custom Criteria
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 20,
),
));
}
The problem is that the CGridview isn't changing where a value of the dropdownlist changed...
I think you have selected the wrong Id for the change event. The Id should be
$('#distribution_id').change(function() {

javascript not hiding form

The error messages on this form ('after') should be getting hidden by default and only showing when the user presses "Register" submit button. However all the error messages are being shown by default - could any help suggest why this isnt working? The javascript file is printing to the console so it can find the file. Ive put the PHP for the form and the javascript below - any help would be very much appreciated, thank you,
This is the PHP to display the form:
<div class="span5 pull-right reg-form hidden">
<?php
echo $this->Form->create('Users.Register', array(
'url' => '/register',
'class' => 'span12 pull-right'));
echo $this->Form->hidden('current_url', array('value' => $this->here));
echo $this->Form->input('username', array(
'class' => 'reg-input',
'label' => array('text' => 'Email:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-email-err show-err">This email address is already taken</span>
<span class="hidden show-emailvalid-err show-err">This email is not valid</span>'
));
echo $this->Form->input('confirm_username', array(
'class' => 'reg-input',
'label' => array('text' => 'Confirm Email:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-user-err show-err">Re-email is incorrect</span>'
));
echo $this->Form->input('password', array(
'class' => 'reg-input',
'label' => array('text' => 'Password:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-pass-long show-err">Password must be at least 6 characters</span>'
));
echo $this->Form->input('confirm_password', array(
'class' => 'reg-input',
'type' => 'password',
'label' => array('text' => 'Confirm Password:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-pass-err show-err">Re-password is incorrect</span>'
));
echo $this->Form->input('firstname', array(
'class' => 'reg-input',
'label' => array('text' => 'Name:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-firstname-err show-err">This field must not empty</span>'
));
echo $this->Form->input('lastname', array(
'class' => 'reg-input',
'label' => array('text' => 'Last Name:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-lastname-err show-err">This field must not empty</span>'
));
?>
<?php echo $this->Form->end(array('label' => 'Register', 'div' => false, 'id' => 'RegSubmit', 'class' => 'btn-sign pull-right')); ?>
</div>
This is the javascript:
(function($){
/** $(document).ready(function(){}) */
$(function(){
console.log('cover');
/*
$('#btn-reg').on('click', function(){
$('#RegisterUsername').val($('#LoginUsername').val());
$('.reg-form').removeClass('hidden');
});
*/
$('#RegSubmit').on('click', function(e) {
//console.log(e);
if($('.show-user-err').attr('class').indexOf('hidden') < 0)
$('.show-user-err').addClass('hidden');
var username = $('#RegisterUsername').val(),
re_username = $('#RegisterConfirmUsername').val(),
password = $('#RegisterPassword').val(),
re_password = $('#RegisterConfirmPassword').val(),
firstname = $('#RegisterFirstname').val(),
lastname = $('#RegisterLastname').val();
var check = 0;
var email_regex = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
$.each(user_emails, function(index, value){
if(value==username){
check = 1;
}
});
if(check == 1){
$('.show-err').addClass('hidden');
$('.show-email-err').removeClass('hidden');
return false;
}
if(!email_regex.test(username) || username == '') {
$('.show-err').addClass('hidden');
$('.show-emailvalid-err').removeClass('hidden');
return false;
}
if(username != re_username){
$('.show-err').addClass('hidden');
$('.show-user-err').removeClass('hidden');
return false;
}
if(password.length < 6){
$('.show-err').addClass('hidden');
$('.show-pass-long').removeClass('hidden');
return false;
}
if(password != re_password){
$('.show-err').addClass('hidden');
$('.show-pass-err').removeClass('hidden');
return false;
}
if(firstname == ''){
$('.show-err').addClass('hidden');
$('.show-firstname-err').removeClass('hidden');
return false;
}
if(lastname == ''){
$('.show-err').addClass('hidden');
$('.show-lastname-err').removeClass('hidden');
return false;
}
});
});
})(jQuery);
I'd guess that one of the other classes like show-err has display:block and that's overriding the hidden class. If you inspect the element in either Chrome or Firefox then it should show you the CSS rules that are being applied.

Trying to fix multiple category drop down

I'm having some problems trying to fix my category drop down on the website i'm developing. Basically one drop down filters has "Sort by Location" and the second one is "Sort by Price" The first one is working correctly which is "Sort by Location" but the second one doesn't. It is loading all the post and not filtering properly.
Here is the link -
http://digitalspin.ph/federalland/?page_id=23
Here is my code
HTML-
<div class="filter_container">
<?php wp_dropdown_categories( $args_cat1 ); ?>
</div>
<div class="filter_container">
<?php wp_dropdown_categories( $args_cat2 ); ?>
</div>
JS-
<!--DROPDOWN SORT CATEGORY 1 -->
<script type="text/javascript">
var dropdown = document.getElementById("cat1");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_option('home');
?>/?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
</script>
<!--DROPDOWN SORT CATEGORY 2-->
<script type="text/javascript">
var dropdown = document.getElementById("cat2");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_option('home');
?>/?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
</script>
Functions.php
//LOCATION FILTER
$args_cat2 = array(
'show_option_all' => '',
'show_option_none' => '',
'orderby' => 'ID',
'order' => 'ASC',
'show_count' => 0,
'hide_empty' => 1,
'child_of' => 0,
'exclude' => '1,2,3,4,32,33,34,35,36,37',
'echo' => 1,
'selected' => 0,
'hierarchical' => 0,
'name' => 'cat2',
'id' => 'cat2',
'class' => 'postform',
'depth' => 0,
'tab_index' => 0,
'taxonomy' => 'category',
'hide_if_empty' => false,
'walker' => ''
);
//PRICE FILTER
$args_cat1 = array(
'show_option_all' => '',
'show_option_none' => '',
'orderby' => 'ID',
'order' => 'ASC',
'show_count' => 0,
'hide_empty' => 1,
'child_of' => 0,
'exclude' => '1,2,3,4,23,24,25,26,27,28,29,30,31',
'echo' => 1,
'selected' => 0,
'hierarchical' => 0,
'name' => 'cat1',
'id' => 'cat1',
'class' => 'postform',
'depth' => 0,
'tab_index' => 0,
'taxonomy' => 'category',
'hide_if_empty' => false,
'walker' => ''
);
Here is a javascript error from firebug-
TypeError: dropdown is null
dropdown.onchange = onCatChange;
Whenever i pick a category in "Sort by Price" it display all the post from "Sort by Location" which is category ID 23
The main problem is that you think your 2 javascripts are executed in different contexts, they are not. They are executed in the same context so
<script type="text/javascript">
var dropdown = document.getElementById("cat1");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_option('home');?>/?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
var dropdown = document.getElementById("cat2");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_option('home');?>/?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
</script>
Would produce the exact same result. You need to change the names of some of your variables and functions so they dont collide or do something like:
document.getElementById("cat1").onChange = function(){
if ( this.options[this.selectedIndex].value > 0 ) {
location.href = "<?php echo get_option('home');?>/?cat="+this.options[this.selectedIndex].value;
}
}
document.getElementById("cat2").onChange = function(){
if ( this.options[this.selectedIndex].value > 0 ) {
location.href = "<?php echo get_option('home');?>/?cat="+this.options[this.selectedIndex].value;
}
}
Or maybe even better
var catChanger = function(){
if ( this.options[this.selectedIndex].value > 0 ) {
location.href = "<?php echo get_option('home');?>/?cat="+this.options[this.selectedIndex].value;
}
}
document.getElementById("cat1").onChange = catChanger;
document.getElementById("cat2").onChange = catChanger;

Categories

Resources