Update div only if a certain conditions holds true - javascript

I am writing a simple webserver with micropython.
I want to switch on a relay for a certain duration (given in input by the user from the HTML form).
When the relay is off, I display a div with the input form for the duration and the activation button.
When the relay is on, the same div is replaced with a countdown; when the relay is on I want to refresh the div every second so that the countdown is updated. When the relay is off, I don't want the div to update because otherwise, if you try to input the duration, every second the input number in the box is cleared.
My div is updated by the following script:
<script>
$(document).ready(function () {
setInterval(function () {
$("#div_name").load(window.location.href + " #heatingDiv");
}, 1000);
});
</script>
The div is:
<div id="div_name">
<h1>Title</h1>
insert_content
</div>
The keyword "insert_content" is replaced with the HTML code inside the micropython program (accordingly to the relay state) before the HTML response is sent.
With the previous code everything works fine except for the fact that the div is updated every second even when the relay is off, making it impossible to input the duration in the form.
What I'd like to do is passing an argument to the script similarly as when one uses onClick to call it (I can modify "state" within micropython before sending the response):
<div id="div_name(state)">
<h1>Title</h1>
insert_content
</div>
and the script should look like:
<script>
$(document).ready(function () {
setInterval(function (var state) {
if(state){
$("#div_name").load(window.location.href + " #heatingDiv");
}
}, 1000);
});
</script>
Of course this does not work because id=div_name is not a function call: it is just to give an idea of what I'd like to achieve.
How can I do that?

Why not use a data attribute:
const $div = $("#div_name");
const state = $div.data('state');
if (state) {
setInterval(function() {
$div.load(window.location.href + " #heatingDiv");
}, 1000);
}
// if you are wanting to do the interval to check if the state changes, you could change it around
setInterval(function() {
const state = $div.data('state');
if (state) {
$div.load(window.location.href + " #heatingDiv");
}
}, 1000);
<div id="div_name" data-state="state">
<h1>Title</h1>
insert_content
</div>
Perhaps if you are only wanting to run the load when the state changes, you may be better of with a MutationObserver watching the data attribute instead of a timeout

Related

How to Change value of input after page loads?

I have used a range picker (Progress bar) to get measurements from the customers. I have set it's limit from 1 to 50 so it takes 1 value by default if user do not select it and user can add product to the cart without selecting range picker. Is there any way that we can change by default value on page load with javascript (No jQuery) to something that does not allow user to add product to the cart.
Link: https://cutt.ly/nrB4PAR
I am using this code now but it's not working. I want value to be null.
<script type="text/javascript" language="javascript">
debugger;
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1)
{
document.getElementById("tmcp_range_1").value = "";
}
</script>
UPDATED:
I’m not sure I really understand why you need this, but you have to put that code in a function, then call an event listener.
function changeVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", changeVal);
Updating the input value after DOM loads will change the value.
function updateVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", updateVal);
And also you need to change noUiSlider logic to update UI.
Ref link https://refreshless.com/nouislider/slider-read-write/

How to append dynamic data

