简体   繁体   中英

Loading a PHP file and set variable based on selection

I need to load the content of a PHP file using jquery based on what is selected by the user in one or more select fields.

I can use...

$("#first-choice").change(function() {
    $("#second-choice").load("getter.php?choice=" + $("#first-choice").val() );
});

...to create the variable 'choice' and when the 'first-choice' field is set by the user.

However, what if I want to use 2 variables based on two drop down selectors, to set the variable 'choice' (based on the selection of #first-choice) and choice2 (based on the selection of #second-choice).

So I would want to load a PHP file something like getter.php?choice=first-choice&choice2=second-choice

here's how i would handle this situation..

don't treat your selects as ids. use a single class for all select options, then bind .change() to all selects using a class-based selector. if you do this, you can iterate over X number of selects, use their ids as the query argument variable and their values as each query value. I created a quick demo for you on jsfiddle. I also posted the code for you below....

Here is my demo on jsfiddle

    <div>
    <select class="php-options" id='first-choice' name='first-choice'>
         <option value='1-0'>choose</option>
        <option value='1-1'>1-1</option>
       <option value='1-2'>1-2</option>
        <option value='1-3'>1-3</option>
        <option value='1-4'>1-4</option>
      <option value='1-5'>1-5</option>
    </select>
</div>
<div>
    <select class="php-options" id='second-choice' name='second-choice'>
        <option value='2-0'>choose</option>
        <option value='2-1'>2-1</option>
       <option value='2-2'>2-2</option>
        <option value='2-3'>2-3</option>
        <option value='2-4'>2-4</option>
      <option value='2-5'>2-5</option>
    </select>
</div>
<div id="request-url"></div>





$(document).ready(function(){
//treat your select options with classes,
//bind change event on each select
$('.php-options').change(function(e){
    var urlValues = [],
        parameterArgs = "";
    //loop selects to build parameters
    $('.php-options').each(function(i,v){
        var optValue = $(this).val(),
            optId=$(this).attr('id'),
            parameter = ""+optId+"="+optValue;
        urlValues.push(parameter);
    });
    //build parameter string
     parameterArgs =urlValues.join("&");

    //output query
    $('#request-url').text('getter.php?'+parameterArgs);        
});

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM