Manish Kumar
Manish Kumar

Reputation: 10502

Html SELECT : send both value and text on submit

I have a select

<select name="country" multiple>
    <option value="IN">India</option>
    <option value="US">United States</option>
</select>

While submitting form If both country is selected, default behaviour is, it will be send as:

country=IN,country=US

but i want to send both value and text i.e IN and INDIA both. How it can be done

Upvotes: 3

Views: 4142

Answers (3)

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

I think you should give this a try:

$("#btnSub").on('click',function(){ // Submit button click
  $(".select option:selected").each(function(i, option){
    console.log($(this).val() + "," + $(this).text());
  });
    return false;
});

HTML

<select class="select" name="country" multiple="multiple"> </select>

Fiddle Demo

Upvotes: 1

Yabada
Yabada

Reputation: 1758

You could build your request data yourself with jquery. Something like : (Not tested, might need a few corrections but here's the idea)

//POST request
$("#form").submit(function(){
    var countryVal = $("[name=country]").val();
    var countryLbl = $("[name=country]").find("option:selected").text();
    $.ajax({
         data:{countryVal:countryVal, countryLbl: countryLbl},
         url: yourUrl,
         method:'post'
    });
    return false;
});

// GET request
$("#form").submit(function(){
    var countryVal = $("[name=country]").val();
    var countryLbl = $("[name=country]").find("option:selected").text();
    $.ajax({
         url: 'yourUrl?countryVal='+countryVal+'&countryLbl='+countryLbl'
    });
    return false;
});

This work if you're ok with ajax request. If you're not, set hidden input in your form and set the value before submit :

$("#form").submit(function(){
    $("[name=countryVal"]).val($("[name=country]").val());
    $("[name=countryLbl]").val($("[name=country]").find("option:selected").text());
});

Upvotes: 0

Tim
Tim

Reputation: 222

Posting the form will only send the "value" of the option to your backend, so if you also need the text, you could combine them in value like

<option value="IN,India">India<option>

and then split the value by the separator in your backend.

Upvotes: 3

Related Questions