質問

I have couple of radio buttons from bootstrap like below.

<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>

How can I perform specific action for each radio button in jQuery?

for instance:

if option1 is checked -> load "html1.html"
if option2 is checked -> load "html2.html"

And I use this code to load an html code in specific div :

<script>
   $(document).ready(function(){ 
       $('#main-content').load('skill-temp.html');
   });
</script>
役に立ちましたか?

解決 2

I believe the easiest way is to have a data attribute in your input, guiding the jQuery load action. Something like:

 <input class="loadhtml" data-html="page1" type="radio" name="options" id="option1">
 <input class="loadhtml" data-html="page2" type="radio" name="options" id="option2">
 <input class="loadhtml" data-html="page3" type="radio" name="options" id="option2">

and then

 <script>
 $('input.loadhtml').on('change', function(){
    var data = $(this).data('html');
    $('#main-content').load(data + '.html');
 });
 </script>

edit

A fiddle, with the only difference i alert(data) passed instead of calling load

他のヒント

You can do something like this:

$('input[name="options"]').change(function() {
    var num = this.id.match(/\d+$/);
    $('#main-content').load('html'+num+'.html');
});

I found the Answer

$(document).on('change', 'input:radio[class^="loadhtml"]', function (event) {
 var data = $(this).data('html');
$('#main-content').load(data + '.html');
});

Add class="loadhtml" to each radio button

<div id="nav" class="btn-group btn-group-vertical" data-toggle="buttons">
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" data-html="Skills" name="options"><span class="fa fa-lock"></span> About
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Skills
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Education
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Timeline
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Hobbies</label>

$('input:radio[name="options"]').change(
        function(){

            var id =this.id;
            if ( id  == 'option1') {
               // call html page 1
            }
             else if( id  == 'option2'){
              // call html page 2

             }    

        });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top