0

I am using jquery, and javascript. I am trying to make a tip calculator using jquery, showing one page at a time. I am up to the page where it asks the user how many people users need to input the number in their party.

$(document).ready(function(){
  $(".begin").click(function(){
    $(".container").html("
      <h1 class = 'jumbotron'>How Many People Ate?</h1>
        <select class='form-control' id= 'foo'>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
       </select>");
    $(".container").append("
      <button class = 'btn btn-info next center-block'>
        Next
      </button>")
  });

  $(".next").click(function(){
    console.log($( "select#foo" ).val());});
  })
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – ibrahim mahrir Feb 13 '17 at 04:10

2 Answers2

0

Since your buttons are dynamically created, you'll have to use event delegation like this:

$(".container").on("click", ".next", function(){
    console.log($( "select#foo" ).val());});
});

Read more here & here!

Community
  • 1
  • 1
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

Firstly, you missed some semicolons there (;)

My answer: You must bind the click event to .container, not the button .next itself to be work :)

change the last script to be like this:

$(".container").on('click','.next',function() {
    console.log($( "select#foo" ).val());
});

so the full script will be like this:

$(document).ready(function(){
    $(".begin").on('click',function(){
        $(".container").html("
           <h1 class = 'jumbotron'>How Many People Ate?</h1>
           <select class='form-control' id= 'foo'>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
           </select>");
        $(".container").append("
            <button class = 'btn btn-info next center-block'>Next</button>
        ");
    });
    $(".container").on('click','.next',function() {
        console.log($( "select#foo" ).val());
    });
});
Taufik Nur Rahmanda
  • 1,862
  • 2
  • 20
  • 36