Search code examples
javascripthtmlnodes

Script not altering text in <span>


I have this script that is collecting the names of places via API from postal codes. The postal codes are inserted to a field, and the corresponding place shows up in a <span>. It's working perfectly fine on several of my web sites, but on this one page (Wordpress, Kinetika theme) it won't work.

The site is using Contact form 7, but it doesn't seem to be related to that (works on other sites with CF7).

I'm clueless to what's causing this problem with this particular theme. Any suggestions?

Tried changing [text....] to <input type="text" id="poststed">. No change.

As you can se here, it runs just fine: https://js.do/code/275407

[text* postnummer id:postnummer class:postnummer]
<span id="poststed" style="font-weight: 700; color: #00ba00">POSTSTED</span>

<script>
    function validatePostalcode(postnummer) {
        if (postnummer.length < 4) {
            return;
        } else {
            var conn = new XMLHttpRequest();
            conn.onreadystatechange = function () {
                if (conn.readyState === XMLHttpRequest.DONE) {
                    var data = JSON.parse(conn.responseText);
                    document.getElementById('poststed').textContent = data.result;
                }
            };
            var url = 'https://fraktguide.bring.no/fraktguide/api/postalCode.json?pnr=' + postnummer + '&callback=?'; conn.open('GET', url, true); conn.send();
        }
    }
    var ele = document.getElementById('postnummer');
    ele.addEventListener('keyup', function (evt) {
        validatePostalcode(ele.value);
    });
</script>

Solution

  • Solved!

    I changed

    if (conn.readyState === XMLHttpRequest.DONE) {
    

    to

    if (conn.readyState === 4) {
    

    And now it works! I'm not sure why this is not an issue with other WP themes, but at least this solved the problem for me.