Submitting Forms in Chrome Extension - javascript

I'm trying to have a form in my chrome extension popup that has its data processed by js when it's submitted. However, without any errors, nothing happens on submission.
manifest.json
"action":{
"default_popup": "index.html"
},
"background": {
"service_workers": ["app.js"]
}
index.html
<!doctype html>
<html>
<body>
<form id="form">
<input id="grade" type="text" placeholder="grade">
<input id="score" type="text" placeholder="score">
<input type="submit" value="Save">
</form>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function () {
var form = document.getElementById("form")
form.addEventListener('submit', function(e){
var grade = document.getElementById("grade").value
var score = document.getElementById("score").value
alert(grade)
chrome.storage.sync.set({grade: grade})
chrome.storage.sync.get(['grade'], function(result) {
console.log('Value currently is ' + result.key);
});
})
})
Is this happening because I don't include the <script src="app.js"> tag? Chrome gives an error if any script tags are inside the html of the popup.
document.addEventListener('DOMContentLoaded', function() {
var form = document.getElementById("form");
form.addEventListener('submit', function(e) {
e.preventDefault();
var grade = document.getElementById("grade").value;
var score = document.getElementById("score").value;
console.log(grade);
// chrome.storage.sync.set({grade: grade});
// chrome.storage.sync.get(['grade'], function(result) {
// console.log('Value currently is ' + result.key);
// });
});
});
<form id="form">
<input id="grade" type="text" placeholder="grade">
<input id="score" type="text" placeholder="score">
<input type="submit" value="Save">
</form>

Related

Is LocalStorage variable exists: if statement does not work after element reloading (page is reloading after submiting reloaded form)

Please help to fix an algorithm and prevent reloading after clicking submit:
my website has to check, does user ever entered a nickname. If he did, then website have to show his name, if did not, then ask to type it. If the user decided to change it, he will click "reset username".
After clicking "reset" user has to submit twice his name (after first click on "Set" total page is reloading, and after second click it is reloading only one element). Please help to fix it - user has to submit it only once.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var formNewName = '<form id="new-task"> <input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text"> <input id="submitname" type="submit" value="Set new name1"> </form>';
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#setnewname').onsubmit = () => {
var newname;
localStorage.setItem('localN', newname);
document.querySelector('#nickName').innerHTML = formNewName;
// Stop form from submitting
return false;
};
});
// Checking does user entered his name
if ( !localStorage.getItem('localN') || localStorage.getItem('localN')=="undefined" )
{ var nick;
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = formNewName;
document.querySelector('#new-task').onsubmit = () => {
nick = document.querySelector('#nickN').value;
localStorage.setItem('localN', nick);
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
// Stop form from submitting
return false;
};
});
}
else
{
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
});
}
</script>
</head>
<body>
<div id = "nickName"></div>
<div id = "newname">
<br>
<form id="setnewname">
<input id="submitreset" type="submit" value="Reset nick name">
</form>
</div>
</body>
Update: event.preventDefault(); and event.stopPropagation(); does not helps to solve the problem.
Sorry for late reply if you are still having it, i couldn't see where you are taking the value from user in your code there's no input field where user can type so i'll add that and then on id submitreset you'll do this:
i work with jquery most so the syntax for that will be
// HTML CODE TO ADD
<input type="text" name="entername" id="entername">
// than in jquery for the submit button you already have
$(document).on("click","#submitreset",function(e){
e.preventDefaults();
var name = $(this).val();
// you can print the value in the div with this id
$("#nickName").html(name);
});
In a Russian language branch of StackOverflow I had received an answer (https://ru.stackoverflow.com/a/901260/291735):
HTML
<div id = "nickName">
<form id="new-task">
<input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text">
<input id="submitname" type="submit" value="Set new name1"> </form>
</div>
<div id = "newname">
<br>
<form id="setnewname">
<input id="submitreset" type="submit" value="Reset nick name">
</form>
</div>
JavaScript
var setName = document.getElementById('submitname');
var reset = document.getElementById('submitreset');
var nickN = document.getElementById('nickN');
document.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('localN')!== null){
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>'
}
})
setName.addEventListener('click', function(){
var newName = document.getElementById('nickN').value;
localStorage.setItem('localN', newName);
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>'
})
reset.addEventListener('click', function(){
delete localStorage['localN'];
document.querySelector('#nickName').innerHTML = '<input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text"> <input id="submitname" type="submit" value="Set new name1">'
});

Accessing HTML service form object

I'm working through https://developers.google.com/apps-script/guides/html/communication trying to submit a form with info loaded from a google sheet. On the client side I have (Based heavily on the form example in the article) :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
// window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
// function updateUrl(url) {
// var div = document.getElementById('output');
// div.innerHTML = 'Got it!';
// }
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<div>
<select id="optionList" name="email">
<option>Loading...</option>
</select>
</div>
<br>
<div>
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>
</div>
<input type="submit" value="Submit" />
</form>
On the server side (code.gs) I have:
function processForm(formObject) {
Logger.log('in here');
var formBlob = formObject.myFile;
var driveFile = DriveApp.createFile(formBlob);
return driveFile.getUrl();
}
I can see that the submit is working because I see 'in here' in the logs. How can I access the form fields from within the processForm function?
This chunk doesn't make sense to me
var formBlob = formObject.myFile;
Your form doesn't contain the input whose 'name' attribute is set to 'myFile'. Once you click 'submit', the 'formObject' variable will be:
{
email: "Loading...", //from <select id="optionList" name="email">
message: "The cat was playing in the garden." //from <textarea name="message">
}

