javascript, how to get html to persist after button click - javascript

Every time i click my HTML button the values are filled in for a brief flash and then disappear. want my variables to stay after the button is clicked. I I have tried putting the .innerHTML outside of the button click and altering just the variables in the js function. not sure what to do here. thanks.
HTML:
< button id="evaluteScoreButton">Evaluate Scores</button >
js:
document.getElementById("evaluteScoreButton").onclick = function evaluateGrades() {
window.document.getElementById('dsumm').innerHTML = arrayAverage(discussionArray());
window.document.getElementById('tsumm').innerHTML = arrayAverage(testArray());
window.document.getElementById('asumm').innerHTML = arrayAverage(assignmentArray());
var totalAverage = findTotalAverage();
window.document.getElementById('totalAverage').innerHTML = totalAverage;
window.document.getElementById('letterAverage').innerHTML = (findLetterGrade(totalAverage));
};

Change the button type
Instead of
<button id="evaluateScoreButton">Evaluate Scores</button>
Try
<input type="button" id="evaluateScoreButton">Evaluate Scores</input>
The reasoning behind this is that I think the <button> element is a Submit button which causes the html form to be posted. Using an <input> should avoid this

Related

Chaning text of href from script makes text vanish and not change

This is function is called when clicking a button in my page:
function LoadEnglishText()
{
document.getElementById("txt_whatwedo_learnmore2").innerHTML = "here.";
}
This is the corresponding HTML:
<a id="txt_whatwedo_learnmore2" href="./pdf/Pricing_App_Dev_2019_Ger.pdf">hier.</a>
So, upon firing the function, the text of the link should change from "hier." to "here." (from German to English), but it doesn't. When clicked on, it simply vanishes off screen.
What is it I am doing wrong?
EDIT:
The function is called like so:
<img src="./img/img_english.png" width=3%</img>
This all works on every other text but not on the link...
**********EDIT 2************
I have just realised that firefox console says that TypeError: document.getElementById(...) is null
allthough the ID is correct. This is the only instance where I am tring to change a LINK in the function. It is usually just a text element so it must be connected to this...
The reason could be that your button is of type submit, when clicking that the from is submitted and the page disappears. You can either prevent the default event using Event.preventDefault() or specify the button type as button.
Please Note: It is better to use textContent or innerText when the content is plain text.
function LoadEnglishText(e){
document.getElementById("txt_whatwedo_learnmore2").textContent = "here.";
}
<a id="txt_whatwedo_learnmore2" href="./pdf/Pricing_App_Dev_2019_Ger.pdf">hier.</a>
<button type="button" onclick="LoadEnglishText()">Change Text</button>
Using Event.preventDefault()
function LoadEnglishText(e){
document.getElementById("txt_whatwedo_learnmore2").textContent = "here.";
e.preventDefault();
}
<a id="txt_whatwedo_learnmore2" href="./pdf/Pricing_App_Dev_2019_Ger.pdf">hier.</a>
<button onclick="LoadEnglishText(event)">Change Text</button>
You need to prevent the reload of the link with event.preventDefault
like :
function LoadEnglishText(e) {
e.preventDefault();
document.getElementById("txt_whatwedo_learnmore2").innerText = "here.";
}
<img src="./img/img_english.png"></img>
Note: use .innerText if you push text only.
You need to call function using parenthesis() onclick="LoadEnglishText()".
A working demo:
function LoadEnglishText(e) {
e.preventDefault();
document.getElementById("txt_whatwedo_learnmore2").innerHTML = "here.";
}
<a id="txt_whatwedo_learnmore2" onclick="LoadEnglishText(event)">hier.</a>

How to store JS slideToggle in localStorage only for clicked button

I have several buttons including divs which they have the same name. unfortunately I can not change the names, they are generated by cms.
So for example when I click only on first button, only the first div is hidden or displayed, and that's fine.
But after refresh page it opens or closes all divs depending is the first div closed or opened, and that I do not want it.
here is the code:
<button class="a">Button</button>
<div class="target"></div>
<button class="a">Button</button>
<div class="target"></div>
$('.a').click(function() {
$(this).next(".target").slideToggle(function() {
localStorage.setItem('visible', $(this).is(":visible"));
});
});
$('.target').toggle(localStorage.getItem('visible') === 'true');
here you can see jsfiddle example: https://jsfiddle.net/pj3gs0z9/3/
So my question is, is it possible to store only clicked button information, and after page refresh display or hide div from only clicked button ?
Thank you
It is possible, but probably not in your case. If you tell us you can't change your button properties, and they are exactly the same, then you won't be able to store different data in your localStorage.
Isn't there any way where you can add some additional information to your button ? It could be a class, an id, a name, or even a data-XXX attribute.
By the way, how are your buttons generated ? are they hard coded, or fetched from a database, or ... ?
EDIT
Here is a way of adding different classes to all of your buttons (althoguh I recommend adding data attributes, but whatever floats your boat) :
let buttons = document.getElementsByTagName('button'); // Array of your buttons
let index = 0;
for (let button of buttons) {
button.className += 'myCustomClass-' + ++index; // Add a custom class to your buttons
}
// Now in your local storage, you can store the class of the button !
EDIT 2 I would store it like this :
// On click, in VanillaJS (sorry, haven't used JQuery in a while)
button.onclick = () => {
let visibleButtons = localStorage.getItem('visible-buttons') || [];
visibleButtons.push(button.className.match(/(myCustomClass-[0-9]*)/)[0]);
}
This is one quick solution, but because of a slideToggle you gonna have a small flash of milliseconds of a visible div unless you first have them hidden and then based on localStorage display them.
$('.a').click(function() {
$(this).next(".target").slideToggle(function() {
localStorage.setItem('visible-' + $(this).index(), $(this).is(":visible"));
});
});
$.each($('.target'), function(k, trg) {
$(trg).toggle(localStorage.getItem('visible-' + $(trg).index()) === 'true');
});

