使用jQuery将textbox值添加到表中以进行回发

时间:2015-03-20 15:09:06

标签: jquery asp.net-mvc

试图搜索这个没有成功。我希望能够从文本框值向表中添加URL,然后将这些URL返回到MVC控制器POST操作。尝试过以下但是提交点击是将帖子触发回服务器而不是执行jquery代码。

<h2>Index</h2>

@using (Html.BeginForm())
{
   <input type="text" name="input" id="Text1"/>
   <input type="submit" value="Submit" id="submit"/>
}

<div class="table-responsive">
   <table class="table" id="table1">
         <tr>
            <th>Site</th>
        </tr>
        <tr>
            <td>www.example.com</td>
        </tr>
    </table>
</div>

@using (Html.BeginForm("WebDriver", "Home", FormMethod.Post))
{
  <input type="submit" value="Complete" id="complete" />
}

<script type="text/javascript">
  $(document).ready(function () {
    $('#submit').click(function(){
        var val1 = $('input[id="Text1"]').val();
        for (var i = 0; i < val1; i++) {
            $('table[id="table1"]')
                .append(' <tr class="row">' + val1 + '</tr>');
        }
    });
});
</script>

3 个答案:

答案 0 :(得分:1)

您的案例中的问题是,当您点击&#34;点击&#34;时,您正在重新加载页面。事件。这就是您必须以这种方式阻止提交按钮的默认行为的原因:

$(document).ready(function () {
  $('#submit').click(function(e){
    //this prevents the form submission
    e.preventDefault();
    //this updates the table info 
    var val1 = $('input[id="Text1"]').val();
    $('#table1').html( $('#table1').html()+' <tr class="row"><td>' + val1 + '</td></tr>');
});
});

答案 1 :(得分:1)

试试这个:

$('#submit').click(function(e){
  e.preventDefault();  // this is how to stop the form submitting
  var val1 = $('#Text1').val();  // us an id selector - it is much better performance
  if (val1 != '') { // check if textbox was empty (not sure what your loop did)
    $('#table1').append('<tr class="row"><td>' + val1 + '</td></tr>');  //apend new row to table
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="./" method="post">
   <input type="text" name="input" id="Text1"/>
   <input type="submit" value="Submit" id="submit"/>
</form>

<div class="table-responsive">
   <table class="table" id="table1">
         <tr>
            <th>Site</th>
        </tr>
        <tr>
            <td>www.example.com</td>
        </tr>
    </table>
</div>

答案 2 :(得分:0)

您可以改为&#34;提交&#34;按钮只需一个&#34;按钮&#34;,在您的点击处理程序上,您可以根据需要在处理后提交表单。您还应该在表单中添加ID。

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "myForm" }))
{
   <input type="text" name="input" id="Text1"/>
   <input type="button" value="Submit" id="submit"/>
}

<script type="text/javascript">
  $(document).ready(function () {
    $('#submit').click(function(){
        var val1 = $('input[id="Text1"]').val();
        for (var i = 0; i < val1; i++) {
            $('table[id="table1"]')
                .append(' <tr class="row">' + val1 + '</tr>');
        }
        $('#myForm').submit();
    });
});
</script>