Adding variable name instead of value of variable to select list

I'm trying to add new options to the select tag, but my code is adding the variable name addedFont instead of the actual number (i.e. 20 pixels)

main.js

$("#add-font-size").click(function(){
    var addedFont = $("#fontSizeInput").val();
    $("#font-select").append("<option value = addedFont> addedFont pixels </option>");
});

index.html

<select class="custom-select mb-2 mr-sm-2 mb-sm-0" id="font-select">
    <option value="16" selected>16 pixels</option>
    <option value="17">17 pixels</option>
    <option value="18">18 pixels</option>
    <option value="19">19 pixels</option>
    <option value="20">20 pixels</option>
</select>

Selector's options after adding font size 21:

enter image description here

Answers 1

  • You need to use string concatenation.

    $("#font-select").append('<option value="'+addedFont+'">' + addedFont + 'pixels </option>');
    

    However, I would recommend you to create element using jQuery

    $("#font-select").append($('<option>', {value : addedFont, text:addedFont + " pixels"});
    

Related Articles