This question already has answers here:
Completely lost on how to save extension popup window content
(2 answers)
Closed 6 years ago.
I have this piece of code(thanks to Shah Abax Khan), and I wanted to make it a Chrome extension. I wrote a settings/options page, but it doesn't actually save the settings. Help?
Javascript:
var pretty_fied = false;
var isOn = localStorage.isOn;
var isCapFirst = localStorage.isCapFirst;
var firstLetterPerWord = localStorage.firstLetterPerWord;
function yay() {
if ($("#on").value == "on") {
isOn = true;
localStorage["isOn"] = true;
}
else {
isOn = false;
localStorage["isOn"] = false;
}
if ($("#first").value == "on") {
isCapFirst = true;
localStorage["isCapFirst"] = true;
}
else {
isCapFirst = false;
localStorage["isCapFirst"] = false;
}
if ($("#per").value == "on") {
firstLetterPerWord = true;
localStorage["firstLetterPerWord"] = true;
}
else {
firstLetterPerWord = false;
localStorage["firstLetterPerWord"] = false;
}
};
$('input, textarea').keyup(function () {
alert(isOn);
if (isOn) {
prev = true;
var value = $(this).val();
var altText = '';
for (num = 0; num < value.length; num++) {
if (num % 2 == 0)
altText += value[num].toUpperCase();
else
altText += value[num].toLowerCase();
}
$(this).val(altText);
}
});
And here's the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Y.A.Y | Options</title>
<script type="text/javascript" src="/js/caps.js"></script>
</head>
<body>
<h1>Settings</h1>
<form>
<label>Enabled: </label>
<select id="on">
<option value="on">Yes</option>
<option value="off">No</option>
</select>
</br>
<label>First Letter:</label>
<select id="first">
<option value="on">Capital</option>
<option value="off">Lowercase</option>
</select>
</br>
<label>Change First Letter of Each </label>
<select id="per">
<option value="on">Word</option>
<option value="off">Sentence</option>
</select>
<button id="done" onclick="yay()">Save</button>
</form>
</body>
</html>
yay() is supposed to save the settings, but it doesn't.
In Chrome Extension you shouldn't use a LocalStorage. It's for websites.
Use Chrome Storage instead like this:
JavaScript:
var pretty_fied = false;
var isOn;
var isCapFirst;
var firstLetterPerWord;
getData()
function getData() {
chrome.storage.sync.get( function ( data ) {
isOn = data.isOn;
isCapFirst = data.isCapFirst;
firstLetterPerWord = data.firstLetterPerWord;
} )
}
function yay() {
isOn = $("#on").value == "on";
isCapFirst = $("#first").value == "on";
firstLetterPerWord = $("#per").value == "on";
chrome.storage.sync.set( {
isOn: isOn,
isCapFirst: isCapFirst,
firstLetterPerWord: firstLetterPerWord
} )
}
Related
There is a email field where in if we access the site using chrome/IE/Firefox browser it works as expected, But if I access it using IPhone Safari browser the email field reverse the text I entered.
Example image here-
The code for the field Email is
<input
id="emal"
required
type="text"
maxlength="40"
onclick="this.focus();"
onfocus="if(this.value == this.dflt) { this.value='' }; this.onchange();"
onblur="if(this.value.length < 1) { this.value = this.dflt };"
onchange="this.ffoc = true; validate_email();"
onpaste="this.onchange();" oninput="this.onchange();"
onkeypress="this.onchange();">
Validation part of code -
function validate_email() {
if (document.loaded) {
$form[0].$emal.value = "";
$form[0].$emal.valid = null;
updateField($form[1].$emal, $form[1].$emal.value.replace(/\s/ig, ""));
if (isValidEmail($form[1].$emal.value) && $form[1].$emal.value != $form[
1].$emal.dflt) {
$form[0].$emal.value = $form[1].$emal.value;
$form[0].$emal.valid = true;
$form[1].$emal.setAttribute("valid", "true");
} else {
$form[1].$emal.setAttribute("valid", ($form[1].$emal.clik) ? ($form[
1].$emal.required) ? "false" : "warn" : "");
$form[0].$emal.valid = ($form[1].$emal.clik && !$form[1].$emal
.required) ? true : null;
}
$form[1].$emal.$wbox.style.display = ((/false|warn/i).test($form[1]
.$emal.getAttribute("valid"))) ? "block" : "none";
refresh();
}
}
function isValidEmail(str) {
var val = false;
if (str != null) {
var ddStr =
"aero%asia%biz%cat%com%coop%edu%gov%info%int%jobs%mil%mobi%museum%name%net%org%pro%tel%travel%ac%ad%ae%af%ag%cf%cg%ai%al%am%an%ao%aq%ar%as%at%au%aw%ax%az%ba%bb%bd%be%bf%bg%bh%bi%bj%bm%bn%bo%br%bs%bt%bv%bw%by%bz%ca%cc%cd%ch%ci%ck%cl%cm%cn%co%cr%cs%cu%cv%cx%cy%cz%dd%de%dj%dk%dm%do%dz%ec%ee%eg%eh%er%es%et%eu%fi%fj%fk%fm%fo%fr%ga%gb%gd%ge%gf%gg%gh%gi%gl%gm%gn%gp%gq%gr%gs%gt%gu%gw%gy%hk%hm%hn%hr%ht%hu%id%ie%il%im%in%io%iq%ir%is%it%je%jm%jo%jp%ke%kg%kh%ki%km%kn%kp%kr%kw%ky%kz%la%lb%lc%li%lk%lr%ls%lt%lu%lv%ly%ma%mc%md%me%mg%mh%mk%ml%mm%mn%mo%mp%mq%mr%ms%mt%mu%mv%mw%mx%my%mz%na%nc%ne%nf%ng%ni%nl%no%np%nr%nu%nz%om%pa%pe%pf%pg%ph%pk%pl%pm%pn%pr%ps%pt%pw%py%qa%re%ro%rs%ru%tw%tz%ua%ug%uk%us%uy%uz%va%vc%ve%vg%vi%vn%vu%wf%ws%ye%yt%yu%za%zm%zw",
ckStr = (ddStr).split("%");
if (str.length > 5 && (
/^\w+([\.\-\'\+]?\w+)*#\w+([\.\-]?\w+)*(\.\w+)+$/i).test(str)) {
for (var i = 0; i < ckStr.length; i++) {
if (str.substring(str.lastIndexOf(".") + 1) == ckStr[i]) {
val = true;
break;
}
}
}
}
return val
}
I really appreciate helping me sorting this or providing any references.
We have three checkboxes as Left, Right, Both.
When selecting Left and Right, Both should be disabled.
However, on checking the right and left; checkbox for Both is not disabling. (or) alert('Hello 1') is not firing.
document.getElementById('Left').disabled = false;
var isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
var isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
var isBoth = document.getElementById('Both').checked;
if (isLeft == true && isRight == true)
{
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
Below is the original code in my JavaScript file
if ($("input:radio[name='Swelling']:checked").length > 0) {
var isChecked = document.getElementById("SwellingYes").checked;
if (isChecked === true)
{
document.getElementById('Left').disabled = false;
let isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
let isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
let isBoth = document.getElementById('Both').checked;
if (isLeft && isRight) {
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
if (isBoth) {
document.getElementById('Left').checked = false;
document.getElementById('Right').checked = false;
document.getElementById('Left').disabled = true;
document.getElementById('Right').disabled = true;
}
}
}
You need to listen on each checkbox's change event, then run your code, like so:
document.addEventListener('DOMContentLoaded', function () {
Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]')).forEach(function (checkbox) {
checkbox.addEventListener('change', function () {
document.getElementById('Left').disabled = false;
var isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
var isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
var isBoth = document.getElementById('Both').checked;
if (isLeft == true && isRight == true) {
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
});
});
});
Left:
<input type="checkbox" id="Left" />
Right:
<input type="checkbox" id="Right" />
Both:
<input type="checkbox" id="Both" />
If you are only supporting modern browsers, you can use a bit of syntactic sugar here as well:
document.addEventListener('DOMContentLoaded', () => {
[...document.querySelectorAll('input[type="checkbox"]')].forEach((checkbox) => {
checkbox.addEventListener('change', () => {
document.getElementById('Left').disabled = false;
let isLeft = document.getElementById('Left').checked;
document.getElementById('Right').disabled = false;
let isRight = document.getElementById('Right').checked;
document.getElementById('Both').disabled = false;
let isBoth = document.getElementById('Both').checked;
if (isLeft == true && isRight == true) {
alert('Hello 1');
document.getElementById('Both').checked = false;
document.getElementById('Both').disabled = true;
}
});
});
});
Left:
<input type="checkbox" id="Left" />
Right:
<input type="checkbox" id="Right" />
Both:
<input type="checkbox" id="Both" />
If you wanted to also disable Left and Right, when Both were checked, you could do that, furthermore, it would be wise to not keep querying the dom for your elements, and rather store them inside variables:
document.addEventListener('DOMContentLoaded', () => {
let leftBox = document.getElementById('Left');
let rightBox = document.getElementById('Right');
let bothBox = document.getElementById('Both');
[...document.querySelectorAll('input[type="checkbox"]')].forEach((checkbox) => {
checkbox.addEventListener('change', () => {
leftBox.disabled = false;
let isLeft = leftBox.checked;
rightBox.disabled = false;
let isRight = rightBox.checked;
bothBox.disabled = false;
let isBoth = bothBox.checked;
if (isLeft && isRight) {
bothBox.checked = false;
bothBox.disabled = true;
}
if (isBoth) {
leftBox.checked = false;
rightBox.checked = false;
leftBox.disabled = true;
rightBox.disabled = true;
}
});
});
});
Left:
<input type="checkbox" id="Left" />
Right:
<input type="checkbox" id="Right" />
Both:
<input type="checkbox" id="Both" />
I'm not sure if this should be a comment or not, but your code only checks to see if it's checked or not once, on page load. If you want it to work properly, you may want to have an event attached or add a loop?
I think so there is a problem with for statement??
Adjusted code again, but not alert popup is all the time even if all the input fields got values?
Hello I am trying to validate a dynamic array of fields on a form:
<form onsubmit="return checkReq();">
<input value="" type="hidden" name="slider[]" id=""/>
</form>
with the following JavaScript, but it doesn't work? Could you tell me please what I am doing wrong.
<script language="javascript">
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
</script>
I think this might help.
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
You always return after the first loop, so it doesn't go through each element (and thus redundant), is this intended?
Try this
You are trying to compare element instead of it's value JSFIDDLE
function checkReq () {
var boxes = document.getElementsByName("slider[]");
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
alert('Problem'); return false;
}
else {return true;}
}
}
I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}
I have a check box which will change the value of a textfield to 1 when checked and change it back to zero when unchecked, how can I do this? I want it in javascript.
<input type="checkbox" name="foo" onclick="document.getElementById('idtextfield').value = +this.checked;" />
You can do like this:
var chk = document.getElementById('checkbox_id');
var txt = document.getElementById('textbox_id');
chk.onclick = function(){
if (this.checked === true){
txt.value = '1';
}
else{
txt.value = '0';
}
};
window.onload = function() {
var checkBox = document.getElementById('idofcheck');
if (checkBox == null) {
return;
}
checkBox.onclick = function() {
var textField = document.getElementByd('ifoftextfield');
if (textField == null) {
return;
}
if (this.checked) {
textField.value = '1';
} else {
textField.value = '0';
}
};
};
if(document.getElementById("checkbox1").checked)
{
document.getElementById('textbox1').value=1;
}
else
{
document.getElementById('textbox1').value='';
}