Updating Global Counter Variable on Submit Button Click in jQuery - javascript

I'm trying to update a global counter variable in JavaScript when a button of type="submit" is clicked.
My submit button is defined like below:
<button
id="submitClicked"
type="submit"
value="Add &amp View Next"
>
I am using the following code in JavaScript to update a global variable I've called orderCounter that increments each time the "Add & View Next" button is clicked:
var orderCounter;
window.onload = function () {
document
.getElementById("submitClicked")
.onclick=incrementCounter;
};
function incrementCounter() {
if (orderCounter == null) {
orderCounter = 0;
} else {
orderCounter = orderCounter + 1;
}
alert(orderCounter);
return orderCounter;
}
The alert with this code always displays 0. Can anyone see where I'm going wrong?
Note: I've also tried using jquery .click on the submitClicked id in addition to using onClick within the HTML form.
I realize this should be simple; not sure where I'm going wrong.
Thank you!

the problem is that every time you click on the submit button your page refreshes, so the orderCounter varriable resets itself. one solution is to persistently wait so that its value is not reinitialized each time the page is loaded. One solution is to use kookies: https://www.w3schools.com/js/js_cookies.asp.
i hope this will welp you

The fix was to run function postValues() "onClick" of button type=submit and use session variables, following the same logic as in this post: Auto Increment in Session using Javascript is not working
I clear the sessionStorage variables in another file.
Working code:
function postValues() {
if(sessionStorage.getItem("count") == null){
counter=sessionStorage.setItem("count", 1);
counters = 1;
} else {
counters= parseInt(sessionStorage.getItem("count"));
counters++;
counter=sessionStorage.setItem("count", counters);
}
alert(counters);
document.getElementById("counter").value = counter;
}

Related

Focus specific 'id' after submit action

