简体   繁体   中英

Pass as string for JS with django not working

The table I have so far, when rendered, properly displays the job numbers which are formatted individually as: '15-215' or '15-552'

I want to pass each job number on the table so that when I click each TD it passes the job number into my javascript. It took me a while to diagnose that I need to pass as string otherwise it will evaluate 15-215 and then pass that.

My html document is like below:

    {% for a in obj %}
    ...

 <tr data-toggle="collapse" data-target="#demo{{forloop.counter}}" class="accordion-toggle">

        <td onclick="test(\'' + {{a.jobnum}} + '\')">{{a.jobnum}}</td>
    ...
    {% endfor %}

My js is like:

function test(y) {
  alert(y);
  document.getElementById("123").innerHTML = y;
  }

I then have:

<p id="123">1</p>

But when I click the relevant td I get neither an alert nor the <p> updating

I would do this a little bit different:

template

{% for a in obj %}
    ...

<tr data-toggle="collapse" data-target="#demo{{forloop.counter}}" class="accordion-toggle">

   <td data-jobnum='{{ a.jobnum }}' class="test">{{a.jobnum}}</td>
    ...
{% endfor %}

js(jquery)

$('.test').click(function(){
    var value = $(this).data('jobnum');
    alert(value);
})

Now you can do any javascript with the value .

Note

I used Jquery but you can do this with js also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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