2

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.

2 Answers 2

1

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/

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

Comments

0

Try

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

instead of:

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

1 Comment

the above code is appending text and value one after one.Not for one <option>.

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.