Home » Jquery » jquery – javascript autoclick does not seem to autoclick-Exceptionshub

jquery – javascript autoclick does not seem to autoclick-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I’m really new to javascript and jquery and I’m trying to get a button to autoclick from an existing code base. I am having trouble getting the button to do that even though this is what I’ve been following How to auto click an input button.

The code is below. I’ve tried using both .submit() and .click() but the start-game-btn doesn’t seem to get pressed either way. I’ve put a console.log within the button whenever it’s pressed and the message doesn’t seem to get logged.

console.log("loading...")

$(() => {

  $("#start-game-btn").click(event => {
    console.log("start-game")
    $("#errors").text("")
    event.preventDefault()
    const height = parseInt($("#height").val())
    const width = parseInt($("#width").val())
    const food = parseInt($("#food").val())
    let MaxTurnsToNextFoodSpawn = 0
    if ($("#food-spawn-chance").val()) {
      MaxTurnsToNextFoodSpawn = parseInt($("#food-spawn-chance").val())
    }
    const snakes = []

    $(".snake-group").each(function() {
      const url = "http://0.0.0.0:8080/"//$(".snake-url", $(this)).val()
      console.log(url)
      if (!url) {
        return
      }
      snakes.push({
        name: "M1",//$(".snake-name", $(this)).val(),
        url
      })
    })
    if (snakes.length === 0) {
      $("#errors").text("No snakes available")
    }
    console.log(12)
    fetch("http://localhost:3005/games", {
      method: "POST",
      body: JSON.stringify({
        width,
        height,
        food,
        MaxTurnsToNextFoodSpawn,
        "snakes": snakes,
      })
    }).then(resp => resp.json())
      .then(json => {
        const id = json.ID
        fetch(`http://localhost:3005/games/${id}/start`, {
          method: "POST"
        }).then(_ => {
          $("#board").attr("src", `http://localhost:3009?engine=http://localhost:3005&game=${id}`)
        }).catch(err => $("#errors").text(err))
      })
      .catch(err => $("#errors").text(err))
  })
  console.log("ready!")
})

window.onload = function(){
    var button = document.getElementById('start-game-btn');
    button.form.submit();
    console.log("Done!!")
}

Everytime I refresh the page the log shows:

loading...
ready!
Done!!

What I think it should be logging is (or at least that’s what I’m trying to achieve):

loading...
start-game
ready!
Done!!
How to&Answer:

submit() does not work because it is for submitting forms.
button.form.submit(); does not work because it assumes your button is part of a form.
As it looks like you are using jQuery, try just calling the jQuery click function without any parameters using a jQuery selector.
eg.
$("#start-game-btn").click();