Link to home
Start Free TrialLog in
Avatar of Tanabe Saori
Tanabe SaoriFlag for Japan

asked on

How do I assign the value of a radio button to a php variable

I have two divs where either one is hidden and the other one isn't.
these are generated by PHP and I have to set the initial state of the divs based on a radio button set named 'worksheets'.
<input type="radio" name="worksheets" value="alpha" id="worksheets_0" checked="checked">
<input type="radio" name="worksheets" value="nums" id="worksheets_1">

Open in new window

I've already worked out grabbing which radio button is selected, using:
$("input[type='radio'][name='worksheets']:checked").val();

Open in new window

so, I attempted to echo this, but ran into syntax trouble with the mixed single and double quotes in the javascript.
a$ = "
a$= "<script>$("input[type='radio'][name='worksheets']:checked").val();</script>";

Open in new window


So then I tried to put that into a function and call the function, but was still stuck.
a$ = "<script type='text/javascript'>worksetter();</script>";

Open in new window

I also tried
a$ = "?> <script type='text/javascript'>worksetter();</script> ?>";

Open in new window

which isn't working either. Lastly, I tried
a$ = echo "<script type='text/javascript'>worksetter();</script>";

Open in new window

of course, that doesn't work either. I tried a couple other things, which didn't work either.

What am I missing?
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

It seems you are trying to run php on the client or run javascript on the server.

To get the clicked button in PHP you need to add it to a form and submit that form with the radio button to the server.
Alternatively AJAX the value to a php on the server
So simple version:

<form action="readRadioButton.php" method="post">
<input type="radio" name="worksheets" value="alpha" id="worksheets_0" checked="checked">
<input type="radio" name="worksheets" value="nums" id="worksheets_1">
<input type="submit">
</form>

Open in new window

Here there,

OK. Javascript and PHP don't talk to each other - one is client-side (the browser) and one is server-side. You can submit values from your form to the server and read values in PHP from there, but you can't set a PHP variable directly with Javascript.
Ajax:

<div id="radios">
  <input type="radio" name="worksheets" value="alpha" id="worksheets_0" checked />
  <input type="radio" name="worksheets" value="nums" id="worksheets_1" />
</div>

Open in new window

document.getElementById("radios").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.name === "worksheets") {
    const val = tgt.value;
    fetch('readRadioButton.php', {
      method: 'post',
      body: JSON.stringify({"worksheets":val})
    }).then(function(response) {
      return response.json();
    }).then(function(data) {
      console.log('result', data);
    });
  }
})

Open in new window


PHP
<?php
  $ worksheets = isset($_POST["worksheets"]) ? $_POST["worksheets"] : "";
  header("content-type: application:json");
  echo '{ "received","'.$worksheet.'"}';
?>

Open in new window

have a look at this code

https://jsfiddle.net/HainKurt/1rv0ntdL/

if ($("input[name='worksheets']").val() == "worksheets_0") {
  $("#div1").hide();
} else {
  $("#div0").hide();
}

Open in new window

you dont need php for this, just use client side...
SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What is it you are trying to achieve?

I understand the radio's toggle the divs but what are you wanting to do with the code you showed us in your post?

Is it just a case of showing one div while hiding another - or is it about communicating this back to the server.

You can toggle divs using just CSS
.show-hide-div + div {
    visibility: hidden;
}
.show-hide-div:checked + div {
    visibility: visible;
}

Open in new window

HTML
<input type="radio" class="show-hide-div" name="toggle-div" checked>
<div>
    <p>Hwæt. We Gardena in geardagum, þeodcyninga, þrym gefrunon, hu ða æþelingas ellen fremedon

</p>
</div>
<input type="radio" class="show-hide-div" name="toggle-div">
<div>
    <p>Oft Scyld Scefing sceaþena þreatum, monegum mægþum, meodosetla ofteah, 
 egsode eorlas. Syððan ærest wearð feasceaft funden, he þæs frofre gebad</p>
</div>

Open in new window

We use adjacent sibling operators to target the div adjacent to the checked div.
Avatar of Tanabe Saori

ASKER

Michel, the buttons are part of a larger form.  Now that I'm expanding my worksheet system, there are  mini portions wrapped in DIVs that get turned into forms when they are needed. (this was the question that I resolved myself and I posted how I accomplished that, there).
As I started building out version two of this worksheet system, I realize that I need to get the value of the selected radio from the main form (the worksheet buttons).
For example, I have this code, unrelated, that works great:
<?PHP
if (!$mysqli->query($query)) {
printf("Errormessage: %s\n", $mysqli->error);
}
echo "<script type='text/javascript'>unsetter();</script>";
} 
?>

Open in new window

where the javascript does this:
<script>
function unsetter() 
{
  $('<form id = "unset" name = "unset" METHOD="GET"><input type="submit"></form>').appendTo('body');
  $( "#unset" ).submit();
} 
</script>

Open in new window

So, I was just trying to do something similar, but instead of echo, I thought I could replace echo with a variable; a$=.

I came up with a different solution, which is to load all items, for alpha and nums, from the query, not just the alpha items. I then fill a second DIV with the nums data, but hide it. I can then click either radio and have jquery toggle which one is shown.
I'm currently debugging this, but I'm still interested in working out this original question.
Julian Hansen , yes, in this revised solution, it is to get the selected radio value in order to show and hide divs that have one of two classes. This is now working. I will still need this value (which is selected) once the "mini forms" are actually appended and submitted. But, at that point, I'll be in Javascript/jquery and can include that in the built form (that solution is in my previous troubleshooting question, which I resolved).
Now I'm trying to disable the inputs of the hidden div using jquery so they don't get submitted.
Can I use
    $(".sideways :input").attr(‘disabled’, true);

Open in new window

Where sideways is a class?
Ah, I suppose I can just empty the divs that are hidden before submitting.
you can disable div
and hide

$(".sideways").attr('disabled','disabled');
$(".sideways").hide();

Open in new window


setting as disabled/hiding does not work...
but this works

$(".sideways").remove();

Open in new window


this one also works!
in case you need to attach again later!

var divSideways = $(".sideways").detach();

Open in new window

HI HainKurt, I posted this as a more concise question here.
https://www.experts-exchange.com/questions/29205858/empty-divs-that-are-set-to-display-none.html
basically, any divs, within the parent div, that are set to display:none need to be gutted