user5005768Himadree
user5005768Himadree

Reputation: 1439

How to insert xml text & value in html option text & value

I want to insert a option tag with text and value from reading xml tags.

Here I want to insert <option value> Text</option> like this way below:

<option value[from each xml col1]> Text [from each xml col2] </option>

Here is the code:

var xml = ' <row id="1_2"> <col1>46.0</col1>   <col2>Acting Allowance</col2> </row> <row >            <col1>A1</col1> <col2>Allowance for 65 years plus</col2></row>',
    xmlDoc = $.parseXML(xml),
    $xml = $(xmlDoc);


$xml.find('col2').each(function () {
    var option = $(this).text(), //i want to take text from each col2 as option text  
        value = $(this).attr('value'); //i want to take text from each col1 as option value  
    $("#selectID").append("<option value='" + value + "'>" + option + "</option>");
});
<select id="selectID"></select>

Please let me know for further information. Thanks.

Upvotes: 1

Views: 300

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29287

Your XML was invalid. You have to insert any root node (I just was wrapped the xml with <root> node.

var xml = '<root><row id="1_2"><col1>46.0</col1><col2>Acting Allowance</col2></row><row><col1>A1</col1><col2>Allowance for 65 years plus</col2></row></root>',
    xmlDoc = $.parseXML(xml),
    $xml = $(xmlDoc);


$xml.find('row').each(function() {
  var row = $(this),
      option = row.find('col2').text(), //i want to take text from each col2 as option text  
      value = row.find('col1').text(); //i want to take text from each col1 as option value

  $("#selectID").append("<option value='" + value + "'>" + option + "</option>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectID"></select>

Upvotes: 1

Related Questions