lena lena - 29 days ago 9
jQuery Question

How to display the value of javascript variable inside option tag in select statement using jquery?

I have got the values of two JavaScript variables. I wanted to give inside the option tag in the value attribute. How to give that in jQuery as I wanted to retrieve the value of that option in the select statement?

Now I have currently given it. but it is displaying the variable not the value.

var packagetype = item.package_type;
var package_price = item.package_price;


$("select.selectedpackagetype").append("<option class='firstoption' value='packagetype:package_price'> "+packagetype+" - Rs. "+package_price+"</option>");

Answer

Now i have current given it. but it is displaying the variable not the value.

Well, of course it is. You've put the text packagetype:package_price literally inside the string. Elsewhere in that same line you use string concatenation, which is also what you might use for value:

$("select.selectedpackagetype").append("<option class='firstoption' value='" + packagetype + ":" + package_price + "'> "+packagetype+" - Rs. "+package_price+"</option>");
// ------------------------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

But I wouldn't use string concatenation to build HTML for the option; I'd build the option object and then append it:

var packagetype = item.package_type;
var package_price = item.package_price;

$("<option>")
    .val(packagetype + ":" + package_price)
    .addClass("firstoption")
    .text(packagetype + " - Rs. " + package_price)
    .appendTo("select.selectedpackagetype");

Example:

var packagetype = "TheType";
var package_price = 42;
    
$("<option>")
    .val(packagetype + ":" + package_price)
    .addClass("firstoption")
    .text(packagetype + " - Rs. " + package_price)
    .appendTo("select.selectedpackagetype");
<select class="selectedpackagetype"></select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>