execute javascript from popup in a caller page

i have 2 pages: A.htm and B.htm
A calls B as a popup, then after some operations B must call a javascript inside A, to do this i used the javascript: "opener".
but i think i did some mistakes because in the popup when i click the button nothing happen, here an example to download: http:\www.suale.it/prova/a.zip
this is the code of A.htm
<html>
<script language="javascript">
function ricaricapagina()
{
var theform;
if
(
window.navigator.appName.toLowerCase().indexOf("netscape") > -1) {
theform = document.forms["frmMain"];
}
else
{
theform = document.frmMain;
}
//txtOperation.value=pOperation;
theform.submit();
}
function SelectArticoli(pForm, txtOperation)
{
var sQueryString=new String;
var WinSettings = "center=yes,resizable=yes,scrollbars=yes,height=600,width=1000";
sQueryString='B.htm';
sQueryString += '?CallerForm=' + pForm;
sQueryString += '&CallerOperation=' + txtOperation;
sQueryString += '&CallerReload=1' ;
window.open(sQueryString, '', WinSettings);
}
</script>
<form name="frmMain" id="frmMain" action="A.htm" method="post">
<input name="txtOperation" type="hidden" id="txtOperation" />
<input name="cmdSelectArticoli" id="cmdSelectArticoli" onclick="javascript:SelectArticoli('frmMain', 'txtOperation');" type="button" value="Aggiungi Articoli...">
</form>
</html>
this is the code of B.htm
<html>
<script language="javascript">
function chiudipopup(pResult)
{
if (pResult==true)
{
window.opener.document.forms[frmMain].item(frmMain.txtCallerOperation.value).value = 'SelectArticoli';
if (frmMain.txtCallerReload.value != '')
{
window.opener.ricaricapagina();
}
}
window.close();
}
</script>
</script>
<form name="frmMain" method="post" id="frmMain">
<input name="txtCallerOperation" type="hidden" id="txtCallerOperation" value="txtOperation" />
<input type="submit" name="cmdConferma" onclick="javascript:chiudipopup(true);" value="conferma" id="cmdConferma" class="button" />
</form>
</html>
can you try declaring the function as window.ricaricapagina = function(){...}
You have two problem:
[B.html]=>change window.opener.document.forms[frmMain].item(frmMain.txtCallerOperation.value).value to window.opener.document.forms["frmMain"].elements["txtOperation"].value
[B.html]=>window.opener.ricaricapagina();(I'm working on it :))

Show alert (Text Field is empty) on submit Html/JavaScript

How to get an Alert on Submit when I left a TextBox empty And It Should Turn To the Next page on submit.
Must Reply,
Thank You.
You can try this :
HTML :
<form action="" method="POST" id="myForm">
<input id="myInput" type="text" />
<input type="submit" />
</form>
(Replace the action attribute by the url of your destination page, the one you call the "next page").
JS (without jQuery):
var myForm = document.querySelector('#myForm');
var myInput = document.querySelector('#myInput');
myForm.addEventListener('submit', function(pEvent) {
if(myInput.value === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
//Do whatever you want
}
});
JS (with jQuery) :
var myForm = $('#myForm');
var myInput = $('#myInput');
myForm.on('submit', function(pEvent) {
if(myInput.val() === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
}
});
Demo : http://jsfiddle.net/af9qvkmp/9/
Here is the demo, based on jQuery!
HTML
<form action="" method="POST" id="form">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
<input id="input4" type="text" />
<input id="input5" type="text" />
<input type="submit" />
</form>
JS
$(function() {
$('#form').on('submit', function(event) {
var isError = false;
$(this).find('input[type="text"]').each(function() {
if($(this).val() == '') {
console.log($(this));
isError = true;
return false;
}
});
if(isError) {
event.preventDefault();
alert("Got Error");
} else {
// Submit the form
}
});
});
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<input type="text" name="reviewValue" value="" id='starRate2' required>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>

alert box not working in jsp

I added a stylish alert box to my page, resource is here . But problem is after clicking ok, confirmsubmit.jsp is not opening. Also in that alert cancel button is not appearing why?
javascript
<form action="confirmsubmit.jsp" method="POST">
<script type="text/javascript">
<!--
function confirmation() {
var answer = csscody.alert("Confirm submit?")// added csscody here for alert but after clicking ok nothing happens
if (answer){
window.location = "confirmsubmit.jsp";
}
else{
return false;// here cancel button is not coming
}
}
//-->
</script>
</form>
html
<input type="text" name="textboxname"/>
<input type="submit" onclick="return confirmation()"/>
</form>
UPDATE
View below code ,it uses button instead of link
<form action="confirmsubmit.jsp" method="POST">
<script type="text/javascript">
$().ready(function() {
$('#btn_submit').click(function(e) {
e.preventDefault();
var that = this;
var text = "si o no compa?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
window.location = "confirmsubmit.jsp";
}
else {
return false;
}
}
})
});
});
</script>
<input type="text" name="textboxname"/>
<input type="submit" id="btn_submit" onclick="return confirmation()"/>
</form>
You willl have to use confirm instead of alert which will giv eyou both ok and cancel buttons which return true and false respectively. And also take off return from onclick
HTML
<form action = "confirmsubmit.jsp" method = "POST">
<input type = "text" name = "textboxname" />
<input type = "submit" onclick = "confirmation();" />
</form>
Javascript
function confirmation() {
var answer = confirm("Confirm submit?");
if (answer){
window.location = "confirmsubmit.jsp";
}
else{
return false;
}
}

Categories

Resources