質問

If I haev a radio button group in bootstrap like the following :

<div class="btn-group" data-toggle="buttons-radio">
        <button class="btn">1</button>
        <button class="btn">2</button>
        <button class="btn">3</button>
        <button class="btn">4</button>
</div>

How can I get/ set the selected value ?

役に立ちましたか?

解決

var num = null;
var ele = document.querySelectorAll(".btn-group > button.btn");
for(var i=0; i<ele.length; i++){
    ele[i].addEventListener("click", function(){
        num = +this.innerHTML;
        alert("Value is " + num);
    });
}

Or jQuery:

var num = null;
$(".btn-group > button.btn").on("click", function(){
    num = +this.innerHTML;
    alert("Value is " + num);
});

他のヒント

To set the active element, add the class active to whichever button you want selected (and deselect the rest).

$('.btn-group > .btn').removeClass('active')    // Remove any existing active classes
$('.btn-group > .btn').eq(0).addClass('active') // Add the class to the nth element

To get the html/text content of the currently active button, try something like this:

$('.btn-group > .btn.active').html()

Here is one more solution

 alert($('.btn-group > .btn.active').text());
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top