Reputation: 13963
I want to remove a part of the existing url of my Website when a user clicks a button. I have an anchor inside a button, but I want to get rid of that to be able to manipulate default url in javascript click handler.
Here is my code
<tbody>
{% for stu in st %}
<tr>
<td>
{{stu.id}}
</td>
<td>
{{stu.type}}
</td>
<td>
{{stu.detail}}
</td>
<td>
{{ stu.title }}
</td>
<td class="td-actions">
<span class="row mb-3" style="width:8vh;">
// I know it's wrong to have an anchor inside a button, but how to do that with javascript click handler
<button class="btn" type="button" id="edit_btn" title="Edit" style="color:white;background-color:#fff;">
<a href="/data/{{stu.id}}/update">
<i class="glyphicon glyphicon-pencil fa-2x"></i>
</a>
</button>
<button class="btn" type="button" id="dlt_btn" title="Delete" style="color:white;background-color:#fff;">
<a href="/data/{{stu.id}}/delete">
<i class="glyphicon glyphicon-trash fa-2x"></i>
</a>
</button>
</span>
</td>
</tr>
{% endfor %}
</tbody>
...
...
...
<script>
var editBtn= document.getElementById('edit_btn');
editBtn.addEventListener("click",function(){
//Here I need {{stu.id}} because I want to remove some part from the default utl before directing to /data/{{stu.id}}/update
})
</script>
Upvotes: 0
Views: 41
Reputation: 1466
if you want to remove anchor, you can use "data-*" attributes
<button class="btn" type="button" id="edit_btn" title="Edit"
data-url="your url"
style="color:white;background-color:#fff;">
</button>
<script>
var editBtn = document.getElementById('edit_btn');
editBtn.addEventListener("click",function(event){
event.preventDefault();
console.log(editBtn.dataset.url); // you can modify it as you want
})
</script>
Upvotes: 1
Reputation: 421
I would suggest making following changes:
First, add data-href
attribute to the button so that we don't need <a></a>
inside it anymore:
<button class="btn" type="button"
id="edit_btn" title="Edit"
style="color:white;background-color:#fff;"
data-href="/data/{{ stu.id }}/update">
<i class="glyphicon glyphicon-pencil fa-2x"></i>
</button>
Then in JavaScript read and extract stuId
from the button tag using simple regular expression:
editBtn.addEventListener("click", function(event) {
let url = this.getAttribute('data-href');
// Assuming every url has same structure:
let stuId = url.match('^/data/([0-9]+)/')[1];
// Do other stuff to stuId / url
// ...
// Then simulate user click:
window.location.href = url;
});
Upvotes: 1