chadb768
chadb768

Reputation: 473

How come my input box's value isn't being returned?

Using twitter bootstrap, I have created a button with an input box beside it. I'm trying to then access that value in my view using jQuery but for some reason I can't get anything back besides "undefined". Here's my code:

jQuery:

var browserInput = $("#browserInput").val();
console.log(browserInput);

Html:

<div class="col-lg-4">
    <div class="input-group">
        <span class="input-group-btn">
            <button class="btn btn-primary" type="button" id="addBrowser">
            <span class="glyphicon glyphicon-plus"></span>
            Add
            </button>
        </span>
        <input id="browserInput" type="text" class="form-control" style="display: none;" >
    </div>
</div>

Upvotes: 0

Views: 82

Answers (2)

Tim Lewis
Tim Lewis

Reputation: 29258

I'm going to undelete my answer because apparently it helped the poster solve his issue...

<input id="browserInput" type="text" value="" class="form-control" style="display: none;" />

Seems that having the value="" in the <input> tag made a difference for him.

I wonder if he meant "" instead of undefined.

Upvotes: 0

baao
baao

Reputation: 73221

If this is your actual code layout, you won't get a value because the DOM isn't loaded at the time you are requesting the value.

You should try to wrap your function in document ready

$(document).ready(function() {
  var browserInput = $("#browserInput").val();
  console.log(browserInput);
});

If you want to have the value on keyup or interaction with the input box, you can also do it like

$(document).ready(function() {
 $('#browserInput').on('keyup',function() {
  var browserInput = $("#browserInput").val();
  console.log(browserInput);
});
});

Upvotes: 2

Related Questions