2017-02-11 2 views
2

Я пытаюсь сделать значение input с именем «имя игры» в столбце «Имя игры» таблицы, когда я нажимаю «добавить игру» button , Также удаление button не работает.Добавление ввода текста в таблицу

Вот мой код:

$(function() { 
 
    var $td = '<td>' + '</td>'; 
 

 
    $('input[name=add-game]').click(function() { 
 
    $('tbody').append('<tr>' + $td + $td + $td + '</tr>'); 
 

 
    var $tableRows = $('tbody tr').length 
 
    $('tbody tr').eq($tableRows).children().eq(0).text($('input[name=game-name]').val()) 
 

 
    $('td:nth-child(3)').html('<button>'); 
 
    $('button').text('Delete').addClass('delete btn btn-block btn-sm btn-danger'); 
 
    }); 
 

 
    $('.delete').click(function() { 
 
    $(this).parent().parent().empty(); 
 
    }); 
 
});
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>Exercises</title> 
 
    <link rel="stylesheet" href="style.css"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
    </head> 
 
    <body> 
 
    <div class="container-fluid"> 
 
     <div class="jumbotron"> 
 
     <h2 class="text-center"><b>FAVORITE VIDEO GAMES <small>(all genres) <span class="glyphicon glyphicon-globe"></span></small></b></h2> 
 
     </div> 
 

 
     <div class="text-center row"> 
 
     <div class="col-sm-6 col-md-6"> 
 
      <ul class="list-group"><h4>These are the games that James like the most</h4> 
 
      <li class="list-group-item">...</li> 
 
      <li class="list-group-item">...</li> 
 
      <li class="list-group-item">...</li> 
 
      </ul> 
 
     </div> 
 
     <div class="col-sm-6 col-md-6"> 
 
      <ul class="list-group"><h4>These are the games that <b>YOU</b> like the most</h4> 
 
      <li class="list-group-item">`empty`</li> 
 
      <li class="list-group-item">`empty`</li> 
 
      <li class="list-group-item">`empty`</li> 
 
      </ul> 
 
     </div> 
 
     </div> 
 

 
     <hr> 
 
     <br> 
 

 
     <div class="row"> 
 
     <div class="col-sm-12 col-md-12 col-lg-12"> 
 
      <form class="text-center" action="index.html" method="post"> 
 
      Game: <input type="text" name="game-name" value="" placeholder="Choose the game"> 
 
      Rate: <input type="text" name="game-rate" value="" placeholder="Rate the game"> 
 
      <input class='btn btn-xs btn-success' type="button" name="add-game" value="Add Game"> 
 
      </form> 
 
      <br> 
 
      <div class="container"> 
 
      <table class="table table-bordered table-striped"> 
 
       <thead> 
 
       <th>Name of the game</th> 
 
       <th>Rating</th> 
 
       <th><span class="glyphicon glyphicon-remove"></span></th> 
 
       </thead> 
 
       <tbody> 
 
       <!-- Here will be added the games --> 
 
       </tbody> 
 
      </table> 
 
      </div> <!-- Close CONTAINER --> 
 
     </div> 
 
     </div> <!-- Close ROW --> 
 
    </div> <!-- Close CONTAINER-FLUID --> 
 

 
    </div> 
 
    <script src='script.js'></script> 
 
    </body> 
 
</html>

+0

Не забудьте upvote полезные ответы. –

+0

@ spencer.sm Жаль, что я не смог бы поддержать. Мне нужна репутация 15, но как только я получу ее, я вернусь и вернусь :) –

+0

О да ... Я забыл об этом. –

ответ

1

Вот быстрое решение. Надеюсь это поможет.

