简体   繁体   English

如何使用 JavaScript 和 PHP 检查是否选择了单选按钮

[英]How can I check if a radio button is selected using JavaScript and PHP

I have a few images that should be a radio button and the uses should select and proceed with the page, but isn't working, it always returns that "Please mark a product".我有一些应该是单选按钮的图像,用途应该是 select 并继续页面,但不起作用,它总是返回“请标记产品”。

PHP Code PHP 代码

        $shoppingTable = array( 
    array("radioValue" => 001, "url_image" => "/images/a.png", "Price" => 19.99, "Coins" => 25, "Package" => 1),
    array("radioValue" => 002, "url_image" => "/images/b.png", "Price" => 34.99, "Coins" => 40, "Package" => 2),
    array("radioValue" => 003, "url_image" => "/images/c.png", "Price" => 49.99, "Coins" => 80, "Package" => 3),
    array("radioValue" => 004, "url_image" => "/images/d.png", "Price" => 89.99, "Coins" => 125, "Package" => 4),
    array("radioValue" => 005, "url_image" => "/images/e.png", "Price" => 124.99, "Coins" => 150, "Package" => 5),
);

echo '<form action="http://'.$_SERVER['HTTP_HOST'].'/?view=donatecoins&action=check" method="post" onsubmit="return validaDados(this);"><input type="hidden" name="method" value="1"/>'; '
    foreach($shoppingTable as $i => $shop) {
        echo '<div id="'.$shop['Package'].'" class="product coin">
            <span class="title">
                <span class="amount">'.$shop['Coins'].'</span>
                <br>
                    coins
            </span>

            <div class="product_coin_image" style="background-image: url('.$shop['url_image'].');"></div>
            <div class="price">R$ '.$shop['Price'].'</div>
            <input type="radio" name="ProdValor_1" id="ProdValor_1" value="'.$shop['radioValue'].'"/>
        </div>';
    }
echo '</form>';

JavaScript Function JavaScript Function

function validaDados(frm)
{
    var f;
    for (i=frm.ProdValor_1.length-1; i > -1; i--) {
        if (frm.ProdValor_1[i].checked) {
            f = true;
            break;
        }
    }

    if(!f) {
        alert("Please mark a product.");
        return false;
    }
}

You can try using the isset function of php.您可以尝试使用 php 的 isset function。 To check if the radio button is checked or not.检查单选按钮是否被选中。 isset function returns true if the radio button is checked.如果选中单选按钮,则 isset function 返回 true。

 <?php 
    f=false;
    if (isset($ProdValor_1))
      {
         f=true;
         echo "A product is checked";
      }

    if(!f) {
      echo "Please mark a product.";
    }
?>

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

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