Search code examples
javascripthtmljqueryhaml

jQuery .val() is returning an empty string for input element


I have a few input elements in a div and I am trying to use jQuery to 1) check the content of the first input, and if it is not blank, then show the next input, and so on. However, the problem I have is no matter what I type into the input box, .val() returns an empty string in the browser console.

HTML:

<div class="col-sm-6">
  <span class="team-member-form" id="team-member-1-form">
    <input class="form-control" type="text"></input>
    <br/>
  <span class="team-member-form" id="team-member-2-form">
    <input class="form-control" type="text"></input>
    <br/>
  <span class="team-member-form" id="team-member-3-form">
    <input class="form-control" type="text"></input>
    <br/>
  <span class="team-member-form" id="team-member-4-form">
    <input class="form-control" type="text"></input>
    <br/>
  <span class="team-member-form" id="team-member-5-form">
    <input class="form-control" type="text"></input>
    <br/>
  
</div>

Javascript:

 $('.team-member-form').on('keyup', function() {
                var teamMemberForm = $(this).attr('id');
                var teamMemberNumber = teamMemberForm.split('-')[2];
                var teamMemberFormValue = $(this).val();
                console.log(teamMemberFormValue);

So no matter what I type into the input, the console.log is just an empty string. Any ideas why?


Solution

  • We need to attach the keyup event to the input element. Currently it is attached to the span.

    I have included a code snippet that is binding the keyup to the .form-control instead.

    $('.team-member-form .form-control').on('keyup', function() {
      var teamMemberFormValue = $(this).val();
      console.log(teamMemberFormValue);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="col-sm-6">
      <span class="team-member-form" id="team-member-1-form">
        <input class="form-control" type="text"></input>
        <br/>
      <span class="team-member-form" id="team-member-2-form">
        <input class="form-control" type="text"></input>
        <br/>
      <span class="team-member-form" id="team-member-3-form">
        <input class="form-control" type="text"></input>
        <br/>
      <span class="team-member-form" id="team-member-4-form">
        <input class="form-control" type="text"></input>
        <br/>
      <span class="team-member-form" id="team-member-5-form">
        <input class="form-control" type="text"></input>
        <br/>
      
    </div>