在同一页面中显示HTML选择值

在同一页面中显示HTML选择值

问题描述:

Basically I just want to have a value set by a dropdown box and then echo the value next to it, ideally without a submit button and in the same page.

<select name="price" action="post" id="mySelect">
<option value="100">Option 1</option>
<option value="120">Option 2</option>
<option value="115">Option 3</option>
<option value="135">Option 4</option>
<option value="80" >Option 5</option>
</select>

echo "£ $price"

I've been looking for a while for a way to do this, most solutions echo the value into the select. I'm sure there's a much better way to do this so any links would be appreciated!

you have to use javascript for this without submitting.

<select name="price" action="post" id="mySelect" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
<option value="100">Option 1</option>
<option value="120">Option 2</option>
<option value="115">Option 3</option>
<option value="135">Option 4</option>
<option value="80" >Option 5</option>
</select>
<p>£ <span id="selectedValue"></span></p>

Using jQuery:

$(document).on('change', '#mySelect', function(){
    $('#DisplayValueSomewhereID').html($('#mySelect').val());
});

The somewhere on the page:

<div>&pound;<span id='DisplayValueSomewhereID'>0.00</span></div>

<html>
  <head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>

    <select name="price" action="post" id="mySelect" onchange="return show_price(this.value);">
    <option value="100">Option 1</option>
    <option value="120">Option 2</option>
      <option value="115">Option 3</option>
    <option value="135">Option 4</option>
    <option value="80" >Option 5</option>
    </select>

    <div>&pound; <span id="price_sp"><span></div>
<script>
    function show_price(price)
    {
        document.getElementById('price_sp').innerHTML = price;
    }
 </script>
</body>
</html>

  1. Add a form
  2. Add a submit button to the form (you have to have some way to tell the browser to send the form data to the server)
  3. Read the value from $_POST[] (if it exists)
  4. Protect yourself from XSS attacks

such:

<form method="post">
<select name="price" id="mySelect">
<option value="100">Option 1</option>
<option value="120">Option 2</option>
<option value="115">Option 3</option>
<option value="135">Option 4</option>
<option value="80" >Option 5</option>
</select>
<input type="submit">
</form>

<?php
    if (isset($_POST['price'])) {
        echo "$";
        echo htmlspecialchars($_POST['price']);
    }