MDoe
MDoe

Reputation: 193

Can I pass a string argument to an onclick javascript function?

In one script I have

<a href="javascript:void;" id="druck">

This is evaluated by javascript in another script (these are nested templates in django). This should then open a new window in order to prepare a site that is more printer-friendly (still a way to go).


$(function() {
    var b = document.getElementById("druck");
    b.onclick = function() {
    
        var mywindow = window.open('', 'PRINT', 'height=400,width=600');
        mywindow.document.write('<html><head><title>' + document.title + '</title>');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/bootstrap.min.css' %}" type="text/css">');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/bootstrap.css' %}" type="text/css">');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/dashboard.css' %}" type="text/css">');
        mywindow.document.write('</head><body>');

I would like to pass a string parameter from the first script to the second script, so that I can print the string as well. I am not fit in js, therefore I am asking how I can pass a string to such a href with an id and a javascript void function with onclick and so on.

Upvotes: 2

Views: 4319

Answers (1)

Akshay K Nair
Akshay K Nair

Reputation: 1476

You can do it in 2 ways. You can either call the function from the element itself like:

<a href="javascript:void;" onclick="myFunction ('string')" id="druck">

Or you can use a data-* attribute;

<a href="javascript:void;" data-string="my string" id="druck">

And inside js,

b.onclick = (event) => {
  let myString = event.currentTarget.dataset.string;
  //Code
}

(https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset)

Upvotes: 3

Related Questions