phicon
phicon

Reputation: 3617

Javascript getElementsByName() for changing names

I have a automatically rendered HTML form which uses a index for the input fields.

for quantity:

<input id="id_orderline_set-0-orderline_quantity" name="orderline_set-0-orderline_quantity" onkeyup="orderlineTotal()" type="number" value="120"> 

for product price;

<input id="id_orderline_set-0-orderline_product_price" name="orderline_set-0-orderline_product_price" onkeyup="orderlineTotal()" type="number" value="22">

for total line price;

<input id="id_orderline_set-0-orderline_total_price" name="orderline_set-0-orderline_total_price" tag="orderline_total_price" type="number" value="2640">

For the following lines the index of the id and name are increased, only quantity example shown;

<input id="id_orderline_set-1-orderline_quantity" name="orderline_set-1-orderline_quantity" onkeyup="orderlineTotal()"  type="number" value="55">

I would like to use the following JavaScript to calculate the total line price;

function orderlineTotal()
{
    var orderlineTotalPrice = 0;   
    var theForm = document.forms["orderform"];

    var orderlineQuantityField = theForm.getElementsByName["orderline_quantity"];
    var orderlineProductPriceField = theForm.getElementsByName["orderline_product_price"];
    var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];

    for (var i = 0; i < orderlineQuantityField.length; i ++) {
        orderlineTotalPrice = orderlineQuantityField[i].value * orderlineProductPriceField[i].value;
        orderlineTotalPriceField[i].value = orderlineTotalPrice;
    }
}

Offcourse this wont work because the name of the elements do not match. Can i lookup the name of the element by using a partial name? If not, how should i loop through the input boxes to calculate the line total?

Upvotes: 0

Views: 702

Answers (2)

Klapsa2503
Klapsa2503

Reputation: 919

Maybe you could use static names. Set the equal input names for inputs of the same type and then use this function:

var elements = document.getElementsByName('name');
for (var i=0; i<elements.length; i++) {
    doSomething(elements[i]);
}

where name matches name of input.

Example

Instead of:

name="orderline_set-0-orderline_total_price"

use:

name="orderline_total_price"

and then:

var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];

and so on...

Upvotes: 0

artm
artm

Reputation: 8584

You tagged jQuery so if you want to use jQuery you can use ends with selector:

$("input[name$='orderline_quantity']")

ends with

there's also

starts with

$("input[name^='id_orderline_set-0']")

and contains

$("input[name*='orderline_']")

Upvotes: 1

Related Questions