-3

Morning!

I'm trying to get an input value populated based on the change in a select box, so the user selects a code and the amount is populated, I need the select box to keep it's value so I can't use the value of that onchange.

I am using a post request in the JS to get this value but can't get it too work and am exhausting options trying to find an answer.

The code is below:

<input id="amount" />
<select id="product" onChange="amountCalc()">
<option value="111">111</option>
<option value="222">222</option>
</select>

<script>
    function amountCalc() {
        var x = document.getElementById("product").value;
        $.post('lib/amount.php', { code: +x+ }, function(result) { 
        document.getElementById("amount").value = result;}
</script>

The PHP page expects the code parameter and returns a value which should populate the amount field.

Any help would be great, javascript noob here :(

srob
  • 167
  • 1
  • 2
  • 10

2 Answers2

3

Your JavaScript had lots of errors in it:

It should be this:

function amountCalc() {
    var x = document.getElementById("product").value;
    $.post('lib/amount.php', { code: x }, function(result) { 
        document.getElementById("amount").value = result;
    });
}

You weren't closing your amountCalc() function, which was the first problem.

The second problem was that you were using +x+, so it was expecting a string or another variable, as + is used for string concatenation in JavaScript. This was stopping your function(result) from working.

Then last of all, you were missing the closing bracket ) from the $.post(.... That needs to go after the function(result){

Albzi
  • 15,431
  • 6
  • 46
  • 63
1

You can do it unobtrusive as you are using jquery then do this way:

$('#product').change(function(e){
    var x = this.value;
    $.post('lib/amount.php', { code: x }, function(result) { 
        $("#amount").val(result);
    });
});
Jai
  • 74,255
  • 12
  • 74
  • 103