0

I have an HTML < form > with two independent < select >. The < option > available in the second < select > is based on the < option > chosen in the first < select >. This works fine using the suggestion from mcravens and further detailed here.

Although the first < select > value is retained when pressing the < submit > button, the selected value in the second < select > is always reset to "-- select one --" . I would like the second selected value to remain displayed and unchanged until manually changed OR the first < option > is changed (which changes the second options available).

I have been able to capture the value of the second selected value by adding a name to the select: (HTML)

<select name="CSsize" id="size">
   <option value="">Select...</option>
</select>

and then using a $_POST to collect the selected value: (PHP)

if(isset($_POST["CSsize"]) && !empty($_POST["CSsize"])) { 
    $CSsize = $_POST["CSsize"];} else { $CSsize="0";}

This means that I can capture the value of the second < select > once submitted and use it in the remaining code. There is no issue there, my question is purely how to keep the chosen value displayed in the second < select > on the page.

I have tried revising the second < select > with PHP echo, etc., such as:

<option <?php if ($CSsize != "0" ) echo 'selected' ; ?> value=""></option>

and also tried revising the .js with if statements, such as:

if ($("#size").val() !== "Select...") {

Nothing seems to work and the second < select > is stubornly reset each time.

I'd love some assistance in showing me where I am going wrong?! Thanks!

Community
  • 1
  • 1
  • `if ($CSsize != "0" )`, selected option will be applied to all the options isn't it ? Don;t you think it should be applied for single option ? You need to consider value of the option as well... – Rayon Mar 10 '16 at 04:18

2 Answers2

1

I can capture the value of the second < select > once submitted and use it in the remaining code

If I understand this correctly, you can generate the option's selected property using captured results in the following script area

"<option>item1...</option><option <?php echo .... 'selected'; ?> >item1...</option>"...

If .js file manipulation using php is not an option, using data attribute in the select element and retrieving it via .data() can work.

Then calling the $("#type").change() at the end of .ready() will executes the handler and construct the 2nd select box as usual.

 $("#type").change();

See Demo

  • Excellent. With a little modification this works perfectly. In case this helps someone in the future, the final 'full' code is as follows: – sanitycheck Mar 10 '16 at 23:08
0

When you are loading the page and have got the value of second select then just call the following code

var val = $('#type').val();
$("#size").html(options[val]);

Check the fiddle link for you solution

Hope this helps