Search code examples
jqueryvariablesradio-buttonloadloading

Load a variable with jQuery into a div based on radio button choice


Problem:

Loading a variable into a div based on choice of radio button.

HTML code:

//Variable to be loaded into
<div id="choice"></div>

//Available variables
$choice1 = '<div id="choice-1">Choice 1</div>';
$choice2 = '<div id="choice-2">Choice 2</div>';

//Radio buttons
<input type="radio" name="authors" id="authors" value="1">
<input type="radio" name="authors" id="authors" value="2">

jQuery code (so far):

$("input[name='authors']").change(function() 
{    
    $('div[id=choice]').load();   
});

Scenario:

If a user choose first radio button (value=1) then $choice1 should be loaded into . If second radio button is chosen after that, $choice1 should be removed and replaced with $choice2.

Thanks in advance!


Solution

  • I assume you're trying to get those variables from a PHP script. In that case, send a parameter with the load request, like

    $(”#choice”).load('myscript.php?choice=' + choice); // choice is variable in which you should put 1 or 2
    

    And in the PHP:

    if($GET['choice'] == 1) echo $choice1;
    else if($GET['choice'] == 2) echo $choice2;