Как поменять местами кнопки (с jQuery) на основе переключателя или нет - PullRequest
0 голосов
/ 16 февраля 2019

Я работаю над интерфейсом, который пользователь выберет адрес доставки.Конструкция по существу использует шаблон переключателей, где отмеченная «карта» будет зеленой, а кнопка будет меняться в зависимости от проверяемой карты (переключателя).

В основном, есть кнопка по умолчанию сосновной класс и он говорит «Доставить по этому адресу», но когда карта проверяется, она должна измениться на «Выбранный адрес».Это сейчас работает.Сначала я попытался использовать «ту же самую» кнопку, но изменить внутренний текст или HTML, и классы, но это не сработало слишком хорошо.Итак, теперь я подумал показать и скрыть кнопки, основываясь на проверенном состоянии переключателя.

Но мне трудно с братьями и сестрами, родителями, детьми и т. Д. - обходя DOM, чтобы получить эффект, который яхочу.Я хочу только, чтобы проверенная карта отображалась зеленым с кнопкой «Выбранный адрес».Это должно быть даже при загрузке страницы, если проверена одна из карточек.И в тот момент, когда я проверяю другую карточку, чтобы «снять отметку» со всех других карточек и вернуть эту кнопку обратно к кнопке «Доставить по этому адресу».

Я сделал JS Fiddle, чтобы полностью понять, что я имею в виду: https://jsfiddle.net/gamehendgeVA/b98v65tx/3/

Вот JS, который я пробовал:

 jQuery(".selectedAddressButton").hide();

  jQuery(function () {
     jQuery(".addressRadio").change(function() {
    if (jQuery(this).is(":checked")) {
        jQuery(this).siblings().find(".selectedAddressButton").show();
        jQuery(this).siblings().find(".deliverButton").hide();
    } else {
        jQuery(this).siblings().find(".selectedAddressButton").hide();
        jQuery(this).parents().find(".deliverButton").show();
    }
 });
});

(мне пришлось использовать «jQuery» вместо $, чтобы заставить вещи работать из-за некоторыхстранные рабочие файлы, точно не знаю почему.)

И фрагмент одного из переключателей "cards":

<label class="fullWidth">
        <input type="radio" name="selectAddress" class="card-input-element d-none hideOffScreen addressRadio" id="address1" value="address1">
        <div class="card card-body bg-light d-flex flex-row justify-content-between align-items-center radioCard">
            <div class="addressField">John Doe</div>
            <div class="addressField">123 Anytown St.</div>
            <div class="addressField">Springfield, MD 22365</div>
            <div class="row">
                <div class="col-md-12 text-left">
                    <div class="deliverButton" style="margin-top:12px;">
                        <div type="button" class="btn btn-primary-custom" style="margin-right:10px;">Deliver to this Address</div>
                    </div>
                    <div class="selectedAddressButton" style="margin-top:12px;">
                        <div style="margin-top:12px;">
                            <div type="button" class="btn btn-success-custom" style="margin-right:10px;"><i class="fa fa-check" aria-hidden="true" style="padding-right:6px;"></i>Selected Address</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 text-left =" style="margin-top:15px;">
                    <button type="button" class="btn btn-secondary-custom" style="margin-right:10px;">Edit</button>
                    <button type="button" class="btn btn-secondary-custom">Delete</button>
                </div>
            </div>
        </div>
</label>

Я подумал обратиться к экспертам, чтобы узнать, смогу ли яЯ на правильном пути - возможно, есть более простой способ выполнить то, что я пытаюсь сделать.

Любая помощь с благодарностью!Спасибо!

Ответы [ 4 ]

0 голосов
/ 16 февраля 2019

Принятый ответ - это хорошо.Просто хотел добавить несколько вариантов / альтернатив, которые достигают того же результата, с меньшим количеством кода и более простыми подходами:

