How to select a value in a selectbox with jQuery?

2019-09-06 06:03发布

问题:

I have a multiselect dropdown box and a input as below:

<select name="offer_type"  multiple="multiple">
    <option value="1">Hot Offer</option>
    <option value="2">Best Offer</option>
    <option value="3">Special / Festival Offer</option>
    <option value="4">Side Offer</option>
    <option value="5">Top Offer</option>
    <option value="6">Megha classified Offers</option>
    <option value="7">Buy One / Get One Offer</option>
    <option value="8">Inagural Offer</option> 
</select>

<input type="text" name="offer" value="" />

Now I want the selected value of offer_type in offer without page refresh. with Jquery.

回答1:

This should do it for you, you don't need any PHP, just jQuery:

$(document).ready(function() {
  $('select[name="offer_type"]').change(function() {
    var selectedValue = $(this).find('option:selected').val();
    $('input[name="offer"]').val(selectedValue);
  });

});

For the multiple select, try something like this:

$(document).ready(function() {
  $('select[name="offer_type"]').click(function() {
    var selectedValsAsString = '';
    $(this).find('option:selected').each(function() {
        selectedValsAsString += $(this).val()+' ';
    });
    $('input[name="offer"]').val(selectedValsAsString);
  });

});

This will display your answers in the text field separated by a space.



回答2:

to get the value of the form fields:

$(function() {

      $('select[name="offer_type"]').change(function() {

      document.write(
      'offer type: ' + $('select[name="offer_type"]').serialize() + '<br />' +     
      'offer name: ' + $('input[name="offer"]').val()
      );

    });
  });