-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 :(

1
  • 2
    Do { code: x },, you don't need the +'s. Commented Aug 11, 2015 at 9:15

2 Answers 2

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){

Sign up to request clarification or add additional context in comments.

2 Comments

Legend! Thanks man works perfectly :)
No worries glad I could help :) @simonrob
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);
    });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.