Search code examples
javascriptregexdomprototypejs

element selection with prototype js


I'm having a some problems with a page where I have an input to take product EAN code and compare that to a table listing of products and update the input box with id ean_xxxx to oldValue+1. My current code looks like this:

function updateProductQty(ean) {
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if(inputs[i].id == "ean_" + ean)
        {
            inputs[i].value = Number(inputs[i].value) + 1;
        }
    }
}

That I call with this code on the input for EAN-code onchange="updateProductQty(this.value);"

Now the problem is that the input box with ID ean_xxxxx is located inside a table row, and I also need to compare to a value in a previous TD-tag. The value I'm looking for is surrounded by HTML like this:

<td>
    <h5 class="title">....</h5>
    <div><strong>...</strong> A252502</div>
    <dl class="item-options">
        <dt>...</dt>
        <dd>..</dd>
    </dl>
</td>
.... more <td>-tags
<td> ... <input id="ean_xxxx" .... /> ... </td>

As you can see, when I locate the input tag, I never know which row in the table I'm at, and the value I want to add a check for is "A252502".

The site uses Prototype as js framework, which I have no experience in what so ever, so I mostly use basic JS where Google fails me for Prototype solutions.

If only I could get the TD contents, I could strip the -tag and any spaces to get the value - but how can search for it? I can't even step back in the DOM tree, because I either get the EAN code or this internal article ID, not both. So no inputs[i] to start out from. Any help is highly appreciated, no matter if it's in Prototype syntax or basic JS.


Solution

  • I managed to solve it. Here's how:

    function updateProductQty(ean) {
        var input = $("ean_" + ean);
        if (input) {
            input.value = Number(input.value) + 1;
        } else {
            var trs = $$('.order-tables tbody tr');
            for (var i = 0; i < trs.size(); i++) {
                if (trs[i].down('div')) {
                    if (trs[i].down('div').innerHTML.split(" ")[1] == ean) {
                        trs[i].down('td').next(4).down('input').value = Number(trs[i].down('td').next(4).down('input').value) + 1;
                    }
                }
            }
        }
    }