LocalStorage with Userscript on Chrome - javascript

I badly need someway to store data within an edited DOM of a page, and then access it from the userscript. Also, I need this to be done on Google Chrome.
This is my current script, but I can't get it working:
The internal script:
var o_shout_tabs=unsafeWindow.localStorage.getItem('va_shout_tabs')||true;
var o_profile_damage=unsafeWindow.localStorage.getItem('va_profile_damage')||true;
var o_allies=unsafeWindow.localStorage.getItem('va_allies')||true;
The edited DOM:
<script type="text/javascript">
function saveData(a,b){
var unsafeWindow=this['unsafeWindow']||window;
unsafeWindow.localStorage.setItem('va_'+a,b);
}
</script>
<input type="checkbox" value="1" onclick="saveData('shout_tabs', this.checked)"/>
<input type="checkbox" value="1" onclick="saveData('profile_damage', this.checked)"/>
<input type="checkbox" value="1" onclick="saveData('allies', this.checked)"/>
However, this always returns false when I test with for example o_shout_tabs==true, no matter the input (although, if it hasn't received an input at all, it returns true).

What always returns false?
Anyway, the init logic is off. For boolean values, code like this:
var o_shout_tabs=unsafeWindow.localStorage.getItem('va_shout_tabs')||true;
will always return true or a string.
Use this code:
function getBoolFromStorageDefaultTrue (varName) {
var val = localStorage.getItem (varName);
if (val == null)
return true;
return ( (val == "false") ? false : true );
}
var o_shout_tabs = getBoolFromStorageDefaultTrue ('va_shout_tabs');
var o_profile_damage = getBoolFromStorageDefaultTrue ('va_profile_damage');
var o_allies = getBoolFromStorageDefaultTrue ('va_allies');

Related

Javascript function does not work on onclick of checkbox

I try to call a Javascript function through an onclick attribute of a checkbox.
The js should show another checkbox if the first one is checked etc.
Now the function isnt working. I tried to use just an alert() for testing without any result...
Fitness:<input type="checkbox" id="fitnessCheck" onclick="checkFunction()">
Beauty:<input type="checkbox" id="beautyCheck">
Streetwear:<input type="checkbox" id="streetwearCheck">
Luxus:<input type="checkbox" id="luxusCheck" onClick="checkFunction()">
Datenschutz: <input style="display:none" type="checkbox" id="datenschutzCheck">
<script>
checkFunction(){
//get Checkboxes
var fitnessCheckbox = document.getElementById("fitnessCheck");
var beautyCheckbox = document.getElementById("beautyCheck");
var streetwearCheckbox = document.getElementById("streetwearCheck");
var luxusCheckbox = document.getElementById("luxusCheck");
var datenschutzCheckbox = document.getElementById("datenschutzCheck");
if(fitnessCheckbox.checked == true || beautyCheckbox.checked == true || streetwearCheckbox.checked == true || luxusCheckbox.checked == true){
datenschutzCheckbox.style.display ="block";
}
}</script>
You have to declare the function checkFunction().
You can do it in many ways such as:
function checkFunction() {
// code here
}
or
var checkFunction = function() {
// code here
}
etc, depending on how you are going to use the function.
This is how to define a function in JavaScript.
Correct your function as below;
function checkFunction(){
}
Alternatively, remove the onclick attribute from HTML and put it in the JavaScript as defined below
var fitnessCheckbox = document.getElementById("fitnessCheck");
fitnessCheckbox.onclick() = function() {
// access properties using this keyword
if ( this.checked ) {
// if checked ...
alert( this.value );
} else {
// if not checked ...
}

checkbox onclick wont change checked via jscript

I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}

Uncaught TypeError: Cannot read property 'value' of null, Element does exist

Before you downvote, I've read a lot of questions and it didn't help me.
My Javascript's alert returns null even when there is a value in the input type.
Here's the code :-
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
</script>
<input type="hidden" name="p0002" id="p0002" value="1" >
<input type="hidden" name="p0003" id="p0003" value="0" >
<input type="hidden" name="p0004" id="p0004" value="2" >
It always returns null. The error in console says :
Uncaught TypeError: Cannot read property 'value' of null
Trying to fix it since last 1 hour. What is wrong here?
Wrap your JavaScript in window.onload. Currently your JavaScript is executing before the element exists:
<script>
window.onload = function () {
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
}
</script>
Another thing you can do is move the script tag to be after the elements you're referencing:
<input type="hidden" name="p0002" id="p0002" value="1" >
<input type="hidden" name="p0003" id="p0003" value="0" >
<input type="hidden" name="p0004" id="p0004" value="2" >
<script>
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
}
else {
var str = null;
}
alert(str);
</script>
Your script should be excuted after inputs being added to DOM. The most crossbrowser way to make your script work, is to move it just before your <body> tag is closed, and wrap it into an immediate function:
<script>
(function() {
if (document.getElementById('p0002') != null) {
var str = document.getElementById("p0002").value;
} else {
var str = null;
}
alert(str);
})();
</script>
</body>
This is faster to execute than an onload handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.
Here your script should be after html.

