javascript - 如何根据用户选择的单选按钮更改要显示的内容?

标签 javascript jquery html

我将创建 3 个单选按钮供用户选择。一旦用户单击该按钮,它将向用户显示用户选择的该单选按钮的描述。

例如

- if user select first radio button ==> it will show the description under that
                                        radio button

- if user select second radio button ==> it will show the description under that
                                        radio button

- if user select third radio button ==> it will show the description under that
                                        radio button

我的代码

<p><input type='radio' name='content_type' value='1' />&nbsp;This is content A of request</p>
<p><input type='radio' name='content_type' value='2' />&nbsp;This is content B of request</p>
<p><input type='radio' name='content_type' value='3' />&nbsp;This is content C of request</p>
<div id='show'></div>

Javascript

$(document).ready(function(){
    $('#content_type').on('change', function(){
    var n = $(this).val();
    switch(n)
    {
            case '1':
                  document.getElementById('#show').innerHTML="1st radio button";
                  break;
            case '2':
                  document.getElementById('#show').innerHTML="2nd radio button";
                  break;
            case '3':
                  document.getElementById('#show').innerHTML="3rd radio button";
                  break;
        }
    });

我上面的代码不起作用。谁能帮我解决这个问题?

提前致谢

最佳答案

您错误地使用了 jQuery 选择器。您还需要关闭 $(document).ready()。正确的代码:

$(document).ready(function(){
    $('input[name=content_type]').on('change', function(){
    var n = $(this).val();
    switch(n)
    {
            case '1':
                  $('#show').html("1st radio button");
                  break;
            case '2':
                  $('#show').html("2nd radio button");
                  break;
            case '3':
                  $('#show').html("3rd radio button");
                  break;
        }
    });
});

JSfiddle

关于javascript - 如何根据用户选择的单选按钮更改要显示的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19701451/

相关文章:

javascript - 添加输入框后获取值

html - 我的 html 没有在页面上呈现什么?

php - 没有文件名的表单操作

javascript - 访问 jQuery 文件中的 PHP session 变量

javascript - 如何使用ajax创建目录并在其中上传文件?

javascript - 在Safari/Chrome中,如何在ready()和focus()上触发函数A,在blur()上触发函数B?

javascript - 如何从 Protractor 中的 promise 中获取嵌套的 JSON

javascript - 使用 jQuery 缩短创建 DOM 片段的代码

javascript - Google Meet 如何显示 CPU 使用率?

javascript - 单例模式的简单 JS 示例不起作用