简体   繁体   English

我收到了单选按钮的 output 值,即使其中一个被选中

[英]i receive the output value of radio buttons as both on even though one is checked

I only did this code of java script我只做了 java 脚本的这段代码

so maybe I need to do an add event listener but i don't know what I need to do所以也许我需要做一个添加事件监听器,但我不知道我需要做什么

pick_up:document.getElementById("shippingOption1").value,
            delivery:document.getElementById("shippingOption2").value
the output is 
pick up:onor

delivery:on

i want so that one of them be on if checked and off if its not checked how can i do that?我希望其中一个在选中时打开,如果未选中则关闭我该怎么做?

html html

<div class="custom-control custom-radio">
<input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio">

<div class="custom-control custom-radio"><input id="shippingOption1" name="shipping-option" class="custom-control-input" checked="checked" type="radio" ">
<label class="custom-control-label" for="shippingOption1">

ps I already tried adding value of 1 and 2 to html code but it only gives 1 and 2 regardless that its not checked ps 我已经尝试将 1 和 2 的值添加到 html 代码,但它只给出 1 和 2,不管它没有被检查

In order to see if a radio button is selected or not, you should use the .checked attribute.为了查看单选按钮是否被选中,您应该使用.checked属性。

pick_up: document.getElementById("shippingOption1").checked,
delivery: document.getElementById("shippingOption2").checked

For value, you could add the attribute value="delivery" in order to know what is checked without knowing it's id .对于价值,您可以添加属性value="delivery"以便在不知道它的id的情况下知道检查了什么。

Here's a piece of code how it works:这是一段代码,它是如何工作的:

 function handleChange() { const options = { pick_up: document.getElementById("shippingOption1").checked, delivery: document.getElementById("shippingOption2").checked } const result = document.querySelector('.result'); if (options.pick_up) { result.textContent = 'You chose pickup'; } else if(options.delivery) { result.textContent = 'You chose delivery'; } console.log(options); };
 <div class="custom-control custom-radio"> <input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="delivery"> <label class="custom-control-label" for="shippingOption2">delivery</label> </div> <div class="custom-control custom-radio"> <input id="shippingOption1" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="pick_up"> <label class="custom-control-label" for="shippingOption1">pick_up</label> </div> <div class="result">Select an option</div> <div class="result2">The value of the selected option is: </div>

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

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