0

I want to make a input field where I can search for friends in a list, these friends I retrieve from a xml file and I generate them using javascript

The code I generate this with:

friendListInDiv = document.createElement("p");
                    var link = document.createElement("a");
                    link.onclick = function() {
                        openChat(friendsXML[i].textContent)
                    };
                    var friendText = document
                            .createTextNode(friendsXML[i].textContent + ":"
                                    + statusXML[i].textContent);
                    link.appendChild(friendText);
                    friendListInDiv.appendChild(link);
                    friendDiv.appendChild(friendListInDiv);

Now the problem I'm facing I have demonstrated in a jsfiddle: https://jsfiddle.net/x897pv9o/

As you can see if you type in "j" in the top input bar it hides all friends but type "j" in the bottom one it will still display "Joske"

This is because these tags

<div id="friendlist"><p><a>
Joske:
Offline</a></p><p><a>
Tom:
Offline</a></p><p><a>
Dirk:
Offline</a></p></div>

are not being formatted correctly, how can I make them format correctly?

2
  • 2
    You can use trim() to trim whitespaces before appending the textnode. Commented May 11, 2015 at 16:20
  • I slightly modified your source. Use <a><p> Joske: Offline</p></a> instead of <p><a> because I see it adds a blank line for your source list (inspect element in web browser). Maybe is about your style def. Commented May 11, 2015 at 16:23

1 Answer 1

1

As Shaunak D mentioned in a comment, you can use .trim() to remove preceding and trailing whitespace, including new lines, from text. You can either use this on your text content when creating the node, or use it in your search function to exclude new lines.

In document.createTextNode:

var friendText = document.createTextNode(
    friendsXML[i].textContent.trim() + ":" + statusXML[i].textContent);

In $('#searchinfriend').keyup:

$('#searchinfriend').keyup(function () {
    var valThis = $(this).val().toLowerCase();
    $('#friendlist p a').each(function () {
        var text = $(this).text().trim().toLowerCase();
        (text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.