0

The following code appends text goes here to an input value

$('#someid').val($('#someid').val() + 'text goes here');

I'm trying to use variable like below but It isn't working

var someText= text goes here;
$('#someid').val($('#someid').val() + 'someText');

How can I properly append variable using val() ?

2
  • element which holding id someid is an text box? Commented Apr 5, 2015 at 10:10
  • if it is normal html element you have to use append() Commented Apr 5, 2015 at 10:10

4 Answers 4

3

Take away the quotes so you're accessing the variable and not the string literal.

var someText = 'foo bar';
$('#someid').val($('#someid').val() + someText);
Sign up to request clarification or add additional context in comments.

Comments

3

You don't use string delimiters around a variable:

$('#someid').val($('#someid').val() + someText);

Comments

2

assign your variable like a string; below

var someText= "text goes here";
$('#someid').val($('#someid').val() + someText);

2 Comments

you still have the 'someText' variable in quotes
Never a problem, i'm glad to help it was just a simple typo/mistake anyways. Just want to make sure that the answer is correct, because it's important that users get good answers.
2

jsFiddle

Description

In my jQuery you'll see that I used .html this can easily be switched to .val if needed. I used .html only for demo's sake, the main part to learn is that a variable is used by name only.

HTML

<p id='someid'>more stuff</p>

JS

# someText is a string variable by putting quotes around the text
var someText=' text goes here';
# someText is a variable and thus is just appended without quotes
$('#someid').html($('#someid').html() + someText);

Comments

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.