tags:

views:

259

answers:

3

Hi,

I have a drop down in html.

When I change the value of the drop down I want to store the selected value in a php variable

How can i achieve this ?

+1  A: 

Without submitting the form, this can be done using an AJAX call (see libraries like Prototype and MooTools for easy methods) all off the onchange HTML attribute of your select tag.

St. John Johnson
+1  A: 

Hey Anand,

Technically it is impossible. PHP is server side, HTML is client side. When a user calls up a URL the server runs the PHP which gets sent to the HTML, so you can not go backwards.

You can however use ajax to get the value of the select box and use it in some meaningful way. What are you wanting to do with this variable?

Metropolis

EDIT

Using jQuery I would send the value of the select box to an ajax file, and then have the ajax file create the text box if the value is what you want it to be. Here is an example.

$("#selectEle").change(function() {
    $.ajax({
        type: "POST",
        url: "yourajaxpage.ajax.php",
        data: {selectVal: $(this).val()},
        success: function(response) {
            $("#textBoxArea").html(response);
        },
        error: function() { alert("Ajax request failed."); }
    }
});

You will grab the value in your ajax page using $_POST['selectVal']. Test that value there, and create an HTML textbox which gets sent back to the success function.

Metropolis
Okay when I select an option from the select box depending on the value selected I will decide whether to display a text box or notbut the problem is that the code for the text box is in another php file ??
Anand
A: 

yes, as suggested a javascript/ajax implementation would be a good fit here.

I use jQuery but I'm assuming it can be achieved in other libraries.

Anyway .change() in jQuery would work for this. When a user changes the selected index of the drop down it triggers the the .change() function and you would insert more javascript conde inside of this function to make the needed changes.

If you wanted you could find out the selected index or get the value of the selected index and put in logic based around that to load your textbox (also using javascript).

Something like

$('target').change(function() {
  var value = $('target').val(); // gets the selected value
  if(value == "what you want it to be")
  {
    // load data into a div from your php file.
    $('#loading_div').load('ajax/test.html');
  }
});

That should definitely get you started.

mmundiff
Thanks a lot for this detailed codei was thinking it would be very simple but now that all of the answers mention ajax i will start looking into itthanks a lot
Anand