0

I want to execute php code base on radio result html example below.

<form>
    <input type="radio" name="type" value="0" checked />Staff
    <input type="radio" name="type" value="1" />Client
</form>

in php I can do this

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

but no idea how to implement that code in javascript using onclick

jhunlio
  • 2,550
  • 4
  • 26
  • 45
  • add attribute in radio element like onchange="this.form.submit();" – user5200704 Aug 10 '16 at 06:43
  • You need to submit the form. If you want to do this with javascript you need to use ajax. Take a look at here: http://stackoverflow.com/questions/1200266/submit-a-form-using-jquery – Ozan Aug 10 '16 at 06:43
  • Are you submitting this form to some PHP's action page? I am asking this because you cannot execute PHP code on same page based on radio selection. PHP is a server side language and it can only get executed on server whereas HTML is a client side language which execute on client side (end user's browser). – d.coder Aug 10 '16 at 06:44
  • i need to make change data value base on radio value before i submit the form that is why javascript is my only option – jhunlio Aug 10 '16 at 06:45

3 Answers3

0

You need ajax. Php is executed before javascript, so it cant change after your click (only if submit and refresh the page).

darthcharmander
  • 129
  • 1
  • 7
0

If you don't need ajax:

Get the DOM element and just add event listeners:

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() { }
    */


}
0

You can execute your code after check radio button value. Here I am using on change event.

    $('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" }
Anshul
  • 464
  • 4
  • 14