$(function() { 
 

 
    $('input[name=add-game]').click(function() { 
 
    
 
    // Lets get the information ready to be added 
 
    var name = '<td>' + $('input[name="game-name"]').val() + '</td>'; 
 
    var rating = '<td>' + $('input[name="game-rate"]').val() + '</td>'; 
 
    var btnDelete = '<td><button class="delete btn btn-block btn-sm btn-danger">Delete</button></td>' 
 
    
 
    // Lets append the information into the game table 
 
    $('tbody[id="game-table"]').append('<tr>' + name + rating + btnDelete + '</td>'); 
 

 
    // Since we've created a delete button, we need to bind 
 
    // an event listener to the button so that we can 
 
    // delete it from the table if the user clicks it 
 
    $('.delete').on('click', function() { 
 
     $(this).parent().parent().empty(); 
 
    }); 
 

 
    }); 
 
    
 
});
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>Exercises</title> 
 
    <link rel="stylesheet" href="style.css"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
    </head> 
 
    <body> 
 
    <div class="container-fluid"> 
 
     <div class="jumbotron"> 
 
     <h2 class="text-center"><b>FAVORITE VIDEO GAMES <small>(all genres) <span class="glyphicon glyphicon-globe"></span></small></b></h2> 
 
     </div> 
 

 
     <div class="text-center row"> 
 
     <div class="col-sm-6 col-md-6"> 
 
      <ul class="list-group"><h4>These are the games that James like the most</h4> 
 
      <li class="list-group-item">...</li> 
 
      <li class="list-group-item">...</li> 
 
      <li class="list-group-item">...</li> 
 
      </ul> 
 
     </div> 
 
     <div class="col-sm-6 col-md-6"> 
 
      <ul class="list-group"><h4>These are the games that <b>YOU</b> like the most</h4> 
 
      <li class="list-group-item">`empty`</li> 
 
      <li class="list-group-item">`empty`</li> 
 
      <li class="list-group-item">`empty`</li> 
 
      </ul> 
 
     </div> 
 
     </div> 
 

 
     <hr> 
 
     <br> 
 

 
     <div class="row"> 
 
     <div class="col-sm-12 col-md-12 col-lg-12"> 
 
      <form class="text-center" action="index.html" method="post"> 
 
      Game: <input type="text" name="game-name" value="" placeholder="Choose the game"> 
 
      Rate: <input type="text" name="game-rate" value="" placeholder="Rate the game"> 
 
      <input class='btn btn-xs btn-success' type="button" name="add-game" value="Add Game"> 
 
      </form> 
 
      <br> 
 
      <div class="container"> 
 
      <table class="table table-bordered table-striped"> 
 
       <thead> 
 
       <th>Name of the game</th> 
 
       <th>Rating</th> 
 
       <th><span class="glyphicon glyphicon-remove"></span></th> 
 
       </thead> 
 
       <tbody id="game-table"> 
 
       <!-- Here will be added the games --> 
 
       </tbody> 
 
      </table> 
 
      </div> <!-- Close CONTAINER --> 
 
     </div> 
 
     </div> <!-- Close ROW --> 
 
    </div> <!-- Close CONTAINER-FLUID --> 
 

 
    </div> 
 
    <script src='script.js'></script> 
 
    </body> 
 
</html>

+0

Большое спасибо за исправление! Теперь я до сих пор не понимаю, почему кнопка '' '' 'не работает. –

+0

@PaulMihali Привет, я добавил исправление для этого как редактирование вышеуказанного кода. – Win

+0

Спасибо. Я все равно исправил это. Я не могу повышать ваш пост прямо сейчас, потому что у меня нет в общей сложности 15 репутации, но я вернусь, как только получу :) –

0

Ваш код в $(function()... это означает, что, когда dogument готовится эти коды будут работать. Вы добавляете кнопки удаления после завершения всех кодов. По-другому ваши кнопки удаления добавляются после следующих кодов:

$('.delete').click(function() { 
    $(this).parent().parent().empty(); 
}); 

Не регистрируется для новых добавленных кнопок .delete.

Для элементов динамического добавления на страницу вам нужно использовать делегат:

$('.delete').on('click', function() { 
    $(this).parent().parent().empty(); 
}); 
+0

По некоторым причинам это не работает. Я поместил эту функцию в '$ ('input [name = add-game]'). Click (function() {}', и теперь он отлично работает. –

+0

Да, я вижу, Но все же это решение кнопок удаления чтобы начать работать. –

+0

Это был я, который впервые упомянул, чтобы использовать делегата. Но вы говорите мне * это не работает * и к тому же коду, который написан после этого, вы сказали * Спасибо *? –

Смежные вопросы