# Delete variable data from a device

Use this example to build an HTML Canvas widget that deletes a device variable's values within a selected time window.

* Create the structure. Paste the following into the HTML code editor tab:

```html
<div>
    <p id="token"></p>
    <p id="selectedDeviceID"></p>
	<p id="selectedDeviceLabel"></p>
	<select id = "labels"></select>
	<form id="date-form">
		<label for="date1">Start date:</label>
		<input type="datetime-local" id="date1" name="date1" value="2023-01-01T00:00" required>
		<br>
		<label for="date2">End date:</label>
		<input type="datetime-local" id="date2" name="date2" value="2023-01-01T12:00" required>		
		<br>
		<button type="submit">Delete values</button>
	</form>
</div>
```

* Paste the following into the CSS code editor tab:

  ```css
  body {
    font-family: Arial, sans-serif;
    max-width: 400px;
    margin: 0 auto;
    padding: 2rem;
  }

  form {
    display: flex;
    flex-direction: column;
  }

  label, input {
    margin-bottom: 1rem;
  }

  button {
    cursor: pointer;
    background-color: #0077cc;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 4px;
    font-size: 1rem;
    font-weight: bold;
  }

  button:hover {
    background-color: #005aa3;
  }
  ```
* Paste the following into the JavaScript code editor tab:

```javascript
var ubidots = new Ubidots();
const BASE_URL = 'https://industrial.api.ubidots.com';
const API1 = '/api/v1.6';
const API2 = '/api/v2.0';
var token;
var deviceLabel;
var deviceID;
var firstTime = true;
var deviceVariables;
var dropdown = document.getElementById('labels');
var selectedVariableLabel;
var selectedVariableID;


ubidots.on('ready', async function () 
{
	token = ubidots.token;
	deviceID = ubidots.selectedDevice;
	deviceLabel = await getDeviceLabelById(deviceID, token);
	deviceVariables = await getDeviceVariables(deviceID, token);
	deleteDropdownItems(dropdown);
	populateDropdownItems(deviceVariables, dropdown);
	displayDeviceData(deviceID, deviceLabel, token);
	firstTime = false;
});

ubidots.on('selectedDevice', async function (data) 
{
	deviceID = data[0];
	displayDeviceID(deviceID);
	if(!firstTime)
	{
		deviceLabel = await getDeviceLabelById(deviceID, token);
		deviceVariables = await getDeviceVariables(deviceID, token);
		deleteDropdownItems(dropdown);
		populateDropdownItems(deviceVariables, dropdown);
		displayDeviceData(deviceID, deviceLabel, token);
	}
    
});

dropdown.addEventListener("change", function() 
{
  	//selectedVariableLabel = this.options[this.selectedIndex].value;
	const este = this.options[this.selectedIndex].value;
	selectedVariableID = este.split(":")[1].trim();
	selectedVariableLabel = este.split(":")[0].trim();

});

document.getElementById('date-form').addEventListener('submit', async function(event)
{
	// Prevents form submission and page reload
	event.preventDefault();

	//Estas son las fechas que la persona pone en los campos
	const ts1 = toTimestamp(document.getElementById('date1').value);
	const ts2 = toTimestamp(document.getElementById('date2').value);
	if(ts1 > ts2)
	{
		console.error("ERROR: end date being earlier than start date.", ts1, ts2);
		console.log("startDate: ", ts1);
		console.log("endDate: ", ts2);
		return {"ERROR": -1};
	}
	
	console.log(selectedVariableID);
	console.log("startDate: ", ts1);
	console.log("endDate: ", ts2);	
	//url quemada con el endpoint, el device y los timestamps
	var url = "https://industrial.api.ubidots.com/api/v2.0/variables/" + selectedVariableID + "/_/values/delete/?startDate=" + ts1 + "&endDate=" + ts2;
	console.log("URL: ", url);
	const response = await fetchWrapper(url, 'POST', token);
	console.log(response);

});

function displayToken(Token)
{
	document.getElementById('token').innerText = "TOKEN: " + Token;
}
function displayDeviceLabel(DeviceLabel)
{
	document.getElementById('selectedDeviceLabel').innerText = "Selected Device label: " + DeviceLabel;
}

function displayDeviceID(DeviceID)
{
	document.getElementById('selectedDeviceID').innerText = "Selected Device id: " + DeviceID;
}

function displayDeviceData(DeviceID, DeviceLabel, Token, VariableLabel)
{
	displayToken(Token);
	displayDeviceLabel(DeviceLabel);
	displayDeviceID(DeviceID);
}

function populateDropdownItems(items, dropdownObj)
{
	var isFirst = true;
	items.forEach(function(item)
	{
		if(isFirst)
		{
			selectedVariableID = item.id;
			selectedVariableLabel = item.label;
		}
		var option = document.createElement('option');
  		option.text = item.label + " : " + item.id;
  		dropdownObj.add(option);
		isFirst = false;
	});
}

function deleteDropdownItems(dropdown)
{
	while (dropdown.firstChild) 
	{
    	dropdown.removeChild(dropdown.firstChild);
  	}
}

async function getDeviceLabelById(DeviceID, Token)
{
    var url = `${BASE_URL}${API2}/devices/${DeviceID}/?fields=label`;
	var response = await fetchWrapper(url, 'GET', Token);
	return response.label;
}

async function deleteDevicesValues(DeviceID, Token)
{
	
}

async function getDeviceVariables(DeviceID, Token)
{
	const url = 'https://industrial.ubidots.com/api/v2.0/devices/' + deviceID + '/variables';
	const response = await fetchWrapper(url, 'GET', Token);
	return response.results;
}

async function fetchWrapper(url, method, token = null, payload = null)
{
	const options =
	{
    	method: method,
    	//headers: {},
		headers: {'Content-Type' : 'application/json'}
	};

	//options.headers['Content-Type'] = 'application/json';

	if (payload)
	{
    	options.body = JSON.stringify(payload);
  	}

  	if (token)
	{
    	options.headers['X-Auth-Token'] = token;
  	}

	const response = await fetch(url, options);
	const jsonData = await response.json();
	return jsonData;
}

function toTimestamp(date) 
{
	const dateObj = new Date(date);
	const timestamp = dateObj.getTime();
	return timestamp;
}
```

The result is a widget like this:

<figure><img src="/files/lWokWnTRSHhJXex3ZlS9" alt="" width="563"><figcaption></figcaption></figure>

Use the dropdown to select a variable from the current device in the Dynamic Dashboard. Then choose a time window with the date pickers.

When you click **Delete values**, Ubidots deletes that variable's data for the selected time window.

Ubidots runs this action asynchronously. You may need to wait a few minutes before the values disappear.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dev.ubidots.com/dashboards-and-widgets/html-canvas/examples/delete-variable-data-from-a-device.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