Добавить / удалить класс selected в родительском элементе .addressRadio, соответствующем :checked состояние этого переключателя.

$('.addressRadio').change(function() {
  $(this)
    .closest('label.fullWidth')
    .toggleClass('selected', this.checked);

  $('.addressRadio')
    .not(this)
    .closest('label.fullWidth.selected')
    .removeClass('selected');
});

Или даже проще, с пользовательским плагином (см. Реализацию .toggleClassUnique() в демонстрационном коде ниже).Может быть не особенно полезным, если вам не требуется многоразовая функциональность в вашем приложении, но в любом случае это так:

$('.addressRadio').change(function() {
  $(this)
    .closest('label.fullWidth')
    .toggleClassUnique('selected', this.checked);
});

Итак, этот дополнительный класс будет использоваться для определения, являются ли его «целевые» дети (.selectedAddressButtonи .deliverButton) должны быть скрыты или показаны.

CSS

.fullWidth .selectedAddressButton {
  display: none;
}

.fullWidth.selected .selectedAddressButton {
  display: block;
}

.fullWidth.selected .deliverButton {
  display: none;
}

Это также устанавливает начальную видимость .selectedAddressButton как «скрытую», или технически display: none, таким образомвам не нужен Javascript для этого.


И последнее, но не менее важное: взгляните на jQuery.noConflict() для возможного решения вашей проблемы с псевдонимами jQuery.

Многие библиотеки JavaScript используют $ как имя функции или переменной, так же как и jQuery.В случае jQuery $ - это псевдоним для jQuery, поэтому все функции доступны без использования $.Если вам нужно использовать другую библиотеку JavaScript вместе с jQuery, верните управление $ back другой библиотеке с помощью вызова $.noConflict().Старые ссылки на $ сохраняются во время инициализации jQuery;noConflict() просто восстанавливает их.

Или просто передает ссылку на глобальный объект jQuery в области действия функции:

(function ($) {

  $(function() {
    // More code using $ as alias to jQuery
  });

})(jQuery);

Как правило, вы добавляете это в самый верхвашего JS-файла, и все коды, для которых требуется jQuery, должны затем войти в эту оболочку.


Полная рабочая демонстрация

(function($) {

  $('.addressRadio').change(function() {
    $(this)
      .closest('label.fullWidth')
      .toggleClass('selected', this.checked);
      
    $('.addressRadio')
      .not(this)
      .closest('label.fullWidth.selected')
      .removeClass('selected');
  });
  
})(window.jQuery);
.fullWidth .selectedAddressButton {
  display: none;
}

.fullWidth.selected .selectedAddressButton {
  display: block;
}

.fullWidth.selected .deliverButton {
  display: none;
}

label.fullWidth {
  width: 100%;
  font-size: 1rem;
}

.card-input-element+.card {
  /*height: calc(36px + 2*1rem);*/
  color: #005499;
  -webkit-box-shadow: none;
  box-shadow: none;
  border: 2px solid transparent;
  border-radius: 4px;
  border: 2px solid #ccc;
}

.card-input-element+.card:hover {
  cursor: pointer;
  background-color: #eee;
  border: 2px solid #005499;
}

.card-input-element:checked+.card {
  border: 2px solid #c3e6cb;
  background-color: #d4edda;
  -webkit-transition: border .3s;
  -o-transition: border .3s;
  transition: border .3s;
  content: '\f00c';
  color: #0e6d2e;
  font-family: 'FontAwesome';
  font-size: 24px;
  -webkit-animation-name: fadeInCheckbox;
  animation-name: fadeInCheckbox;
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.card-input-element:checked+.card::after {
  content: '\f00c';
  color: #0e6d2e;
  font-family: 'FontAwesome';
  font-size: 24px;
  -webkit-animation-name: fadeInCheckbox;
  animation-name: fadeInCheckbox;
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  position: absolute;
  top: 0;
  right: 5px;
}

@-webkit-keyframes fadeInCheckbox {
  from {
    opacity: 0;
    -webkit-transform: rotateZ(-20deg);
  }
  to {
    opacity: 1;
    -webkit-transform: rotateZ(0deg);
  }
}

@keyframes fadeInCheckbox {
  from {
    opacity: 0;
    transform: rotateZ(-20deg);
  }
  to {
    opacity: 1;
    transform: rotateZ(0deg);
  }
}

.addressField {
  font-family: Lato, "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 18px;
  margin-bottom: 5px;
}

.radioCard {
  padding: 20px;
  margin: 6px 0;
  position: relative;
}

.radioCard:hover {
  background-color: #eee;
  cursor: pointer;
}


/* note: the position relative goes with the position absolute on the ::after to get the checkmark in the top-right of the div */


/* hiding actual radio button away from screen */

input[type="checkbox"].hideOffScreen,
input[type="radio"].hideOffScreen {
  position: absolute;
  margin-left: -9999px;
}

.btn-success-custom {
  font-family: "ProximaNova", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: normal;
  font-size: 14px;
  text-align: center;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  background-color: #28a745;
  color: #fff;
  border-radius: 3px;
  padding-top: 9px;
  min-height: 38px;
  transition: background 0.5s ease 0s;
  -webkit-transition: background 0.5s ease 0s;
  -moz-transition: background 0.5s ease 0s;
  -ms-transition: background 0.5s ease 0s;
}

.btn-success-custom:hover,
.btn-success-custom:focus,
.btn-success-custom:active,
.btn-success-custom.active,
.open .dropdown-toggle.btn-success-custom {
  background-color: #218838;
  color: #fff;
}

.btn-success-custom:active,
.open .dropdown-toggle.btn-success-custom {
  background-image: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="row">
   <div class="col-md-12">
      <div>Is the address you'd like to use displayed below? If so, select the corresponding box below. Or, you can <a>enter a different address</a>.</div>
      <div class="radioPanel">
         <label class="fullWidth">
            <input type="radio" name="selectAddress" class="card-input-element d-none hideOffScreen addressRadio" id="address1" value="address1">
            <div class="card card-body bg-light d-flex flex-row justify-content-between align-items-center radioCard">
               <div class="addressField">John Doe</div>
               <div class="addressField">123 Anytown St.</div>
               <div class="addressField">Springfield, MD 22365</div>
               <div class="row">
                  <div class="col-md-12 text-left">
                     <div class="deliverButton" style="margin-top:12px;">
                        <div type="button" class="btn btn-primary-custom" style="margin-right:10px;">Deliver to this Address</div>
                     </div>
                     <div class="selectedAddressButton" style="margin-top:12px;">
                        <div style="margin-top:12px;">
                           <div type="button" class="btn btn-success-custom" style="margin-right:10px;"><i class="fa fa-check" aria-hidden="true" style="padding-right:6px;"></i>Selected Address</div>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-12 text-left =" style="margin-top:15px;">  
                     <button type="button" class="btn btn-secondary-custom" style="margin-right:10px;">Edit</button>
                     <button type="button" class="btn btn-secondary-custom">Delete</button>   
                  </div>
               </div>
            </div>
         </label>
         <label class="fullWidth" style="margin-top:10px;">
            <input type="radio" name="selectAddress" class="card-input-element d-none hideOffScreen addressRadio" id="address2" value="address2">
            <div class="card card-body bg-light d-flex flex-row justify-content-between align-items-center radioCard">
               <div class="addressField">Sally Smith</div>
               <div class="addressField">555 Elm St.</div>
               <div class="addressField">Nantucket, CA 55698</div>
               <div class="row">
                  <div class="col-md-12 text-left">
                     <div class="deliverButton" style="margin-top:12px;">
                        <div type="button" class="btn btn-primary-custom" style="margin-right:10px;">Deliver to this Address</div>
                     </div>
                     <div class="selectedAddressButton" style="margin-top:12px;">
                        <div style="margin-top:12px;">
                           <div type="button" class="btn btn-success-custom" style="margin-right:10px;"><i class="fa fa-check" aria-hidden="true" style="padding-right:6px;"></i>Selected Address</div>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-12 text-left =" style="margin-top:15px;">  
                     <button type="button" class="btn btn-secondary-custom" style="margin-right:10px;">Edit</button>
                     <button type="button" class="btn btn-secondary-custom">Delete</button>   
                  </div>
               </div>
            </div>
         </label>
      </div>
      <!-- /.radioPanel -->
   </div>
</div>

С пользовательским плагином jQuery

(function($) {

  $('.addressRadio').change(function() {
    $(this)
      .closest('label.fullWidth')
      .toggleClassUnique('selected', this.checked);
  });
  
  
  // Custom plugin
  $.fn.toggleClassUnique = function (className, state) {
    this
      .toggleClass(className, state)
      .siblings()
      .removeClass(className);
      
    return this;
  };
  
})(window.jQuery);
.fullWidth .selectedAddressButton {
  display: none;
}

.fullWidth.selected .selectedAddressButton {
  display: block;
}

.fullWidth.selected .deliverButton {
  display: none;
}

label.fullWidth {
  width: 100%;
  font-size: 1rem;
}

.card-input-element+.card {
  /*height: calc(36px + 2*1rem);*/
  color: #005499;
  -webkit-box-shadow: none;
  box-shadow: none;
  border: 2px solid transparent;
  border-radius: 4px;
  border: 2px solid #ccc;
}

.card-input-element+.card:hover {
  cursor: pointer;
  background-color: #eee;
  border: 2px solid #005499;
}

.card-input-element:checked+.card {
  border: 2px solid #c3e6cb;
  background-color: #d4edda;
  -webkit-transition: border .3s;
  -o-transition: border .3s;
  transition: border .3s;
  content: '\f00c';
  color: #0e6d2e;
  font-family: 'FontAwesome';
  font-size: 24px;
  -webkit-animation-name: fadeInCheckbox;
  animation-name: fadeInCheckbox;
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.card-input-element:checked+.card::after {
  content: '\f00c';
  color: #0e6d2e;
  font-family: 'FontAwesome';
  font-size: 24px;
  -webkit-animation-name: fadeInCheckbox;
  animation-name: fadeInCheckbox;
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  position: absolute;
  top: 0;
  right: 5px;
}

@-webkit-keyframes fadeInCheckbox {
  from {
    opacity: 0;
    -webkit-transform: rotateZ(-20deg);
  }
  to {
    opacity: 1;
    -webkit-transform: rotateZ(0deg);
  }
}

@keyframes fadeInCheckbox {
  from {
    opacity: 0;
    transform: rotateZ(-20deg);
  }
  to {
    opacity: 1;
    transform: rotateZ(0deg);
  }
}

.addressField {
  font-family: Lato, "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 18px;
  margin-bottom: 5px;
}

.radioCard {
  padding: 20px;
  margin: 6px 0;
  position: relative;
}

.radioCard:hover {
  background-color: #eee;
  cursor: pointer;
}


/* note: the position relative goes with the position absolute on the ::after to get the checkmark in the top-right of the div */


/* hiding actual radio button away from screen */

input[type="checkbox"].hideOffScreen,
input[type="radio"].hideOffScreen {
  position: absolute;
  margin-left: -9999px;
}

.btn-success-custom {
  font-family: "ProximaNova", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: normal;
  font-size: 14px;
  text-align: center;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  background-color: #28a745;
  color: #fff;
  border-radius: 3px;
  padding-top: 9px;
  min-height: 38px;
  transition: background 0.5s ease 0s;
  -webkit-transition: background 0.5s ease 0s;
  -moz-transition: background 0.5s ease 0s;
  -ms-transition: background 0.5s ease 0s;
}

.btn-success-custom:hover,
.btn-success-custom:focus,
.btn-success-custom:active,
.btn-success-custom.active,
.open .dropdown-toggle.btn-success-custom {
  background-color: #218838;
  color: #fff;
}

.btn-success-custom:active,
.open .dropdown-toggle.btn-success-custom {
  background-image: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="row">
   <div class="col-md-12">
      <div>Is the address you'd like to use displayed below? If so, select the corresponding box below. Or, you can <a>enter a different address</a>.</div>
      <div class="radioPanel">
         <label class="fullWidth">
            <input type="radio" name="selectAddress" class="card-input-element d-none hideOffScreen addressRadio" id="address1" value="address1">
            <div class="card card-body bg-light d-flex flex-row justify-content-between align-items-center radioCard">
               <div class="addressField">John Doe</div>
               <div class="addressField">123 Anytown St.</div>
               <div class="addressField">Springfield, MD 22365</div>
               <div class="row">
                  <div class="col-md-12 text-left">
                     <div class="deliverButton" style="margin-top:12px;">
                        <div type="button" class="btn btn-primary-custom" style="margin-right:10px;">Deliver to this Address</div>
                     </div>
                     <div class="selectedAddressButton" style="margin-top:12px;">
                        <div style="margin-top:12px;">
                           <div type="button" class="btn btn-success-custom" style="margin-right:10px;"><i class="fa fa-check" aria-hidden="true" style="padding-right:6px;"></i>Selected Address</div>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-12 text-left =" style="margin-top:15px;">  
                     <button type="button" class="btn btn-secondary-custom" style="margin-right:10px;">Edit</button>
                     <button type="button" class="btn btn-secondary-custom">Delete</button>   
                  </div>
               </div>
            </div>
         </label>
         <label class="fullWidth" style="margin-top:10px;">
            <input type="radio" name="selectAddress" class="card-input-element d-none hideOffScreen addressRadio" id="address2" value="address2">
            <div class="card card-body bg-light d-flex flex-row justify-content-between align-items-center radioCard">
               <div class="addressField">Sally Smith</div>
               <div class="addressField">555 Elm St.</div>
               <div class="addressField">Nantucket, CA 55698</div>
               <div class="row">
                  <div class="col-md-12 text-left">
                     <div class="deliverButton" style="margin-top:12px;">
                        <div type="button" class="btn btn-primary-custom" style="margin-right:10px;">Deliver to this Address</div>
                     </div>
                     <div class="selectedAddressButton" style="margin-top:12px;">
                        <div style="margin-top:12px;">
                           <div type="button" class="btn btn-success-custom" style="margin-right:10px;"><i class="fa fa-check" aria-hidden="true" style="padding-right:6px;"></i>Selected Address</div>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="row">
                  <div class="col-md-12 text-left =" style="margin-top:15px;">  
                     <button type="button" class="btn btn-secondary-custom" style="margin-right:10px;">Edit</button>
                     <button type="button" class="btn btn-secondary-custom">Delete</button>   
                  </div>
               </div>
            </div>
         </label>
      </div>
      <!-- /.radioPanel -->
   </div>
</div>

PS Если вы заинтересованы в создании своего собственного, см. , как создать базовый плагин .

0 голосов
/ 16 февраля 2019

Фрагмент ниже действует так, как вы хотите.

Я написал несколько дополнительных строк CSS и использовал jquery для добавления класса .selected к окружающему ярлыку.Если также отменяет выбор ранее выбранных карт и может использоваться с несколькими радиогруппами на одной странице.

Jquery был полностью прокомментирован ниже.

Дайте мне знать, если вы хотите что-то еще.

Новый CSS

label .selectedAddressButton, label.selected .deliverButton {
  display: none;
}

label.selected .selectedAddressButton, label .deliverButton {
  display: inherit;
}


Демо

// Add change event for you radio button class
$(".addressRadio").change(function() {

  // Check the radio button group name
  // So you can have multiple radio groups on a single page
  radioGroup = $(this).attr("name");

  // Cycle through each of the associated radio buttons
  $("input[type='radio'][name='" + radioGroup + "']").each(function() {
  
    // Remove any selected classes from the wrapping label
    $(this).closest("label").removeClass("selected");

  });

  // Check if the changed radio button has been selected 
  if ($(this).is(":checked")) {

    // Add the selected class if it has
    $(this).closest("label").addClass("selected");

  }

});
label.fullWidth {
  width: 100%;
  font-size: 1rem;
}

.card-input-element+.card {
  /*height: calc(36px + 2*1rem);*/
  color: #005499;
  -webkit-box-shadow: none;
  box-shadow: none;
  border: 2px solid transparent;
  border-radius: 4px;
  border: 2px solid #ccc;
}

.card-input-element+.card:hover {
  cursor: pointer;
  background-color: #eee;
  border: 2px solid #005499;
}

.card-input-element:checked+.card {
  border: 2px solid #c3e6cb;
  background-color: #d4edda;
  -webkit-transition: border .3s;
  -o-transition: border .3s;
  transition: border .3s;
  content: '\f00c';
  color: #0e6d2e;
  font-family: 'FontAwesome';
  font-size: 24px;
  -webkit-animation-name: fadeInCheckbox;
  animation-name: fadeInCheckbox;
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.card-input-element:checked+.card::after {
  content: '\f00c';
  color: #0e6d2e;
  font-family: 'FontAwesome';
  font-size: 24px;
  -webkit-animation-name: fadeInCheckbox;
  animation-name: fadeInCheckbox;
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  position: absolute;
  top: 0;
  right: 5px;
}

@-webkit-keyframes fadeInCheckbox {
  from {
    opacity: 0;
    -webkit-transform: rotateZ(-20deg);
  }
  to {
    opacity: 1;
    -webkit-transform: rotateZ(0deg);
  }
}

@keyframes fadeInCheckbox {
  from {
    opacity: 0;
    transform: rotateZ(-20deg);
  }
  to {
    opacity: 1;
    transform: rotateZ(0deg);
  }
}

.addressField {
  font-family: Lato, "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 18px;
  margin-bottom: 5px;
}

.radioCard {
  padding: 20px;
  margin: 6px 0;
  position: relative;
}

.radioCard:hover {
  background-color: #eee;
  cursor: pointer;
}


/* note: the position relative goes with the position absolute on the ::after to get the checkmark in the top-right of the div */


/* hiding actual radio button away from screen */

input[type="checkbox"].hideOffScreen,
input[type="radio"].hideOffScreen {
  position: absolute;
  margin-left: -9999px;
}

.btn-success-custom {
  font-family: "ProximaNova", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: normal;
  font-size: 14px;
  text-align: center;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  background-color: #28a745;
  color: #fff;
  border-radius: 3px;
  padding-top: 9px;
  min-height: 38px;
  transition: background 0.5s ease 0s;
  -webkit-transition: background 0.5s ease 0s;
  -moz-transition: background 0.5s ease 0s;
  -ms-transition: background 0.5s ease 0s;
}

.btn-success-custom:hover,
.btn-success-custom:focus,
.btn-success-custom:active,
.btn-success-custom.active,
.open .dropdown-toggle.btn-success-custom {
  background-color: #218838;
  color: #fff;
}

.btn-success-custom:active,
.open .dropdown-toggle.btn-success-custom {
  background-image: none;
}

label .selectedAddressButton,
label.selected .deliverButton {
  display: none;
}

label.selected .selectedAddressButton,
label .deliverButton {
  display: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-12">
    <div>Is the address you'd like to use displayed below? If so, select the corresponding box below. Or, you can <a>enter a different address</a>.</div>
    <div class="radioPanel">
      <label class="fullWidth">
<input type="radio" name="selectAddress" class="card-input-element d-none hideOffScreen addressRadio" id="address1" value="address1">
<div class="card card-body bg-light d-flex flex-row justify-content-between align-items-center radioCard">
<div class="addressField">John Doe</div>
<div class="addressField">123 Anytown St.</div>
<div class="addressField">Springfield, MD 22365</div>
<div class="row">
<div class="col-md-12 text-left">
<div class="deliverButton" style="margin-top:12px;">
<div type="button" class="btn btn-primary-custom" style="margin-right:10px;">Deliver to this Address</div>
</div>
<div class="selectedAddressButton" style="margin-top:12px;">
<div style="margin-top:12px;"><div type="button" class="btn btn-success-custom" style="margin-right:10px;"><i class="fa fa-check" aria-hidden="true" style="padding-right:6px;"></i>Selected Address</div></div>
</div> 
</div>
</div>
<div class="row">
<div class="col-md-12 text-left =" style="margin-top:15px;">  
<button type="button" class="btn btn-secondary-custom" style="margin-right:10px;">Edit</button>
<button type="button" class="btn btn-secondary-custom">Delete</button>   
</div>
</div>
</div>
</label>
      <label class="fullWidth" style="margin-top:10px;">
<input type="radio" name="selectAddress" class="card-input-element d-none hideOffScreen addressRadio" id="address2" value="address2">
<div class="card card-body bg-light d-flex flex-row justify-content-between align-items-center radioCard">
<div class="addressField">Sally Smith</div>
<div class="addressField">555 Elm St.</div>
<div class="addressField">Nantucket, CA 55698</div>
<div class="row">
<div class="col-md-12 text-left">
<div class="deliverButton" style="margin-top:12px;">
<div type="button" class="btn btn-primary-custom" style="margin-right:10px;">Deliver to this Address</div>
</div>
<div class="selectedAddressButton" style="margin-top:12px;">
<div style="margin-top:12px;"><div type="button" class="btn btn-success-custom" style="margin-right:10px;"><i class="fa fa-check" aria-hidden="true" style="padding-right:6px;"></i>Selected Address</div></div>
</div> 
</div>
</div>
<div class="row">
<div class="col-md-12 text-left =" style="margin-top:15px;">  
<button type="button" class="btn btn-secondary-custom" style="margin-right:10px;">Edit</button>
<button type="button" class="btn btn-secondary-custom">Delete</button>   
</div>
</div>
</div>
</label>
    </div>
    <!-- /.radioPanel -->
  </div>
</div>
0 голосов
/ 16 февраля 2019

Вы должны установить вид по умолчанию, когда установлен любой флажок, попробуйте следующий код:

jQuery(function () {
    jQuery(".addressRadio").change(function() {
        if (jQuery(this).is(":checked")) {
            jQuery(document).find(".selectedAddressButton").hide(); // To hide all select buttons
            jQuery(document).find(".deliverButton").show(); //To show all deliver button                 
            jQuery(this).siblings().find(".selectedAddressButton").show();
            jQuery(this).siblings().find(".deliverButton").hide();
        } else {
            jQuery(this).siblings().find(".selectedAddressButton").hide();
            jQuery(this).parents().find(".deliverButton").show();
        }
    });

Надеюсь, это поможет вам.

0 голосов
/ 16 февраля 2019

Одним из способов упростить это было бы использование метода «переключения».

jQuery(".selectedAddressButton").hide();

jQuery(function () {
    jQuery(".addressRadio").change(function() {   
        jQuery(this).siblings().find(".selectedAddressButton").toggle();
        jQuery(this).siblings().find(".deliverButton").toggle();
    }
});

Переключение не требует, чтобы вы знали предыдущее состояние.Таким образом, вам даже не нужно знать, был ли установлен флажок.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...