Manoj Singh
Manoj Singh

Reputation: 7707

Using JQuery for reading XML through javascript

I have a JavaScript function code where I want to alert.

function msgalert(x,y)
{
 tempstr = x.value
if(tempstr.length>y)
 {
  alert(c_AcknowledgementText);
  x.value = tempstr.substring(0,y);
  }
}

Now I have an xml with below format:

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <key name="c_ContactUsHeading">Contact Us</key>
    <key name="c_AcknowledgementText">Comments can not be more than 250 characters.</key>
</root>

I want the JavaScript code so that the message shown in above alert can be read from above xml key name "c_AcknowledgementText".

I am trying with the below code, but unable to solve the problem, can you please have a look

    <script language="javascript" type="text/javascript">
function msgalert(x,y)
{
tempstr = x.value
    if(tempstr.length>y)
     {
            $(document).ready(function(){
                $.ajax({
                    type: "GET",
                    url: "../includes/ResourceData.xml",
                    dataType: "xml",
                    success: function(xml) {                    
                        $(xml).find('key').each(function(){
                            var title = $(this).find('name').text();                        
                            );
                        });                 
                    }
                });
            });
}
}
        </script>

some where I need to modify the above function so that I can use it to give alert value through XML.

Upvotes: 0

Views: 1279

Answers (2)

Paolo Bergantino
Paolo Bergantino

Reputation: 488714

I can't really understand what you're trying to do, but this code is wrong:

var title = $(this).find('name').text();

At that point, this is the current <key> element you are looping through. To get the value of the name attribute of this element, you would need to do this:

var title = $(this).attr('name');

And then to get the contents of this element, you would do:

var title = $(this).text();

In response to your comment, I think you want this:

var title = $(this).find('key[name=c_AcknowledgementText]').text();
alert(title);

Upvotes: 2

googletorp
googletorp

Reputation: 33285

So there are some different ways to go about this problem, you could

$(xml).find([name='key']).each(function(){
    alert($(this).text());                                                
});  

This finds all elements where the name attribute equals 'key', and then it posts an alert with the text of that element.

Upvotes: 1

Related Questions