Search code examples
javascripthtmlweb-applicationsanchor

Add anchor tag dynamically to page as pop up while onclick


Trying to add an <a> tag in the below <div> after submit button.

$("div#idSection").append('<a href=http://localhost/request+{argument passed dynamically after clicking on submit button}+' onclick = "window.open('href=http://localhost/request+{argument passed dynamically after clicking on submit button}'">REPORT</a>);
<div align="center" id="idSection">
  <input type="text" id="first" placeholder="Enter id here..." maxlength="11" />
  <input type="button" id="submit" value="Submit" />
</div>


Solution

  • You are trying to append an tag to a element after a submit button is clicked, and you are passing an argument dynamically to the href attribute of the tag. Your approach is almost correct, but there are a few issues with the syntax of the code you've provided:

    • The href attribute in the tag should be enclosed in quotation marks.

    • You are using ' onclick' instead of ' onClick'

    • You are trying to use the variable passed dynamically inside the single quotes of the window.open function, you should use it like this:

      window.open(href=http://localhost/request+${argument})

    Here's an updated version of the code:

    $("div#idSection").append(`<a href="http://localhost/request+${argument}" onClick="window.open(href)" >REPORT</a>`);

    This approach should work as long as the variable "argument" is defined and contains the correct value when the submit button is clicked.

    Also, it's worth noting that, using window.open() might not be the best approach as it can be blocked by pop-up blockers and it may cause the browser to open the link in a new window or tab, which may not be desirable. You may consider using window.location.href or router.push() instead.

    In summary, this approach is correct but needs some syntax and formatting changes.