How to make a text box change depending on a dropd

2019-10-04 03:25发布

问题:

I would like to know how to make a text box change according to a drop down menu. So for example ...

<form action="index.php" method="POST">
<p>Product:</p>
<select id = "myPRODUCTS">
<option value = "Apple">Apple</option>
<option value = "Orange">Orange</option>
<option value = "Mango">Mango</option>
</select>
<p>Price:</p><input type="text" name="Price" readonly="readonly" />

So I want the price text box to change if I have selected Apple I want it to be £0.45 or if I select orange I want it to be £0.50 and so on. How would I do this?

Thanks in advance, Marek

回答1:

This code shows how you can accomplish what you seek.
As others have mentioned, it's not exactly the most secure / efficient way to do this, especially if you're dealing with real money, but all you have to do to get this to work is add jquery to your html file with <script src="http://code.jquery.com/jquery-latest.min.js"></script>

$('#myPRODUVTS').on('change', function() {
 fruit = $(this).val();
    if (fruit == 'Apple') {
        $('#Price').val('£0.45');
    }
    if (fruit == 'Orange') {
        $('#Price').val('£0.50');
    }
    if (fruit == 'Mango') {
        $('#Price').val('£0.65');
    }
});

http://jsfiddle.net/LtBh6/ this shows the code in action with your example.



回答2:

You have do create a JS function that run onchange of the select. That function will reload the page and atribute the value of the price to a variable, that you will use to give value to the price field.

Of course that you shuld have all those names and prices in a DB to be easier to select values.

:)

Some update:

DB with data query fot that DB table called

$result_consulta_mes ( in my example )

in samefile.php some Js that will get the value of the select and reload the same file with the variable.

<script>function unid()
{
    var mse=document.getElementById("select_mes");
    var mse2=mse.options[mse.selectedIndex].value;
    document.getElementById("mes_index").value = mse2;
    window.location.href = "samefile.php?rowmes=" + mse2;
}</script>

Then GET the variable value that came from the JS

<?php $varmes = "$_GET[rowmes]"; ?>

And the select with a while:

<input class="hidden" name="mes_index" type="text" id="mes_index" value= "<?php echo $varmes?>"><select data-size="20" id="select_mes" onchange="unid()" >
<?php
    $current_mes = $varmes;
    while($row_me = mysql_fetch_array($result_consulta_mes)){ 
    if ($row_me['mes_id'] == $current_mes){
    echo "<option selected value=" . $row_me['mes_id'] . ">" . $row_me['mes_mes'] . "</option>" ;}
    else {
    echo "<option value=" . $row_me['mes_id'] . ">" . $row_me['mes_mes'] . "</option>" ;}
    }
?></select>