简体   繁体   中英

Radio Buttons not showing checked

I have created some radio buttons that when clicked show a price. The code I am using is below..

   <label for='<?php echo $price; ?>' class="tabs">
   <input type="radio" name="j" class="radioBtn" id='<?php echo $price; ?>' value="<?php echo $price; ?>" onclick="calculate(this);" />
   <?php echo $number; ?>
   </label>

The price is then being shown like this:

<span class="prices" id="output"></span>

by

function calculate(obj) { document.getElementById("output").innerHTML = obj.value;}

The prices and buttons are working correctly, but I need to style the label to show that the correct button has being selected. In the DOM it says that the radio input is checked, but it's not being rendered in the HTML.

I also need to get the first checkbox to be selected as default.

Can anyone help point me in the right direction at all please?

Paddy

The grofar.com site looks fine to me. When you say the styling isn't working on the label, what exactly do you mean? Are you trying to apply a different color, font, etc.?

As for making the first option selected by default, you have a few options. The first would be to use PHP to determine the first one and add the checked attribute to the input element. For instance, if you are doing a loop, use an if/then statement to set the checked attribute if the loop counter is 1.

A second option is to use jQuery to select the first box:

$(function() {
   $("input[name='j']:first").prop("checked", true);
});

However, with that method, your calculate function is not called and therefore the price is not updated.

A third option is to use jQuery to simulate a click of the first box:

$(function() {
    $("input[name='j']:first").click();
});

That will select the box and update the price.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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