1

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.

4
  • 1
    So what exactly isn't working? Note that <col2> doesnt' have a value ? Commented Dec 27, 2015 at 11:26
  • @adeneo thanks.I saw that col2 doesn't have value.But i just want its the text (not value) of col1 as a Value for <option > tag and text (not value) of col2 as a Text for <option > tag.thanks Commented Dec 27, 2015 at 11:32
  • 1
    might work better if you use <row> in your find action and the grab value/text from either <col1/col2> Commented Dec 27, 2015 at 11:35
  • Thanks @RST .can you please show me this on the given snippet.thanks Commented Dec 27, 2015 at 11:51

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Mosh Feu the option tag text works. But i want the value from col1 Not from col2 .can you help me on this.thanks
I was updated my answer. See if that's what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.