【问题标题】:jQuery: find id of of a form fieldjQuery:查找表单字段的 id
【发布时间】:2009-04-06 05:35:19
【问题描述】:

我正在创建一个动态表单,用户可以在其中向表单添加一组输入。 html 看起来像这样:

<form>
    <input id="title1" class="title" name="title1"  type="text" value="">
    <input id="productionCompany1" name="productionCompany1" type="text" value="">
    <input id="year1" name="year1" type="text" value="">
    <input id="role1" name="role1" type="text" value="">
<div id="newCredit">&nbsp;</div>
<a href="#" id="addCredit">add another credit</a>
</form>

当用户单击 id 为“addCredit”的链接时,会调用以下 jQuery 脚本:

$(document).ready(function() {
    var $ac = $('#addCredit');
    $ac.click(function() { 
/* the following two lines are where the problem lies? */
        var $credInt = $(this).prev(".title"); 
        $.get("addCredit.php", {num: $credInt},
        function(data){
        $('#newCredit').append(data);});
        return false;
    });
});

jQuery 函数查询名为“addCredit.php”的 php 文件,如下所示:

<?php 
$int = $_GET["num"];
$int = substr($int, -1); 
$int++;
?>
<input id="title<?php echo $int;?>"  class="title" name="title<?php echo $int;?>"  type="text" value="">
<input id="productionCompany<?php echo $int;?>" name="productionCompany<?php echo $int;?>" type="text" value="">
<input id="year<?php echo $int;?>" name="year<?php echo $int;?>" type="text" value="">
<input id="role<?php echo $int;?>" name="role<?php echo $int;?>" type="text" value="">

我的问题是正确设置 javascript 变量 $credInt 以便可以将其发送到 addCredit.php 页面并相应地更新表单字段。我还需要确保每次附加表单时,发送的下一个值是递增的值。

我有什么想法可以做到这一点吗?感谢您的帮助。

【问题讨论】:

    标签: php jquery


    【解决方案1】:

    这是错误的做法; PHP 可以处理变量名中的数组语法。这使它更容易处理。也不需要调用服务器来克隆表单。你应该这样命名你的字段:

    <form>
        <div id="originalCredit">
        <input name="title[]"  type="text" value="">
        <input name="productionCompany[]" type="text" value="">
        <input name="year[]" type="text" value="">
        <input name="role[]" type="text" value="">
        </div>
        <a href="#" id="addCredit">add another credit</a>
    </form>
    

    然后你的 Javascript 可以是这样的:

    $(function() {
        $('#addCredit').click(function() {
            var newCredit = $('#originalCredit').clone(); // create new set
            newCredit.find('input').val(''); // empty input fields
            $(this).before(newCredit); // append at the end
            return false;
        });
    });
    

    当表单最终发送到服务器时,因为变量是name[]的格式,PHP会识别出它们是一个数组,然后你可以这样做:

    <? foreach($_POST['title'] as $k => $v) { ?>
        Title: <?=$_POST['title'][$k]?><br>
        Company: <?=$_POST['productionCompany'][$k]?><br>
        Year: <?=$_POST['year'][$k]?><br>
        Role: <?=$_POST['role'][$k]?><br>
    <? } ?>
    

    显然,这只是作为示例显示,但您可以使用它进行保存/更新/任何操作。

    【讨论】:

    • 我喜欢克隆功能,它消除了对附加文件的需要。漂亮的代码!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2013-11-11
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多