简体   繁体   English

如何在选择单选按钮时加载文本?

[英]How do I load text on selection of radio button?

I have a Radio button input which says No and Yes. 我有一个单选按钮输入,提示“否”和“是”。 How do I load "Hello World" when I select no, and "Hello World 1" when I select yes. 选择否时如何加载“ Hello World”,选择是时如何加载“ Hello World 1”。

By default, both the hello world and hello world 1 should be disabled. 默认情况下,hello world和hello world 1均应禁用。 Any help? 有什么帮助吗?

Regards, Bill 问候,比尔

 <span>No</span> <span class="float-right mr-3"> <input type="radio" name="damage"> </span> <span class="">Yes</span> <span class="float-right mr-3"> <input type="radio" name="damage"> </span> <p>Hello World</p> <p>Hello World 1</p> 

You can modify your code to give each radio a data attribute and class. 您可以修改代码以为每个无线电提供数据属性和类。 That way you can simplify the code and even plan ahead 这样,您可以简化代码,甚至提前计划

 $(document).ready(function(){ $(document).on("change",".data-radio",function(){ $(".data-content").hide(); $($(this).data("content")).show(); }); }); 
 .data-content{display:none;} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span>No</span> <span class="float-right mr-3"> <input type="radio" class="data-radio" data-content=".no-damage" name="damage"> </span> <span class="">Yes</span> <span class="float-right mr-3"> <input type="radio" class="data-radio" data-content=".damaged" name="damage"> </span> <p class="data-content no-damage">No Damage!</p> <p class="data-content damaged">Damaged!</p> 

This answer might be easier to understand. 这个答案可能更容易理解。

Here a single <p></p> element is created and a specific id="output-text" is given to it. 在这里,创建了一个<p></p>元素,并为其指定了特定的id="output-text"

add onclick attribute to each radio button and in the listener function (in this code clicked() function) pass the data you want to so. onclick属性添加到每个单选按钮,然后在侦听器函数(在此代码中, clicked()函数)中传递您想要的数据。 And rest of work is done by javascript . 其余工作由javascript完成。

See the following code: 请参见以下代码:

 function clicked(val) { document.getElementById("output-text").textContent = val; } 
 <span>No</span> <span class="float-right mr-3"> <input onclick="clicked('Hello World')" type="radio" name="damage"> </span> <span class="">Yes</span> <span class="float-right mr-3"> <input onclick="clicked('Hello World 1')" type="radio" name="damage"> </span> <p id="output-text"></p> 

Hope, this helps. 希望这可以帮助。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM