user1009453 user1009453 - 3 months ago 10
Javascript Question

Keep values in radio buttons after submit

I'm building a form with radio buttons.

<form id="land" name="input" method="POST" action="test.php">
<input type="radio" name="Albania" value="Albania" class="test">
<input type="radio" name="Sweden" value="Sweden" class="test">
<input type="radio" name="Norway" value="Norway" class="test">
<input type="hidden" name="hidden" value="action">
<input type="submit" value="Submit">

There are over 150 countries to choose from. And when you choose a country, the application I'm building shows a line chart representing the data for the country in question. I've built a script so that I can have multiple choices. Basically it builds an array of the selected values, and then builds a SQL query from the imploded array.

This works fine when I use the submit button to send the data. But I wanted the chart to update directly when the the user checked a radio button. I added


to the input field and this works fine.

My problem is that I can't choose two values now, eg, Norway and Sweden to compare the two, because once I check one radio button the page loads and the value disappears and the radio button is unchecked.

So. How do I send the query without the value disappearing?

Any help much appreciated!

<input <?php if (!(strcmp($_POST['Albania'],"Albania"))) {echo 'checked="checked"';} ?> type="radio" name="Albania" value="Albania" class="test">
<input <?php if (!(strcmp($_POST['Sweden'],"Sweden"))) {echo 'checked="checked"';} ?> type="radio" name="Sweden" value="Sweden" class="test">
<input <?php if (!(strcmp($_POST['Norway'],"Norway"))) {echo 'checked="checked"';} ?> type="radio" name="Norway" value="Norway" class="test">

But why don't you use checkboxes instead; maybe the user what to uncheck one of the radio inputs.

I recommend that you change the names of the radio buttons to: name="country[countryName]" it's easier to retrieve the selected countries by doing implode()

<input <?php if (in_array("Albania", $_POST['country'])) {echo 'checked="checked"';} ?> type="radio" name="country[Albania]" value="Albania">
<input <?php if (in_array("Sweden", $_POST['country'])) {echo 'checked="checked"';} ?> type="radio" name="country[Sweden]" value="Sweden">
<input <?php if (in_array("Norway", $_POST['country'])) {echo 'checked="checked"';} ?> type="radio" name="country[Norway]" value="Norway">

Generate the radio buttons:

<?php while($row = mysql_fetch_array($sth)) { ?> 
<input class="className" type="radio" name="country[<?php echo $row['land']; ?>]" value="<?php echo $row['land'];?>" onClick='this.form.submit()' <?php if (in_array($row['land'], @$_POST['country'])) {echo 'checked="checked"';} ?> /><?php echo $row['land'];?> 
<?php }?>