Yogesh kumar Gupta
Yogesh kumar Gupta

Reputation: 25

XML Attribute to HTML select value using jquery

I am new to jquery.I have an XML file contaning names of countries,states and cities. I want to fill three HTML of country,state and city by using jquery.I have done successfully to transform name of country to a html .But my Problem is i am unable to transform the xml attribute to value.

My Xml file is as follows:

<Locations>
  <Countries>
    <CName index='1'>Afghanistan</CName>
    <CName index='2'>Algeria</CName>
    <CName index='36'>India</CName>
  </Countries>
  <States>
    <SName cindex='36' sindex='1' stype='st'>Andhra Pradesh</SName>
    <SName cindex='36' sindex='2' stype='st'>Arunachal Pradesh</SName>
    <SName cindex='36' sindex='3' stype='st'>Assam</SName>
  </States>
  <Cities>
    <cindex>36</cindex>
    <cityname sindex='1' ctype='ct'>Anantpur</cityname>
    <cityname sindex='1' ctype='ct'>Guntakal</cityname>
    <cityname sindex='1' ctype='ct'>Guntur</cityname>
    <cityname sindex='1' ctype='mct'>Hydrabad/Secundrabad</cityname>
  </Cities>
</Locations>

My HTML is as follows:

<select id="CounList" class="drsel01">// For Country
 </select>

<select id="StateList"></select> //For State

//For City

My JQuery Code is as follows:

<script type="text/javascript">
 $(document).ready(function() {
     var spl_data;      

     // Loading Country
     $.get('Locations.xml', function(data) {
         spl_data = data;
         var that = $('#CounList');
         $('CName', spl_data).each(function() {
             $('<option>').text($(this).text()).appendTo(that); //
             $('<option>').value($(this).attr('index')).appendTo(that);

         });
     }, 'xml');
 }); 

 I want to country name to be fill in <option> text and value of index attribute to be filled as <option> value.So that when i choose a country then related name of states or cities which belongs to country will be filled.

I have successfully filled text but not value.

Thanks in advance.

Upvotes: 2

Views: 1605

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69915

There is no such method called value(). You should use val() method if you want to set the value of option element. Even after using val() your code will create 2 option elements and append them to CountList.

Try this instead

$('CName', spl_data).each(function() {
   $('<option />', { 
       text: $(this).text(),
       value: $(this).attr('index')
   }).appendTo(that);
});

Working demo - http://jsfiddle.net/qQ2Xw/

Upvotes: 1

Vimalnath
Vimalnath

Reputation: 6463

Try

$('<option>').val($(this).attr('index')).appendTo(that);

instead of:

$('<option>').value($(this).attr('index')).appendTo(that);

Upvotes: 0

Related Questions