Felipe S. Bueno Felipe S. Bueno - 4 months ago 7
PHP Question

Setting value of input from a jQuery script

I need to get the

$_POST
value of an input that have the value from a jQuery script, but for some reason when I try to
var_dump
the entire
$_POST
, the field
amount
(which is the one that have the value from the script) output nothing at all.

Here's some code to your undestanding:

jQuery code:

$(document).ready(function(){
update();
});

$('input[type=checkbox]').click(function(){
update();
})

function update(){
var amount2 = 0;
var options = 0;
$('#instNum2 option').remove();
$('.check_list').each(function () {
if (this.checked) {
amount2 += Number($(this).attr("val"));
options ++;
}
});

$("#amount2").val("R$"+amount2.toFixed(2));


And here is the html:

<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<br><h4 style="margin-top: -5px;">Total Selecionado:</h4>
<input type="text" class="form-control" id="amount2" name="amount">
<p class="help-block text-danger"></p>
</div>
</div>


The function is simple, it sum the value of each column when selected and then it prints the total value on the input.

The problem is when I try to catch the total value of the input with generic
$_POST['amount']
after submiting the form, it prints an empty field...

Any thoughts?

Answer

I think there were two errors.

1st: The line which updates the #amount2 was outside the update() function.
2nd: this line fails amount2 += Number($(this).val());
You want the inputted value (or modified value) of this input... Not the value attribute's value.

Difference is: $(this).attr("val") would return something defined in the attribute like so :
<input type="text" class="form-control" id="amount2" name="amount" value="default value">

And $("#amount2").val() will return the actual value.

Thy this:

function update(){
    var amount2 = 0;
    var options = 0;
    $('#instNum2 option').remove();
    $('.check_list').each(function () {
        if (this.checked) {
            amount2 += Number($(this).val());
            options ++;
        }
        $("#amount2").val("R$"+amount2.toFixed(2));
        console.log($("#amount2").val());
});

I added a console.log for you to check if the value you want is present when executing the update() function.

EDIT based on comment

Try this in your PHP:

if (isset($_POST['amount'])){
    echo "$_POST['amount'] is set.<br>";
    echo "It's value is: x" . $_POST['amount'] . "x";   // if it is empty, you'll get "xx" echoed.
}else{
    echo "$_POST['amount'] is NOT set.<br>";
}
Comments