Programing

버튼 라디오의 Twitter Bootstrap onclick 이벤트

lottogame 2020. 12. 10. 08:27
반응형

버튼 라디오의 Twitter Bootstrap onclick 이벤트


Twitter Bootstrap 버튼 라디오가 있고 onclick 이벤트를 연결합니다. 그러나 어떤 버튼이 트리거되었는지 어떻게 확인합니까?

내 첫 번째 생각은 단순히 'active'클래스를 확인하는 것이었지만 경쟁 조건이 생성되어야합니다 (결과는 Twitter Bootstrap 이벤트 또는 내 onclick 이벤트가 먼저 처리되는지 여부에 따라 다릅니다).


이것은 정말 성가신 일입니다. 내가 사용하게 된 것은 다음과 같습니다.

먼저 data-toggle속성 이없는 간단한 버튼 그룹을 만듭니다 .

<div id="selector" class="btn-group">
    <button type="button" class="btn active">Day</button>
    <button type="button" class="btn">Week</button>
    <button type="button" class="btn">Month</button>
    <button type="button" class="btn">Year</button>
</div>

다음으로 클릭 된 버튼을 '활성화'하고 다른 모든 버튼을 '비활성화'하여 라디오 버튼 효과를 시뮬레이션하는 이벤트 핸들러를 작성합니다. (편집 : 주석에서 통합 된 Nick 의 클리너 버전.)

$('#selector button').click(function() {
    $(this).addClass('active').siblings().removeClass('active');

    // TODO: insert whatever you want to do with $(this) here
});

복잡한 답변이 많이 보이지만 Bootstrap 3에서는 매우 간단합니다.

1 단계 : 공식 예제 코드 를 사용하여 라디오 버튼 그룹을 만들고 컨테이너에 ID를 제공합니다.

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>

2 단계 :이 jQuery 핸들러 사용 :

$("#myButtons :input").change(function() {
    console.log(this); // points to the clicked input button
});

바이올린 데모 사용해보기


다음과 같은 클릭이 아닌 변경 이벤트를 사용합니다.

$('input[name="name-of-radio-group"]').change( function() {
  alert($(this).val())
})

Bootstrap 3의 경우 기본 라디오 / 버튼 그룹 구조는 다음과 같습니다.

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option1"> Option 1
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option2"> Option 2
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option3"> Option 3
    </label>
</div>

다음과 같이 활성 상태를 선택할 수 있습니다.

$('.btn-primary').on('click', function(){
    alert($(this).find('input').attr('id'));
}); 

토글 동작을 직접 제어 할 수 있도록 data-toggle 속성을 사용하지 마십시오. 그래서 그것은 '경주 조건'을 피할 것입니다

내 코드 :

버튼 그룹 템플릿 (.erb로 작성, 루비의 레일에 포함 된 루비) :

<div class="btn-group" id="featuresFilter">
     <% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
</div>

및 javascript :

onChangeFeatures = function(e){
        var el=e.target;
        $(el).button('toggle');

        var features=el.parentElement;
        var activeFeatures=$(features).find(".active");
        console.log(activeFeatures);
}

버튼을 클릭하면 onChangeFeatures 함수가 트리거됩니다.


표시해야하는 데이터의 기간을 선택할 수있는 차트에 대해서도 동일한 작업을 수행해야했습니다.

따라서 CSS 클래스 'btn-group-radio'를 도입하고 다음과 같은 눈에 잘 띄지 않는 자바 스크립트 한 줄을 사용했습니다.

// application.js
$(document).ready(function() {
  $('.btn-group-radio .btn').click(function() {
    $(this).addClass('active').siblings('.btn').removeClass('active');
  });
});

다음은 HTML입니다.

<!-- some arbitrary view -->
<div class="btn-group btn-group-radio">
  <%= link_to '1W', charts_path('1W'), class: 'btn btn-default active', remote: true %>
  <%= link_to '1M', charts_path('1M'), class: 'btn btn-default', remote: true %>
  <%= link_to '3M', charts_path('3M'), class: 'btn btn-default', remote: true %>
  <%= link_to '6M', charts_path('6M'), class: 'btn btn-default', remote: true %>
  <%= link_to '1Y', charts_path('1Y'), class: 'btn btn-default', remote: true %>
  <%= link_to 'All', charts_path('all'), class: 'btn btn-default', remote: true %>
</div>

Twitter Bootstrap 페이지 ( http://twitter.github.com/bootstrap/base-css.html#forms ) 의 라디오 버튼에 대한 HTML 예제를 보면 각 입력에 고유 한 ID 속성 (예 : optionsRadios1및)이 있음을 알 수 optionsRadios2있습니다.

완전성을 위해 관련 HTML 예제 스 니펫이 여기에 포함되어 있습니다.

<div class = "controls">
  <label class = "radio">
    <input type = "radio"checked = ""value = "option1"id = "optionsRadios1"name = "optionsRadios">
    옵션 1은 이것과 저것입니다. 그 이유를 반드시 포함하십시오.
  </ 라벨>
  <label class = "radio">
    <input type="radio" value="option2" id="optionsRadios2" name="optionsRadios">
    Option two can is something else and selecting it will deselect option one
  </label>
</div>

So you can use a jQuery click event, and then use the this reference to look at the id of the HTML element that was clicked.

$('.controls').find('input').bind('click',function(event){
  if($(this).attr('id')==='optionsRadios1'){
    alert($(this).attr('id'));
  } else {
    //... call some other function
  }
});

I searched so many pages: I found a beautiful solution. Check it out:

git link

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

    <script>
        $(function() {
            $("#my_launch_today_chk").change(function() {
                var chk = $(this).prop('checked');
                if(chk == true){
                    console.log("On");
                }else{
                    console.log("OFF");
                }
            });
        });
    </script>
</head>
<body >

<input type="checkbox" id="my_launch_today_chk" checked data-on="Launch" data-off="OFF" data-toggle="toggle" data-size="small">
</body>
</html>

If your html is similar to the example, so the click event is produced over the label, not in the input, so I use the next code: Html example:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>      
</div>

Javascript code for the event:

$('#option1').parent().on("click", function () {
   alert("click fired"); 
});

참고URL : https://stackoverflow.com/questions/9262827/twitter-bootstrap-onclick-event-on-buttons-radio

반응형