选择单选按钮时显示<p>

时间:2017-03-26 15:44:00

标签: javascript html addeventlistener

我是JS + HTML的新手,但基本上我想要4个单选按钮,每个按钮都有不同的名称

o PS4
o Xbox
o Nintendo DS

当点击/选中其中一个时,我想输出将在它们旁边的“p”中保存的价格,如图所示

o PS4   £400
""
""

然后在点击下一个时隐藏价格,然后显示相应的价格,我花了几个小时试图搜索并测试一些东西,但似乎什么都没有用,所以非常感谢任何帮助

谢谢,

3 个答案:

答案 0 :(得分:0)

以下是完全正常的代码:

$(document).ready(function(){
$(".price").hide();
$("input").click(function(){
	$(".price").hide();
  $(this).siblings().show();
});
});
<form id="form">
<span>
<input type="radio" name="drink" value="vodka"/>Vodka <span  class="price">$40</span><br />
</span>
<span>
<input type="radio" name="drink" value="beer"/>Beer <span class="price">$50</span><br />
</span>
<span>
<input type="radio" name="drink" value="juice"/>Juice <span class="price">$20</span><br />
</span> 
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

或直接在这里试试这个jsfiddle: https://jsfiddle.net/balyancoder/dbgkfw0f/

答案 1 :(得分:0)

这是一个简单的JavaScript示例:

<form id="form">
  <label>
    <input name="console" type="radio" value="400">PS4</label>
  <label>
    <input name="console" type="radio" value="350">XBox</label>
  <label>
    <input name="console" type="radio" value="200">Nintendo DS</label>
</form>
<br>
<div>Price:
  <div id="price"></div>
</div>

JavaScript(使用ES6)

document.getElementById('form').addEventListener('change', () => {

  const radios = document.getElementsByName('console');

  Object.keys(radios).forEach((obj, i) => {
    if (radios[i].checked) {
      price = document.getElementById('price');
      price.innerHTML = `<p>£${radios[i].value}</p>`;
    }
  });

});

样品: JsFiddle

答案 2 :(得分:0)

以下是使用普通javascript和段落标记以及每个单选按钮的示例:

HTML:

<ul>
    <li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 1
        <p class="parag">price 1</p>
    </li>
    <li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 2
        <p class="parag">price 2</p>
    </li>
    <li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 3
        <p class="parag">price 3</p>
    </li>
    <li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 4
        <p class="parag">price 4</p>
    </li>
</ul>

使用Javascript:

var radios = document.getElementsByClassName("radio_btn");
for (var i = 0; i < radios.length; i++) {
    radios[i].addEventListener(
        'click',
        function() {
            var parags = document.getElementsByClassName("parag");
            for (var i = 0; i < parags.length; i++) {
                parags[i].style.display = "none";
            }
            this.nextElementSibling.style.display = "inline-block";
        }
    );
}

这里is JSFiddle上的示例