Button onclick function in HTML keeps resetting the form input fields to default values. How can I avoid this?

Anubhov Sharma :

Hi I'm in the process of building a basic tableau extension using HTML and JavaScript that takes start and end dates from the user, on submission of which my view in Tableau gets filtered to the range.

However, each time I click submit in the form the dates keep getting resetting to the default value defined in my HTML code and passes that to my JS code to process. It does not retain the user input, could someone have a look at the code below and advise on what I'm missing here?

<html>
    <head>
        <title>My Extension</title>
        <script src="/tableau.extensions.1.latest.js"></script>
    </head>
    <body>
        <h1>Hello! This is a basic filter extension</h1>
        <form>
          <label for="sdate">Start Date:</label><br>
          <input type="date" id="sdate" name="sdate" value="2015-01-01"><br>
          <label for="ldate">End Date:</label><br>
          <input type="date" id="ldate" name="ldate" value="2016-01-01"><br><br>
            <button onclick="tableau.extensions.initializeAsync()">Submit</button>
            <script>
            tableau.extensions.initializeAsync().then(() => {
                let fieldName = 'Order Date';
                let dashboard = tableau.extensions.dashboardContent.dashboard;
                let selectedWorksheet = dashboard.worksheets.find(w => w.name === 'Sale Map (2)');
                updateFilterRange(selectedWorksheet, fieldName);
            });
            function updateFilterRange(worksheet, fieldName) {
                let today=new Date();
                var lastDate=new Date(document.getElementById("ldate").value);
                var startDate=new Date(document.getElementById("sdate").value);
                worksheet.applyRangeFilterAsync(fieldName, { min: startDate, max: lastDate});
            }
            </script>
        </form>

    </body>
</html>
Abhishek Prashant :

You can try this. Add an id to that button and add an eventlistener to prevent the default way form submission is handled

<button id = "submit">Submit</button>
<!-- HTML Code -->
<script>
  const button = document.getElementById("submit")
  button.addEventListener("click", function(e) {
    e.preventDefault()
    // Your code for handling button click
  }
</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198450&siteId=1