Удалить клас если сменилась option в select
Здравствуйте!
Нашел на этом форуме отличный пример, при смене опции он удаляет и добавляет клас, хороший пример. Но как быть если уже опция выбрана. например при редактировании документа. Но этот вариант подходит только к созданию документа когда поумолчанию выбрана опция "ничего не выбрано" А если редактирования документа в котором опция другая а не "ничего не выбрано", можно удалять класс? <!doctype html> <html> <head> <title></title> <meta charset='utf-8' /> <style> .bl { display: none; } </style> </head> <body> <select name="sel" id="sel"> <option value=""></option> <option value="one">one</option> <option value="two">two</option> <option value="three">three</option> </select> <div id="toShow" class="variations_button bl">Hello, I am hidden block</div> <script> var sel = document.getElementById('sel'); sel.addEventListener('change', function (event) { if(this.value) { document.getElementById('toShow').classList.remove('bl') } else { document.getElementById('toShow').classList.add('bl') }; }) </script> </body> </html> |
подожду переводчика ... :(
|
Цитата:
Писал ночью, и сейчас тоже бы не отказался от переводчика))) В общем) Нужен такойже скрипт, который бы работал только тогда, когда выбрана опция "-- Выбрать --" Пример: Создаем статью, есть выпадающий список Цвет: Поумолчанию установлена опция "-- Выбрать --" активируем скрипт и он ждет когда мы изменим опцию на "Синий" - изменили, скрипт добавил класс show. Заходим в редактирование статьи, и вней видим что уже выбрана опция "Синий" скрипт добавил класс show. Мы выбираем опцию "-- Выбрать --" скрипт удаляет класс show:) Это у меня такой костыль чтобы сделать выбор "партнера" обязательным, потому что я уже четвертый день никак немогу заставить ajax не отправлять данные если input name="affiliate_id" пустой... Прилагаю скрипт который как по мне отвечает за отправку данных, может глянете, пока я слюни не начал пускать) // Checkout $('#button-save').on('click', function() { if ($('input[name=\'order_id\']').val() == 0) { var url = '{{ catalog }}index.php?route=api/order/add&api_token={{ api_token }}&store_id=' + $('select[name=\'store_id\'] option:selected').val(); } else { var url = '{{ catalog }}index.php?route=api/order/edit&api_token={{ api_token }}&store_id=' + $('select[name=\'store_id\'] option:selected').val() + '&order_id=' + $('input[name=\'order_id\']').val(); } $.ajax({ url: url, type: 'post', data: $('select[name=\'payment_method\'] option:selected, select[name=\'shipping_method\'] option:selected, #tab-total select[name=\'order_status_id\'], #tab-total select, textarea[name=\'comment\'], input[name=\'affiliate_id\']'), dataType: 'json', crossDomain: true, beforeSend: function() { $('#button-save').button('loading'); }, complete: function() { $('#button-save').button('reset'); }, success: function(json) { $('.alert-dismissible, .text-danger').remove(); if (json['error']) { $('#content > .container-fluid').prepend('<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>'); } if (json['success']) { $('#content > .container-fluid').prepend('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>'); } if (json['order_id']) { $('input[name=\'order_id\']').val(json['order_id']); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); $('#content').delegate('button[id^=\'button-upload\'], button[id^=\'button-custom-field\'], button[id^=\'button-payment-custom-field\'], button[id^=\'button-shipping-custom-field\']', 'click', function() { var node = this; $('#form-upload').remove(); $('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>'); $('#form-upload input[name=\'file\']').trigger('click'); if (typeof timer != 'undefined') { clearInterval(timer); } timer = setInterval(function() { if ($('#form-upload input[name=\'file\']').val() != '') { clearInterval(timer); $.ajax({ url: 'index.php?route=tool/upload/upload&user_token={{ user_token }}', type: 'post', dataType: 'json', data: new FormData($('#form-upload')[0]), cache: false, contentType: false, processData: false, beforeSend: function() { $(node).button('loading'); }, complete: function() { $(node).button('reset'); }, success: function(json) { $(node).parent().find('.text-danger').remove(); if (json['error']) { $(node).parent().find('input[type=\'hidden\']').after('<div class="text-danger">' + json['error'] + '</div>'); } if (json['success']) { alert(json['success']); } if (json['code']) { $(node).parent().find('input[type=\'hidden\']').val(json['code']); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } }, 500); }); $('.date').datetimepicker({ language: '{{ datepicker }}', pickTime: false }); $('.datetime').datetimepicker({ language: '{{ datepicker }}', pickDate: true, pickTime: true }); $('.time').datetimepicker({ language: '{{ datepicker }}', pickDate: false }); |
Alexprom,
<!doctype html> <html> <head> <title></title> <meta charset='utf-8' /> <style> .red { color: Red; } .green { color: Green; } .blue { color: Blue; } </style> </head> <body> <select name="sel" id="sel"> <option value="">-- Выбрать --</option> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <div id="toShow" class="variations_button bl">Hello, I am hidden block</div> <script> var sel = document.getElementById('sel'), div = document.getElementById('toShow'), current; sel.addEventListener('change', function(event) { if (current) div.classList.remove(current) if (this.value) { current = this.value; document.getElementById('toShow').classList.add(current); } }) </script> </body> </html> |
Спасибо):)
|
Часовой пояс GMT +3, время: 17:45. |