I want to focus on specific id (ex. using $('#a')) after submit.
There is nothing special with my code yet.
My javascript code is
function get_info(id){
$(user_id).submit();
$('#a).focus();
};
After submit, it should focus on where id='a'.
But after submit window focus on id='a' and reset the page.
I tried using
function get_info(id){
$(user_id).submit(function(e){
e.preventDefault();
$('#a').focus();
});
};
But this code make program worse. I think it stops performing submit.
Can anyone help me?
As Chris's comment says you couldn't focus on the element simply by using $('#a').focus(); after the submit since the page will be redirected/refreshed.
You need to use cookies or local storage, here a suggested sample using local storage like :
function get_info(id) {
localStorage.setItem('focusItem', '#a');
$(user_id).submit();
};
Then in the ready function, you could add :
$(function(){
var focusItem = localStorage.getItem('focusItem');
if( focusItem != null ){
$(focusItem).focus();
localStorage.removeItem('focusItem');
}
});
function SetFocus(){
$("#FocusingID").focus();}
/***********another way **********************//*
$("#submitbtnId").click(function(){
//your submession and other task;
$("#FocusingID2").focus();
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id=FocusingID>
<button type=submit onclick="SetFocus();">click</button>

Save and open the content of a textarea

i'm working on a text editor as part of a school project and i'm having a small issue with my save and open code.
Here are my buttons:
<button id="gu" onclick="save()">Save</button>
<button id="ab" onclick="open()">Open</button>
Here's my textarea:
<textarea name="comment" rows=30 cols=101 id="texto"></textarea>
And here's my javascript functions:
function save(){
gu = document.getElementById("texto");
localStorage.setItem("texto",gu);
console.log(texto+"="+gu);
}
function open(){
console.log("Abierto")
document.getElementById('texto').innerHTML=gu;
}
My goal is that if write something and then press the "save" button, the content inside my textarea is saved, and if i press the "open" button it shows what i wrote on the textarea.
Any idea on how to fix my code?
Sorry if my english is bad.
Here you go: https://jsfiddle.net/cinerobert/qwgv18r5/
function save()
{
localStorage.setItem("someitem", document.getElementById("texto").value);
document.getElementById("texto").value = "";
console.log(texto + "=" + gu);
}
function retrieve(){
console.log("Abierto")
document.getElementById("texto").value = localStorage.getItem("someitem");
}
You can't use open() as a function name because it's already a built-in function in javascript, so I changed it to retrieve(). See here: http://www.w3schools.com/jsref/met_win_open.asp
Is there some reason you're required to use setItem()? Using a variable (gu) and setItem is redundant. It would work either way.
Also to get and set the text inside a text area I you need to use value().
I also changed the save() function so that it clears the textbox, so that you can see something happen when you click retrieve().
Below are the things need to be done
function save()
{
gu = document.getElementById("texto");
localStorage.setItem("texto",gu.innerText); //here you were saving the dom object not the text inside
console.log(texto+"="+gu.innerHTML);
}
function open()
{
console.log("Abierto")
document.getElementById('texto').innerHTML=localStorage.getItem("texto"); //here you need to get the text from your local storage
}

Two submit buttons (one hidden and one visible)

One button is hidden so if it reaches the setTimeout, It will submit the page. The other button is visible and gives them a message that " You are about to close this attempt.
These are the two buttons:
<input type="submit" style="display: none;" name="autosubmit" onclick="autoclick()">
<input type="submit" value="Submit and finish" onclick="return changeSncro()">
There is the javescript:
<script type="text/javascript">
setTimeout(function() {
document.querySelector('[name="autosubmit"]').click();
}, (5000));
function autosubmit(){
sncro = 0;
}
</script>
<script type="text/javascript">
var sncro = 0;
function changeSncro(){
sncro = 1;
return confirm('You are about to close this attempt. Once you close the attempt you will no longer be able to change your answers.')
}
window.onbeforeunload = function (evt) {
if(sncro !=1){
var message = 'If you leave prior to SUBMITTING your test, it WILL NOT be scored and you WILL NOT get another attempt';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt ) {
evt.returnValue = message;
}
return message;
}
}
function maximize(){
window.moveTo(0, 0);
window.resizeTo(screen.width, screen.height);
}
maximize();
</script>
Right now the Time out works, but it's submitting it like someone hit the X button in the browser. It needs to just submit the information. The visible button is working like it should.
Thanks
It's a submit button so it will submit the form. Try a) using a plain button, b) stopping the default behaviour of your submit button, or c) not using a button at all. You've got a timer running, why not make it just do the thing you want with a function call?
BTW this code looks like something from 1998. It's technically correct but I suggest you look into a modern library like jQuery and learn about event listeners. If you're relying on some online resources for learning this stuff, look around for others. A lot has changed in 15 years and seeing "onclick" in HTML should be a big red flag! Good luck.

Button.onclick automatically triggers, then will not trigger again

I have a script, which I'm using to try and display only one section of a webpage at a time.
function showMe(id){ clearPage(); changeDisplay(id, "block"); console.log(id)}
Currently, I'm using buttons to change which section is displayed.
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=showMe("a-btn-section-id");
otherBtn.onclick=showMe("other-btn-section-id");
However, when I load the page, the following happens:
I see the function attached to each button activate once in sequence in the console.
The page refuses to respond to further button inputs.
Testing with the console shows that showMe() and the functions it calls still all work properly. I'm sure I'm making a very basic, beginner mistake (which, hopefully, is why I can't find this problem when I Google/search StackOverflow/read event handling docs), but I'm at a loss for what that mistake is. Why would my script assume my buttons are clicked on load, and why won't it let me click them again?
You're calling the function an assign the value to onclick property instead of attach the function, try defining your onclick property as:
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
Try the follow jsfiddle:
function showMe(id){ // some stuff..
console.log(id)
}
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
<input type="button" value="a-btn" id="a-btn"/>
<input type="button" value="other-btn" id="other-btn"/>
Hope this helps,

JavaScript Character Counter Resets to 0 after PostBack

I have this JavaScript that counts character from a textarea which is the code below:
$(document).ready(function () {
$('#count').click(counter);
$('#txtComment').change(counter);
$('#txtComment').keydown(counter);
$('#txtComment').keypress(counter);
$('#txtComment').keyup(counter);
$('#txtComment').blur(counter);
$('#txtComment').focus(counter);
$('#txtComment').focusin(counter);
$('#txtComment').focusout(counter);
$('#txtComment').mousedown(counter);
$('#txtComment').mouseenter(counter);
$('#txtComment').show(counter);
$('#txtComment').load(counter);
$('#txtComment').submit(counter);
$('#btnSubmit').click(counter);
});
counter = function () {
var value = $('#txtComment').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0); // I only use this one.
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length; // I only use this one.
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount); // I only use this one.
$('#charCountNoSpace').html(charCountNoSpace);
};
And I am displaying the counter in a span:
<span id="totalChars">0</span> characters
When the Page is not PostBack, the count seems to be working fine. On the page, I have a submit button which is an ASP.NET control that runs at server. When it comes to the scenario where the button is clicked, the page is doing a PostBack, after submitting the data, It will display the same page, retains the content of the textarea, but, the count sets back to zero even when there are value/s on the textarea. As you can see, I have already put almost all of possible events the form should do.
I need to count the characters and display it after PostBack.
The counter function is not firing until the textarea is interacted with. After binding all your events, call the counter function manually (IE counter();) in your $(document).ready function and the code will be run at page load.
You might think the load event would do this for you, but load only works with elements that have a URL associated with them (like images and scripts, see the documentation for more information).
You can use jQuery Cookies Plug-in to persist, like:
to save: jQuery.cookie("cookie_counter", totalChars);
to get: var totalChars = jQuery.cookie("cookie_counter");
You can change the span tag to run at the server, so the ViewState will persiste the value after the postback.
<span id="totalChars" runat="server">0</span> characters
on the submit button "OnClientClick" event you can call a javascript function.
save the character count in the session.
after page loads completely assign the value stored in session to the span.
you should create a session variable before only to make use of it.
eg. function setVar(){ alert("Testing"); <% Session("TempVar") = "setVar Test" %> }

Categories