Как добавить класс css активной радиокнопке?
Здравствуйте!
Нужно выделять фон выбранного радиокнопкой способа доставки в woocommerce... Для этого хочу добавить элементу списка с активной радиокнопкой дополнительный класс css... В js совсем не силен, поэтому мучаюсь уже второй день..:( Пробовал добавлять на страницу код
<script>
$('#shipping_method').click(function() {
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
}
});
</script>
но что-то не получается ничего... Помогите пожалуйста. |
Igorsrt,
сделайте полностью пример |
Цитата:
Код html в фаербаге примерно такой получается: <li class="shipping_method"> <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" class="shipping_method" checked="checked"><label for="shipping_method_0_flat_rate">Доставка1</label><div style="float:right;">300 руб.</div></li> <li class="shipping_method"> <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_local_delivery" value="local_delivery" class="shipping_method"><label for="shipping_method_0_local_delivery">Доставка2</label><div style="float:right;">500 руб.</a></div></li> возможно, я скрипт куда-то не туда вставляю... но пробовал уже по всякому и в разные места... (( |
Igorsrt,
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
.selected {
width: 50px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$('input.shipping_method').click(function() {
$('input.shipping_method').each(function(indx, element){
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
}).filter(":checked").click();
})
</script>
</head>
<body>
<ul>
<li class="shipping_method">
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" class="shipping_method" checked="checked"><label for="shipping_method_0_flat_rate">Доставка1</label><div style="float:right;">300 руб.</div></li>
<li class="shipping_method">
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_local_delivery" value="local_delivery" class="shipping_method"><label for="shipping_method_0_local_delivery">Доставка2</label><div style="float:right;">500 руб.</div></li>
</ul>
</body>
</html>
|
Спасибо!
но почему-то тоже не работает у меня... что же я делаю не так... |
Igorsrt,
нет кода нет совета |
Цитата:
<?php
/**
* Checkout Form
*
* This template can be overridden by copying it to yourtheme/woocommerce/checkout/form-checkout.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
* will need to copy the new files to your theme to maintain compatibility. We try to do this.
* as little as possible, but it does happen. When this occurs the version of the template file will.
* be bumped and the readme will list any important changes.
*
* @see http://docs.woothemes.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.3.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
wc_print_notices();
do_action( 'woocommerce_before_checkout_form', $checkout );
// If checkout registration is disabled and not logged in, the user cannot checkout
if ( ! $checkout->enable_signup && ! $checkout->enable_guest_checkout && ! is_user_logged_in() ) {
echo apply_filters( 'woocommerce_checkout_must_be_logged_in_message', __( 'You must be logged in to checkout.', 'woocommerce' ) );
return;
}
?>
<h3>Способ доставки</h3>
<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( wc_get_checkout_url() ); ?>" enctype="multipart/form-data">
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
<?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_order_review' ); ?>
<?php if ( sizeof( $checkout->checkout_fields ) > 0 ) : ?>
<?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>
<div class="" id="customer_details">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
<?php do_action( 'woocommerce_checkout_shipping' ); ?>
</div>
<div class="form-row place-order">
<noscript>
<?php _e( 'Since your browser does not support JavaScript, or it is disabled, please ensure you click the <em>Update Totals</em> button before placing your order. You may be charged more than the amount stated above if you fail to do so.', 'woocommerce' ); ?>
<br/><input type="submit" class="button alt" name="woocommerce_checkout_update_totals" value="<?php esc_attr_e( 'Update totals', 'woocommerce' ); ?>" />
</noscript>
<?php wc_get_template( 'checkout/terms.php' ); ?>
<?php do_action( 'woocommerce_review_order_before_submit' ); ?>
<?php echo apply_filters( 'woocommerce_order_button_html', '<input type="submit" class="woo-order-button" name="woocommerce_checkout_place_order" id="place_order" value="Отправить" data-value="Отправить" />' ); ?>
<?php do_action( 'woocommerce_review_order_after_submit' ); ?>
<?php wp_nonce_field( 'woocommerce-process_checkout' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
<?php endif; ?>
</form>
<?php do_action( 'woocommerce_after_checkout_form', $checkout ); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$('input.shipping_method').click(function() {
$('input.shipping_method').each(function(indx, element){
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
}).filter(":checked").click();
})
</script>
|
Igorsrt,
ок но не могу помочь, php не знаю |
насколько я понимаю, с помощью php в конечном счете формируется обычная html страница с кодом, фрагмент которого приводил в начале...
Мне было интересно, может быть я сам скрипт как-то неправильно вставляю.. В любом случае, спасибо за попытку помочь. :) |
Igorsrt,
попробуйте весь код с JS поместить в echo |
это как?
<?php
echo '<script>
$(function(){
$('input.shipping_method').click(function() {
$('input.shipping_method').each(function(indx, element){
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
}).filter(":checked").click();
})
</script>'
?>
что-то у меня не получается... |
<?php
echo "<script>
$(function(){
$('input.shipping_method').click(function() {
$('input.shipping_method').each(function(indx, element){
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
}).filter(\":checked\").click();
})
</script>"
?>
|
Цитата:
<?php
echo '<script>
$(function(){
$('input.shipping_method').click(function() {
$('input.shipping_method').each(function(indx, element){
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
}).filter(":checked").click();
})
</script>'
?>
что-то у меня не получается... |
поместил в echo... пока что тоже самое.. (
|
Igorsrt,
вы тэг style не вставили в код.
<?php
echo " <style type=\"text/css\">
.selected {
width: 50px;
}
</style>";
echo "
<li class=\"shipping_method\">
<input type=\"radio\" name=\"shipping_method[0]\" data-index=\"0\" id=\"shipping_method_0_flat_rate\" value=\"flat_rate\" class=\"shipping_method\" checked=\"checked\"><label for=\"shipping_method_0_flat_rate\">Dostavka1</label><div style=\"float:right;\">300 rub</div></li>
<li class=\"shipping_method\">
<input type=\"radio\" name=\"shipping_method[0]\" data-index=\"0\" id=\"shipping_method_0_local_delivery\" value=\"local_delivery\" class=\"shipping_method\"><label for=\"shipping_method_0_local_delivery\">Dostavka2</label><div style=\"float:right;\">250 rub</a></div></li>
";
echo "
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js\"></script>
";
echo "<script>
$(function(){
$('input.shipping_method').click(function() {
$('input.shipping_method').each(function(indx, element){
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
}).filter(\":checked\").click();
})
</script>";
?>
|
Цитата:
тупо сейчас вставил Ваш код - никаких изменений, кроме того что два новых чекбокса появилось внизу страницы, но классы так же не добавляются |
Igorsrt,
а этот класс определен в таблице стилей и эта таблица подключена к файлу? http://pixs.ru/showimage/ttpng_7046123_20782733.png |
пока нет... я просто смотрю в фаербаге "просмотреть код" и жду когда у элемента списка появится новый класс "checked"... стили уж потом пропишу ))
|
Цитата:
|
Цитата:
|
Цитата:
<li class="shipping_method"> <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" class="shipping_method" checked="checked"><label for="shipping_method_0_flat_rate">Доставка1</label><div style="float:right;">300 руб.</div></li> класс "checked":
$(this).addClass('selected');
извиняюсь не "checked" а "selected" |
Igorsrt,
может вы это хотели?
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
.selected {
background-color: #FF00FF;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$('input.shipping_method').click(function() {
$('li.shipping_method').each(function(indx, element){
if ($('input',this)[0].checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
}).filter(":checked").click();
})
</script>
</head>
<body>
<ul>
<li class="shipping_method">
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" class="shipping_method" checked="checked"><label for="shipping_method_0_flat_rate">Доставка1</label><div style="float:right;">300 руб.</div></li>
<li class="shipping_method">
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_local_delivery" value="local_delivery" class="shipping_method"><label for="shipping_method_0_local_delivery">Доставка2</label><div style="float:right;">500 руб.</div></li>
</ul>
</body>
</html>
|
Ух ты, кажется заработало... спасибо )))
|
и еще один вопрос. Если я хочу на этой же странице так же выделять еще один чекбокс (оплату) с классом wc_payment_methods, мне нужно новый скрипт писать или в этот же можно вставить?
|
Цитата:
|
Igorsrt,
учитесь делать лаконичные макеты и чётко формулировать ... ваши два поста выше не осилил. |
Цитата:
<h3>Способ оплаты</h3> <ul class="wc_payment_methods payment_methods methods"> <li class="wc_payment_method payment_method_cod"> <input id="payment_method_cod" type="radio" class="input-radio" name="payment_method" value="cod" data-order_button_text=""> <label for="payment_method_cod"> Наличными курьеру при получении заказа </label> <div class="payment_method_desc"> <p>Оплата производится курьеру в момент доставки товара.</p> </div> </li> <li class="wc_payment_method payment_method_cheque"> <input id="payment_method_cheque" type="radio" class="input-radio" name="payment_method" value="cheque" data-order_button_text=""> <label for="payment_method_cheque"> Альтернативный способ оплаты </label> <div class="payment_method_desc"> <p>Мы готовы предложить Вам другие способы оплаты заказа.</p> </div> </li> </ul> Нужно сделать то же самое, т.е. присвоить активному элементу <li> дополнительный класс 'selected'... Думал сделать по аналогии с Вашим первым вариантом, но что-то не получается опять (возможно куда-то не туда вставляю или ошибка в самом коде у меня)... Не могли бы Вы еще для этого варианта прописать скрипт? |
Igorsrt, checked в input добавьте если нужно
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
.selected {
background-color: #FF00FF;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$('li').click(function() {
$(this).siblings().add(this).each(function(indx, el){
if ($('input',el)[0].checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
} });
})
$("li input:checked").parent().click();
})
</script>
</head>
<body>
<ul>
<li class="shipping_method">
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" class="shipping_method" checked="checked"><label for="shipping_method_0_flat_rate">Доставка1</label><div style="float:right;">300 руб.</div></li>
<li class="shipping_method">
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_local_delivery" value="local_delivery" class="shipping_method"><label for="shipping_method_0_local_delivery">Доставка2</label><div style="float:right;">500 руб.</div></li>
</ul>
<h3>Способ оплаты</h3>
<ul class="wc_payment_methods payment_methods methods">
<li class="wc_payment_method payment_method_cod">
<input id="payment_method_cod" type="radio" class="input-radio" name="payment_method" value="cod" data-order_button_text="">
<label for="payment_method_cod">
Наличными курьеру при получении заказа </label>
<div class="payment_method_desc">
<p>Оплата производится курьеру в момент доставки товара.</p>
</div>
</li>
<li class="wc_payment_method payment_method_cheque">
<input id="payment_method_cheque" type="radio" class="input-radio" name="payment_method" value="cheque" data-order_button_text="">
<label for="payment_method_cheque">
Альтернативный способ оплаты </label>
<div class="payment_method_desc">
<p>Мы готовы предложить Вам другие способы оплаты заказа.</p>
</div>
</li>
</ul>
</body>
</html>
|
да, спасибо огромное - все заработало наконец-то... )))
|
| Часовой пояс GMT +3, время: 16:33. |