python小菜 2015-08-06 12:40 采纳率: 0%
浏览 152

动态获取按钮ID

I need to get the button id when the button is clicked---

This is my code for my button, to show dynamically data dynamically when the condition is true.

Twig:

  {% for usr in userstats %}
    {% if usr.condition == TRUE %} 
        <button type="submit" class="btn btn-success btn-xs  myOnButton.onclick = function(event){alert(event.currentTarget.id);} myOnButton">Allow</button> 

this is my ajax for my button ---

<script>
    $(".myOnButton").on('click', function () {
        if (confirm('{% trans %}Are you sure?{% endtrans %}')) {
            $('body').addClass('load');

            var url = '/hello/hello';
            // Submit data via AJAX
            var data = {};
            $.ajax({
                url: url,
                type: 'POST',
                success: function (data) {
                    // Redirect to view
                    url = '/hello';
                    location.href = url;
                }
            });
        }
        return false;
    });

For being more clear- Suppose in one column we have (name:Dell, CompanyId:3001, Address- HelloDell, Phone-07555, condition:True) and in other column we have (name:Apple, CompanyId:5001, Address- HelloApple, Phone-07555, condition:True).

So how can I get the CompanyId when the button is clicked in the twig file?

Does someone know any solution for this problem?

  • 写回答

1条回答 默认 最新

  • weixin_33696106 2015-08-06 13:03
    关注

    using plain JS (without frameworks) and asuming you have multiple buttons with the class myOnButton you could easily do this:

    var buttonClickHandler = function(e){
      console.log(e.target.id);
    }
    
    var buttonList = document.getElementsByClassName('myOnButton');
    buttonList.forEach(function(button){
      button.addEventListener('click', buttonClickHandler);
    });
    

    EDIT1 & EDIT2:

    using JQuery I assume corresponding code would look something like this:

    $('.myOnButton').on('click', function(e){
      var buttonId = e.currentTarget.id;
      //start post request
      $.post('my/path/to/service.php', {id:buttonId}, function(data, err){
         //wait for response here
         console.log("my data yippii", JSON.stringify(data));
      })
    });
    

    PHP Part the service.php would look something like this (I have to admit it's absolutely not my strength)

    //retrieve id
    id = $_POST['id'];
    

    now that you got the ID you can verify it and start to SELECT on DB or something

    hope this helped

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?