Tricky Javascript logic with Objects, Array and Booleans

I am having a lot of issue trying to figure out this logic. Let me set the stage here:
In the HTML there are some form/input elements type radio. Each of them have an ID assigned to it.
<form>
<input type="radio" name="oneAllowed" id="yesterday" />
<input type="radio" name="oneAllowed" id="today" />
<input type="radio" name="oneAllowed" id="tomorrow" />
</form>
Using Javascript essentially what I am trying to do is loop through the 3 objects, since they all have same name assigned within HTML only a single one can be selected, whichever one is returning true I want grab hold of that result then access the second key:value pair, for example for 'commitYesterday' it would be 'commitYesterday.hasValue();' and dispatch that to a different function for other calculation.
var urgentOrderSelector = function(){
var commitYesterday = {
isChecked: document.getElementById("yesterday").checked,
hasValue: function(){
if (this.isChecked == true) {
return 3;
};
};
};
var commitToday = {
isChecked: document.getElementById("today").checked,
hasValue: function(){
if (this.isChecked == true) {
return 2;
};
};
};
var commitTomorrow = {
isChecked: document.getElementById("tomorrow").checked,
hasValue: function(){
if (this.isChecked == true) {
return 1;
};
};
};
var urgentArray = [commitYesterday.isChecked, commitToday.isChecked, commitTomorrow.isChecked];
for(var i = 0; i <= urgentArray.length-1; i++){
if (urgentArray[i].isChecked == true) {
//This is where I am stuck. I was thinking of doing perhaps the following:
return urgentArray[i].hasValue();
};
}
};
Why don't you change your HTML to this:
<form>
<input type="radio" name="oneAllowed" id="yesterday" value="3" />
<input type="radio" name="oneAllowed" id="today" value="2" />
<input type="radio" name="oneAllowed" id="tomorrow" value="1" />
</form>
And use document.querySelector to get the selected elements:
document.querySelector('[type="radio"][name="oneAllowed"]:checked').value
If you actually need to run specific functions dependend on which radio box is checked you could add an attribute data-fn="fnName" to each input and then create an object with the keys as functions:
var fns = {'fnName1': function () {}, 'fnName2': function() {} …};
And then call the function defined by the Attribute:
fns[document.querySelector('[type="radio"][name="oneAllowed"]:checked').getAttribute('data-fn')]();
Not exactly sure what your end goal is.
But here's a more minified version of your logic. Hope it helps.
var urgentOrderSelector = function(){
var radioDict = {'yesterday':3, 'today':2, 'tomorrow':1};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')];
};
Alternatively, if you wanted to execute some function based on the selection, you could store the function pointers and execute them accordingly, ie:
var funcYesterday = function(){alert('yesterday');};
var funcToday = function(){alert('today');};
var funcTomorrow = function(){alert('tomorrow');};
var funcUrgentOrder = function(){
var radioDict = {
'yesterday' : funcYesterday,
'today' : funcToday,
'tomorrow' : funcTomorrow
};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')]();
};
Or, much simpler, since you are using the 'value' property on your radios:
function urgentOrderSelector = function() {
return $('input[name=oneAllowed]:checked').val();
};

Why does the order of Boolean values affect this program?

I created a basic program where user input is turned into an alert on submission. I can't figure out why the program only works as intended if I use false rather than true as the first condition in my if/else statement. I'm sure this is very basic but I've failed to find anything of relevance. After a long search I decided to post the question. Any answers will be greatly appreciated.
The HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
The broken script:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The working script:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The variable input will never be equal to the boolean true because it is a string. Try changing it to:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}
To clarify ferd tomale's answer, it's one of the "weird" type conversion cases where a check on equality to true does not behave in the same way as check on equality to false.
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
You can switch to using typesafe comparison operators (===, !==), which behave much more predictable, but then you'll have to convert values to the correct type yourself. Or you can learn the quirks of JS's automatic type conversion when you use == or !=.
Because your input is a string. And string == true will be false.
You can set breakpoints to check them.

Categories

Resources