0

I want JavaScript to click a button when a parameter is in the url (&startCalc=1).

html:

<input name="startCalc" value="Start" type="submit">

javascript:

var parameterExists = url.searchParams.get("startCalc");
if(typeof parameterExists !== 'undefined' && parameterExists == 1) {
    document.getElementsByName('startCalc').click();
}

I get an error: "click is not a function". I want to simulate a click the same way as an user would would do it when clicking on that button...

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • Does this answer your question? [How do I programmatically click on an element in JavaScript?](https://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-javascript) – Yannick Dec 03 '21 at 15:31
  • You can't click multiple elements. Look at what `getElementsByName` returns. – isherwood Dec 03 '21 at 15:32
  • 1
    try `document.getElementsByName('startCalc')[0].click();` – TechySharnav Dec 03 '21 at 15:37

1 Answers1

0

Two things you need to change First searching parameter in URL and second when getting button by name you get an array so you need to specify the index of that. Check the code below: DEMO

let url = "https://jsfiddle.net&startCalc=1"; // Suppose you are getting url in here
let urlParams = new URLSearchParams(url);
let parameterExists = urlParams.get('startCalc');

if(typeof parameterExists !== 'undefined' && parameterExists == 1) {
    document.getElementsByName('startCalc')[0].click();
    console.log('button clicked!')
}
iftikharyk
  • 870
  • 5
  • 10