sanjiv kumar
sanjiv kumar

Reputation: 11

Select option from the drop down list and display in table cell using javascript

I have a drop down list and submit button along with table header called fruits

For example: If I select one of the option from the drop down list and by clicking the submit button. The selected option from the list, should display in table cell.

Could some one help me to resolve the issue that would be grateful.

Here is code:

$(function() {
  $("#btnGet").click(function() {
    var selectedText = $("#ddlFruits").find("option:selected").text();
    var display = document.getElementById("display");
    var newRow = display.insertRow(row);

    var cell1 = newRow.insertCell(0);
    cell1.innerHTML = selectedText;
    row++;

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="ddlFruits">
  <option value="">None</option>
  <option value="1">Apple</option>
  <option value="2">Mango</option>
  <option value="3">Orange</option>
</select>
<input type="button" id="btnGet" value="Submit" />

<table id="display">
  <tr>
    <th>Fruits</th>
  </tr>

Upvotes: 0

Views: 1721

Answers (2)

ubm
ubm

Reputation: 636

I changed the script.Please try this code.

<script type="text/javascript">
$(function () {
    $("#btnGet").click(function () {
        var selectedText = $("#ddlFruits").find("option:selected").text();
        if(selectedText!="None"){
            var display = document.getElementById("display");
             $('#display tr:last').after('<tr><th>'+selectedText+'</th></tr>');
        }



    });
});

Upvotes: 0

Gangadhar Gandi
Gangadhar Gandi

Reputation: 2252

The below code will work,

$(function () {
      $("#btnGet").click(function () {
        var selectedText = $("#ddlFruits").find("option:selected").text();
        var display = document.getElementById("display");
        var newRow = display.insertRow(display.rows.length);
        var cell1 = newRow.insertCell(0);
        cell1.innerHTML = selectedText;
      });
    });

Upvotes: 1

Related Questions