Basically i have a REST api which return a JSON . In this JSON , it return the last viewed topic. For example
{ lastview : ABC }
So i want to insert this to my page
<div class = 'lastview'>Last viewed topic: </div>
$.getJSON("json link", function(data){
$('<a/>',{
text: data.lastview
}).appendTo('.lastview');
But since this data may change after another topic is viewed. What i mean is if user go to another topic name XYZ , the JSON change lastview from ABC to XYZ but the one in web will not ( still ABC ) because it only execute the function one time when the page loads.
So is there anyway to dynamically check the JSON and return correctly when the content changes ( What i mean is when the lastview topic change to XYZ , the one in div will automatically change to XYZ too)
Thanks
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
1000 ms = 1 second.
The function is only executed once. If you need to repeat execution, use the setInterval() method.
setInterval({
$.getJSON("json link", function(data){
$('<a/>',
{
text: data.lastview
}).appendTo('.lastview');
}, 1000);
This is a sample of keep requesting and update every 500ms
setInterval(function() {
// Fake ajax
data = { lastview: "Page " + Math.floor(Math.random() * 3) };
// Just for demo
$("#lastview").empty();
$("#lastview").append(
$("<a></a>").text(data.lastview)
);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Last viewed topic: <span id="lastview"></span></div>

Change the output automatically without refreshing

I have this code, it basically changes the word 'article' to 'articles' if the value is '0' or more than '1'. But the word only changes when the page is refreshed. Is it possible to automaticaly re-run the code at the same moment the value (quantity) changes?
<span id="quantity" class="simpleCart_quantity"></span> gets it's value from an external file, it is always a number (like 0, 1, 2, 3, etc.)
<span id="quantity" class="simpleCart_quantity"></span>
<span id="quantityText"></span>
<script type="text/javascript">
$(window).load(function()
{
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
});
</script>
Thanks in advance!
Yes it's possible.
The direct and dirty way is to poll the server for changes at an interval. make a timer function that calls an ajax function that checks to see if the article count has changed.
something like:
setInterval(function(){
$.ajax({
url:"checkchanges.php",
dataType:"json",
type:'GET',
.success(function(data){
if (data.articlecount>1){ //pseudocode, it depends on how you get your data
$("#quantity").innerHTML="articles";
}
})
});
},3000);
Another method is to use a framework like meteor that wires the checking up for you.

javascript flush text

I'm trying to change the text in an h3 tag, but the changes don't happen until that the function is ended. I want to change the text immediately.
For example:
<h3 id="myText"></h3>
<input type="button" onClick="changeText('Hello');">
<script type="text/javascript">
function changeText(str){
document.getElementById('myText').innerHTML = str;
}
</script>
Is it possible to refresh the screen immediately after changing the text?
(Like flush() command in C).
Note that if I put an alert after the command, the text is changed immediately:
function changeText(str){
document.getElementById('myText').innerHTML = str;
alert('HelloWorld');
}
To force an immediate refresh, you can do this :
document.getElementById('myText').innerHTML = str; // change the dom
setTimeout(function(){
// do other things
}, 0);
The do other things code will be executed after the refresh.
But it's highly unusual to have a script go on running for seconds.
If you are talking about the refresh all the page, you will lose the content you have changed on the client side because it is stateless (between requests). If you persist it on a repository (session, application, files you can read and write, databases, etc..) on server side you can read from the server side and keep it on your html elements.
In Javascript you could implement an dictionary (element id on key and innerHTML on value) and use it as a cache and implement a flush method to display all changes, try something like:
<script>
var cacheChanges = {};
function addChange(element, value){
cacheChanges[element] = value;
}
function flush() {
for(var i in cacheChanges)
{
var element = document.getElementById(i);
if (element) {
element.innerHTML = cacheChanges[i];
}
}
}
function ChangeSomething(){
// do some changes
addChange('myText', 'Hello');
addChange('myText2', 'Hello 2');
addChange('myText3', 'Hello 3');
// apply all them
flush();
}
</script>
and in your html:
<h3 id="myText"></h3>
<h3 id="myText2"></h3>
<h3 id="myText3"></h3>
<input type="button" onClick="ChangeSomething();">

Change a variable or activate a JS-linked <select> dropdown with Greasemonkey

I'm looking to change a javascript variable on page load with Greasemonkey.
The variable I'm looking to change is iDisplayLength the default value is 25, I want to change it to -1 on page load.
This is the script I tried; it did not work:
function changeTheDefaultViewVarLol() {
location.href = "javascript:void(windows.iDisplayLength = -1)";
};
changeTheDefaultViewVarLol();
Edit: From a comment below, the target page is tf2spreadsheet.blogspot.com.
The OP is actually trying to change the number of rows displayed on the page -- a function that is triggered by the "Show {x} entries" <select> dropdown.
You would just use:
unsafeWindow.iDisplayLength = -1;
No need for any of that changeTheDefaultViewVarLol() stuff.
However, this will not have the effect that you want if iDisplayLength is used by the page just after the page sets it to 25.
You will probably have to call a JS function to apply the new value. Link to the target page if this is the case.
Update for additional page information:
What you are actually trying to do is to invoke the "Show All entries" functionality of that page.
So, don't think in terms of poking JS variables, think in terms of activating whatever JS is tied to that <select>.
For a normal page similar to the one you specified, code like this would do it:
var showAllOpt = document.querySelector ('#main_table_length select option[value="-1"]');
var changeEvent = document.createEvent ("HTMLEvents");
if (showAllOpt) {
showAllOpt.parentNode.selectedIndex = showAllOpt.index;
changeEvent.initEvent ("change", true, true);
showAllOpt.parentNode.dispatchEvent (changeEvent);
}
BUT, that page AJAXes-in the desired table long after the page "loads". So, an additional step is needed, like so:
var showAllEntriesSelect = setInterval ( function() {
setSelectValueWhenitLoads (
"#main_table_length select option",
"-1",
showAllEntriesSelect
);
}
, 200
);
function setSelectValueWhenitLoads (cssSelector, targetValue, timerVar) {
var showAllOpt = document.querySelector (
cssSelector + '[value="' + targetValue + '"]'
);
if (showAllOpt) {
clearInterval (timerVar);
showAllOpt.parentNode.selectedIndex = showAllOpt.index;
var changeEvent = document.createEvent ("HTMLEvents");
changeEvent.initEvent ("change", true, true);
showAllOpt.parentNode.dispatchEvent (changeEvent);
}
}

Categories

Resources