0

I am trying to add the values from an input field with the values of a variable inside a jquery. When doing so I get [object Object] displaying as the result. My goal is to get the value from the input field so I can then added to a variable and ultimately display on result on another textbox with id called person. The texbox I am trying to get the value from is count. How can I achieve this?

$.ajax({
    type: 'POST',
    url: 'person.php',
    data: $(this).serialize(),
    dataType: 'json',
    success: function (data) {
    var num = $('#count').val(data);
    $('#person').val(num+ newUniqueAI);
    }
});
4
  • What is data? Why are you passing it to .val if you want to retrieve the value? Please read the jQuery documentation: api.jquery.com/val. It contains information about how .val should be called. Commented Dec 4, 2013 at 8:40
  • 1
    You are setting the value of data to count, not getting Commented Dec 4, 2013 at 8:41
  • @FelixKling Sorry, I added the whole example. Commented Dec 4, 2013 at 8:41
  • So, do you want to set the value of #count and also use the new value for #person? What is the value of data? What is newUniqueAI and its value? Commented Dec 4, 2013 at 8:43

2 Answers 2

3

You are using:

$('#count').val(data);

This sets the value of #count to the value of data and returns a jQuery object. You want to get the value of #count. Therefore you should use:

$('#count').val();

If you do not specify a parameter the val function returns the value. More information about val() could be read here: http://api.jquery.com/val/

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

Comments

1
$('#count').val(data);// first set the value     

var num = $('#count').val(); //get by val()
$('#person').val(parseInt(num)+ parseInt(newUniqueAI)); // set by val(something)

reference .val()

3 Comments

+1 Great but now (num+ newUniqueAI) will not add for example if num=5 and newUniqueAI =3 I get result 53. How come?
@Code_Ed_Student: One of the values (or both) is a string. Convert strings to numbers first, e.g. with the unary + operator: +num.
If you use parseInt, don't forget to pass the radix as second argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.