onclick收音机输入显示php

时间:2016-08-10 06:37:41

标签: javascript

我想在下面的无线电结果html示例中执行php代码。

<form>
    <input type="radio" name="type" value="0" checked />Staff
    <input type="radio" name="type" value="1" />Client
</form>
在php中我可以做到这一点

<?php
    if($_POST['type'] == 1){
        echo "some of my php code";
    } else {
        echo "my second option php code";
    }
?>

但不知道如何使用onclick

在javascript中实现该代码

3 个答案:

答案 0 :(得分:0)

你需要ajax。 Php在javascript之前执行,因此在您点击后无法更改(仅当提交并刷新页面时)。

答案 1 :(得分:0)

如果你不需要ajax:

获取DOM元素并添加事件侦听器:

var inputRadio = document.querySelectorAll("input[type='radio']");

for(var i = 0; i < inputRadio.length; i++) {
    inputRadio[i].addEventListener('click', function() {
        console.log(this); // if you click the radio button, 
                           // it will be logged to the console
    });

    /* 
        instead of `addEventListener` you can use:

        inputRadio[i].onclick = function() { }
    */


}

答案 2 :(得分:0)

您可以在检查单选按钮值后执行代码。我在这里用于改变事件。

    $('input[name=radioName]').change(function(){
      var value = $('input[name=radioName]:checked').val();
          if(value == 1){
          //do anything
            alert(value);
          }else{
            //do anything
            alert(value);
            }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="radio" name="radioName" value="1" /> 1
    <input type="radio" name="radioName" value="0" /> 0
var result = $('input[name=type]:checked').val()); if(result == 1){ //"do anything" } else{ //"do anything" }
相关问题