Hello community, i try to use a js function within an webform to calculate prices for some colours. <script type="text/javascript"> <!-- function form_ral451() { var wert1 = Number(document.getElementById('wert1').value); var wert2 = Number(document.getElementById('wert2').value); var resultField1 = document.getElementById('result1'); var result1 = wert2*wert1; resultField1.value = result1; } --> </script> Code (JavaScript): and the html code to call the function <label for="wert1">How many litre colour RAL 451?</label><input type="text" name="wert1" id="wert1" onkeyup="form_ral451();"><br> <label for="wert2">Euro / litre</label><input type="text" name="wert2" id="wert2" value="20" onkeyup="form_ral451();"><br> <br> <label for="result1">Price:</label><input type="text" name="result1" id="result1" readonly><br> HTML: Now there are some more colours to calculate (RAL 452, RAL 460 and so on), always in the same way. Is it possible to use this function for all the colours or do i have to write this function for each colour, only with another name ? Thx a lot for a reply / example
Hi, you should definitely be able to use the function as often as you like - that's good programming practice. The trick is to make the input and output fields easily identifiable. I'll give an example but bear with me if I haven't got it quite right, should be enough for you to get started with though. <label for="paint451">How many litre colour RAL 451?</label><input type="text" name="paint[451]" id="paint451"><br> <label for="price451">Euro / litre</label><input type="text" name="price[451]" id="price451" value="20 "><br> <label for="result451">Price:</label><input type="text " name="result[451]" id="result451" readonly><br> <label for="paint452">How many litre colour RAL 452?</label><input type="text" name="paint[452]" id="paint452"><br> <label for="price452">Euro / litre</label><input type="text" name="price[451]" id="price452" value="20" readonly><br> <label for="result452">Price:</label><input type="text " name="result[452]" id="result452" readonly><br> <script type="text/javascript"> function calculatePrice() { var paintId = this.id.substring(5); var price = document.getElementById('price' + paintId); var resultField = document.getElementById('result' + paintId); var result = this.value * price.value resultField.value = result; } document.getElementById("paint451").addEventListener("keyup", calculatePrice); document.getElementById("paint452").addEventListener("keyup", calculatePrice); </script> HTML: I figure that you're looping through a database result set to create the rows in the form so you might as well use them to your advantage.