简体   繁体   English

隐藏的输入值,表单循环中的非唯一ID

[英]HIdden input value, non unique ID in form loop

I'm trying to prep forms with multiple (dynamic) inputs to insert correctly via ajax. 我正在尝试准备具有多个(动态)输入的表单,以通过ajax正确插入。

Currently, using my php loop, I have 4 div/forms. 目前,使用我的php循环,我有4个div / forms。 Each form has a starting input, and upon clicking the moreItems_add button, it dynamically adds another input, up to 10 per form/div. 每个表单都有一个起始输入,单击moreItems_add按钮后,它会动态添加另一个输入,每个表单/ div最多可添加10个输入。

This works fine. 这很好。 But I added a variable and console.log to log the value of my hidden input though, which should be getting an ID ( <?php echo $ticker['ticker'] ?> ) for each form, but it's currently only logging '1'. 但是我添加了一个变量和console.log来记录我的隐藏输入的值,该值应该为每个表单获取一个ID( <?php echo $ticker['ticker'] ?> ),但目前仅记录' 1。 So when I clicked the button in the first form it looked right, but when I click the others, it's still 1. I think this is because I don't have a unique ID on the hidden input? 因此,当我单击第一个表单中的按钮时,它看起来正确,但是当我单击其他表单时,它仍然为1。我认为这是因为我在隐藏的输入中没有唯一的ID?

How can I change the way I'm keeping track of the hidden input so that I can make an ajax call that will only make an insert on the inputs of the given form WITH the correct ticker ID? 如何更改跟踪隐藏输入的方式,以便可以进行ajax调用,该调用仅在具有正确的代码ID的给定表单的输入上进行插入?

<?php foreach($tickerDisplays as $key => $ticker):?>

    <form id="Items" method="post">
        <label id="ItemLabel">Item 1: </label>
        <input type="text" name="Items[]"><br/>
        <button type="button" class="moreItems_add">+</button>

        <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
        <input type="submit" name="saveTickerItems" value="Save Ticker Items">  
    </form>

<?php endforeach;?>


<script type="text/javascript">

$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
  var numItems = $("input[type='text']", $(this).closest("form")).length;
  if (numItems < 10) {
    var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
    html += '<input type="text" name="Items[]"/><br/>';
    $(this).before(html);
    console.log(tickerID);
  }
});

</script>

To generate a unique id attribute you should append your ticker value from php to... the id attribute. 为了生成唯一的id属性,您应该将PHP的ticker值附加到... id属性。 Or if not the ticker value, at least something that makes it unique. 或者,如果不是代码价值,则至少要使其唯一。 But you don't really need to. 但是您并不需要。

Since all your elements are wrapped in a form tag and are at the same level, you can find to which ticker corresponds the clicked button by finding the hidden input among its siblings : 由于所有元素都包装在一个form标签中并且处于同一级别,因此您可以通过在siblings元素中找到hidden input来找到与单击的按钮对应的代码:

var tickerID = $(this).siblings('input[name="tickerID"]').val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM