Patrick R
Patrick R

Reputation: 1979

Show XML items from dropdown

I've been working on a small tool for my work, but can't really get the last thing to work.

You can see the code etc. here: http://jsfiddle.net/wb157kbx/5/

What I'm trying to do is, i want the country from the XML into the dropdown, as it already are. When you select a country, it shows the mobile, phone and code data from the XML in the #tal tag. I'm making it all with JQuery.

What am i doing wrong, since i don't get the selected price, phone, code etc. ?

DEMO

Upvotes: 0

Views: 45

Answers (1)

user733421
user733421

Reputation: 497

$('#dropdown').change(function () {     

    $selected = $('#dropdown').find(":selected");
    var id = $selected.prop("id");  
        $(xml).find('item[id="' + id + '"]').each(function ({

            var code = $(this).find('code').text();
            var fastnet = $(this).find('phone').text();
            var mobil = $(this).find('mobile').text();

        $("#pris").text("Mobil: " + mobil + " Fastnet: " + fastnet + " Landkode: " + code);

});

The problem is that you add a value to the global scoped id too soon. This way your id will allways be the last id on the xml.

You need to address the selected option id

var id = $selected.prop("id");  

what I would do is:

success: function (xml) {

            // Parse the xml file and get data
            var xmlDoc = $.parseXML(xml),                
                $xml = $(xmlDoc),
                options = "";


            $(xml).find('item').each(function () {
                id = $(this).attr('id');
                land = $(this).find('country').text();
                code = $(this).find('code').text();
                fastnet = $(this).find('phone').text();
                mobil = $(this).find('mobile').text();

                options += "<option data-id='"+id +"' data-land='"+land +"' data-code='"+code +"' data-fastnet='"+fastnet +"' data-mobil='"+mobil+"' >" + land + "</option>";

            });
          $("#dropdown").html(options)

        }

And then on change I would do this:

 $('#dropdown').change(function () {       
    $selected = $('#dropdown').find(":selected");
    $("#pris").text("Mobil: " +$selected.data("mobil")+
                    " Fastnet: " +$selected.data("fastnet") + 
                    " Landkode: " + $selected.data("code"));

 });

Upvotes: 1

Related Questions