From JQuery to Javascript code

I have this div
<div id="lk_37" class="lk_link" style="display: inline-block">
TADE
</div>
And i want to make one script to check if the button_37 is clicked
and if is clicked to go on, if its unclicked then the script should click it.
Also we have a page with different id's of buttons and we want to check them all and click what is unclicked with this particular button.
when the button is clicked the "TADE" is turning on "DTT" this is what i want to check if its clicked or unclicked. we click "TADE" with this class="lk_button_37 lk_post" and its turning on to "DTT" with the same class="lk_button_37 lk_post" as before. so we want to check if "TADE" is on we want the button to be clicked, and if "DTT" is on we want to override it.
The JQuery code for doing this is
$('.lk_button_37:contains(TADE)').click();
And i want to convert this to javascript code for chrome extension.
I've already made up this
var el = document.getElementsByClassName('lk_button_37');
for (var i=0;i<el.length; i++)
{
el[i].click();
}
But i dont know how to make the code click ONLY the "TADE" button.
Any help would be appreciated. Thanks!
Just check the content of the element
var el = document.getElementsByClassName('lk_button_37');
for (var i=0;i<el.length; i++) {
if ( el[i].innerHTML.indexOf('TADE') != -1 ) {
el[i].click();
}
}

Javascript getElementById value setting getting reset on function return

I have a simple function to show / hide a div element. I have a javascript function to do that. I debugged this with Opera. The function sets the hidden value properly on the div element. I can see the div element disappear. However, when the function returns the div element reappears. The javascript function is in its own file:main.js:
function showhide(name){
var elem = document.getElementById(name) ;
if( elem.hidden == false ) {
document.getElementById(name).hidden = true ;
} else {
document.getElementById(name).hidden = false ;
}
}
The Html is:
<div class=wrap><p>
<div class=sidebar>
<FORM><input type="submit" value="Toggle" onclick="showhide('specname');"/></FORM></div>
<div class=main>main Div
<div id="specname">collapsible text</div></div></p></div>.
I have set debugging breakpoints in the javascript function showhide to see that the value is being set properly. But on function return, the value is reset.
It is probably something simple I am missing but can't seem to see it? Any ideas? Thanks!
The answers solved my problem. I was missing the fact that the submit repainted the page and I lost my changes. I changed the type=submit to type=button. And I removed the form to just an input element with type button. That worked very nicely. Thanks everyone for your help!!! I really appreciate your answers!
The following wont do anything in some browsers:
document.getElementById(name).hidden = true
change it to
document.getElementById(name).style.display = 'block' // and 'none' for the matching line
does that make it do what you need?
As others have pointed at, it is also submitting the page - either use a different element or change the function to start :
function showHide(e, name) {
e.preventDefault();
//do the toggle here
return false;
}
The problem is you are using a submit control which will submit to the server and refresh the page. You want to stop the submit or change the control type. Both of the following should work. I recommend the 2nd one.
Try this
<FORM><input type="submit" value="Toggle" onclick="showhide('specname'); return false;"/>
or this
<input type="button" value="Toggle" onclick="showhide('specname');"/>
Probably because when you click the button the form submits and it refreshes the page ?
You should not be using a form just to have a button that does something. Instead, try using
<button onClick="showhide('specname');">Toggle</button> (and get rid of the form entirely)
Try this for your showhide().
function showhide(name){
var elem = document.getElementById(name);
(elem.style.visibility == 'hidden'?elem.style.visibility = 'visible':elem.style.visibility = 'hidden');
}
OR similarly:
function showhide(name){
var elem = document.getElementById(name);
(elem.style.display== 'none'?elem.style.display= 'inline':elem.style.display= 'none');
}
Maybe try them both and see which you need.
Cheers.

how to alert user when there are changes inside an object field

how can i alert the user if there are any changes inside the object field
i''m trying to detect the changes on this div inside the object
if it's normal the code would be this:
<div id="HeaderNewMessageIcon" class="BrosixContactNewMessage" style="display:none;">
</div>
but if there are changes it will look like this:
<div id="HeaderNewMessageIcon" class="BrosixContactNewMessage" style="display: block; ">
</div>
i want to alert the user if there are changes inside the object, either via alert or using an image.
is there any way for me to achieve this?
and another thing, i have no access to the code inside the object, i can only view it but not edit it.
I believe there must be some JavaScript code which changing your html you can call your method from there. Other way you can use setInterval.
You can use jQuery plugin Mutation Events plugin for jQuery . see thread
var a = document.getElementsByClassName('HeaderNewMessageIcon')[0];
var oldTitle = a.title;
setInterval(function(){
if(a.title !== oldTitle){
alert("Title change");
oldTitle = a.title;
}
},100);
jsfiddle
You have to detect the changes when throught user interaction such as click, mouseover, mousedown, etc... then you can attach a function to see if its attributes or anything inside it changes.
//detect inputs change
$('#HeaderNewMessageIcon').find(':input').change(function(){ alert(...)});
//detect attributes change
$('#HeaderNewMessageIcon').click(function(){
detectChange(this);
});
As for detectChange to work, you must save the attributes when page just loaded
var attrs = $('#HeaderNewMessageIcon').get(0).attributes;
function detectChange(obj){
//pseudo-code, you need to find a function on the web to commpare 2 objetcs
if (obj.attributes === attrs){
alert(...);
}
//the same comparison for the children elements $(obj).children()
}

Categories

Resources