How To Save Click Event To HTML Form Using Javascript
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.
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
.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM