Ad

How To Save Click Event To HTML Form Using Javascript

- 1 answer

I have an HTML form that includes several links in the following format:

<a id="url_1" target="_blank" rel="nofollow noreferrer" href="#" target="_blank">LINK</a>

How can I detect whether such a link was clicked and then save that event (e.g., as url_1.clicked) in my form?

I tried

<script>
    function updateInput(){
    document.getElementById("#url_1").value = "clicked";
}
</script>

and adding onclick="updateInput(this.value)" to the link, but that doesn't work.

I suppose the problem is that the link is not an input and can therefore not be updated. I am stuck however in creating an appropriate input to the form. In the data file that results from submitting the form, one variable should indicate whether the link has been clicked.

Ad

Answer

Solved it with the help of a co-worker today. This is the only solution that worked for me:

JavaScript:

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

<script>
var clickedlinks = [0,0,0,0];

$('html').on('click','.tracked',function () {
    var id = $(this).attr('id').split('_')[1];
    console.log(id);
    clickedlinks[id] += 1;
    $('#tracker').val(clickedlinks);
});
</script>

HTML:

<form>
<a id="url_0" class="tracked" target="_blank">LINK</a>
<a id="url_1" class="tracked" target="_blank">LINK</a>
<a id="url_2" class="tracked" target="_blank">LINK</a>
<a id="url_3" class="tracked" target="_blank">LINK</a>
<input id="tracker" type="hidden" name="tracker">
<input type="submit">
</form>

The number of times each link was clicked is saved in clickedlinks and then sent to the form as tracker via a hidden input field. For this to work it is crucial that each link id ends on _{number} as in url_1.

Ad
source: stackoverflow.com
Ad