user914425 user914425 - 5 months ago 14
Javascript Question

Input Text Box Returns Undefined in Javascript

Here is my HTML:

<form name='cred' class="panel-body2">
<div class="form-group">
<label for='addjidlbl'> Username (JID):</label>
<input type='text' id='addjid' />
</div>
<input type='button' id='add' value='add' />
</form>


Here is the JavaScript:

$('#add').bind('click', function() {
var jid = $('#addjid').value;
alert(jid);
//var jid=document.getElementById('addjid').value;
var jid2 =$('#addjid').get(0).value;
alert(jid2);
// //$('#addjid').get(0).value;
log('jid=>'+jid);
var data = document.getElementById("addjid").value; //$(".panel.panel-default2#addjid").value;
alert(data);

alert("type=>"+ typeof(jid));
addRoster(jid);
});

function addRoster(jid) {
log('addRoster=>' + jid);
}


What I get are two message boxes with "undefined" and third with "type=>undefined". Why can't I get the input text of the
addjid
text box?

If I change
var jid = $('#addjid').get(0).value;
,
jid
is just blank even when the textbox has value. Why?

Answer

Here you have it working using .val()

add some text to the text box and click on the add button and the alert will popup

$('#add').on('click', function() {
  alert($('#addjid').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='cred' class="panel-body2">
    <div class="form-group">
      <label for='addjidlbl'> Username (JID):</label>
      <input type='text' id='addjid' />
    </div>
  <input type='button' id='add' value='add' />
</form>

Comments