3

I am trying to concatenate the value of the input with the String variable. For instance: (lets say that the input with an id 'input1' has the value of 'tttttt')

var test = 'blabla' + $('#input1').val() + 'blabla';

So the expected result (at least for me) should be 'blablattttttblabla'. The problem is that it does not insert the value of that input in the middle so the result is 'blablablabla'. Does someone has an idea what I am doing wrong?

7
  • It seems that .val() returns an empty string. Are you sure that field is there and it's the only one with that id? Commented Mar 28, 2013 at 15:00
  • 1
    Try executing $('#input1').val() in the console and see what the result is. Commented Mar 28, 2013 at 15:00
  • 1
    whats the value of $('#input1').val() by itself? My guess is that your selector is wrong. Commented Mar 28, 2013 at 15:00
  • that looks like it should be working. are you getting an error? most likely if your not then you have a scope issue and your trying to concat before input1 has a value. can you show the scope in which this is being called? Commented Mar 28, 2013 at 15:01
  • does $('#input1').length return 1 Commented Mar 28, 2013 at 15:03

2 Answers 2

4

Try

<input type="text" name="text" id="input1" value="ttttttt"/>

JS

<script>
$(document).ready(function(){
    var test = 'blabla' + $('#input1').val() + 'blabla';
    alert(test);
});
</script>
Sign up to request clarification or add additional context in comments.

Comments

2

What it seems to me is that either you are missing a jQuery library at the top or this script is not called in the doc ready handler:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
   $(function () {
      var test = 'blabla' + $('#input1').val() + 'blabla';
      alert(test);
   });
</script>

Demo Fiddle

Be sure that your #input1 has a value contained in.

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.