Call checkbox value if checked from html file in javascript function - javascript

I have two files: myPage.html and myCode.gs in google scripts. I have deployed the html file as a web app, and I have figured out (with help) how to make the onclick event for the 'submit' button to trigger the emailTech function from the myCode.gs file just fine. I have also been able to insert the value from the text box in the html file into the email that is called from the onClick event.
I also have two check boxes and if checked, I would like to have their values entered into the email triggered by the onClick event. I have tried various versions of 'if checked then' statements both in the script tage of the html file and in the emailTech function but neither seem to work. Any suggestions?
myPage.html file:
<head>
<title>Test Page</title>
</head>
<body>
<form>
<input type="text" value=" " name="techEmail" />
<input type="checkbox" name="checkone" value="checkone" />Checkone
<input type="checkbox" name="checktow" value="checktwo" />Checktwo
<input type="button" onClick="formSubmit()" value="Submit" />
</form>
</body>
<script type="text/javascript">
function formSubmit() {
google.script.run.emailTech(document.forms[0]);
}
</script>
myCode.gs file:
function doGet() {
return HtmlService.createHtmlOutputFromFile('myPage');
}
function emailTech(form){
//I want something along the lines of:
//if form.checkone == "checked"{
//var checkone = "checkone"
//}
//if form.checktwo == "checked"{
//var checktwo = "checktwo"
//}
var nameBox = form.techEmail;
var message = "This is the text box value" + nameBox + checkone + checktwo;
MailApp.sendEmail("email#somewhere.com", "This is the subject", message );
}
Also, is there a way to clear the textbox and checkboxes when the submit button is clicked? I don't want to have a seperate reset button, I'd like this to reset and send the email with one click if possible. Thanks in advance!

The checkbox input shouldn't be in a self-closing tag. (That's one that ends with />.) You also need to align your value setting with what you'll look for in your handler ('checked'). Change your html like this:
<input type="checkbox" name="checkone" value="checked" >Checkone
<input type="checkbox" name="checktow" value="checked" >Checktwo
Now in your server-side handler, you can just check for the presence of 'checkone' and/or 'checktwo', because they will only be delivered in the event when checked. You can alternatively check the value, as you were planning to.
Just remove the comments from your "wish", fix the syntax, and you're good!

Related

Button not opening another HTML file after clicking check box

I have been trying to get my Terms and Service conditions HTML page to have a checkbox with a button that opens the next page (another HTML page) only if check box is checked. When I check the check box the continue button doesn't load next page. Even if the checkbox is unchecked it does not load the next page.
<h2>Terms and Service</h2>
<div class="ex3">
My conditions and terms.................................
</div>
<script>
document.querySelector('.checkbox').checked
</script>
<form>
<input type="checkbox" class="checkbox" required>I agree to all Terms and Conditions</br>
</form>
<button onclick="other_page.html">Click</button>
Thanks for helping me out!
There are a couple of reasons why this code isn't working.
Firstly, the onclick handler doesn't work like that. It executes JavaScript code within it, so you could just redirect with a simple
<button onclick="window.location='other_page.html'">Click</button>
but you need it to be conditional. So you would call a JavaScript function to do that.
var redirectIfClicked = function () {
// check if the checkbox is checked
var isChecked = document.querySelector('.checkbox').checked
// If it is then we can redirect using window.location
if (isChecked) {
window.location = 'other_page.html'
} else {
// it isnt checked so don't do anything (or do something else)
console.log('Dont do anything')
}
}
<h2>Terms and Service</h2>
<div class="ex3">
My conditions and terms.................................
</div>
<form>
<input type="checkbox" class="checkbox" required />I agree to all Terms and Conditions
</form>
<button onclick="redirectIfClicked()">Click</button>
The code above is ran when the button is clicked. It first checks if the checkbox is checked. If it is, then it redirects to your chosen page. If it isn't then it does nothing.
Secondly, this does nothing:
<script>
document.querySelector('.checkbox').checked
</script>
This returns true or false, so your code effectively becomes
<script>
true
</script>
You aren't doing anything with this and it wouldn't work even if you did because you aren't waiting for the DOM to be loaded.

I can't get form submit to work in html / JavaScript

I have tried a bunch of different things as well as searching and googling but I just can't see how to make some very basic code work.Trying to let the user submit text input.
This code below should just change the first paragraph to say working.
<HTML>
<CENTER>
<BR>
<H1>Test</H1>
<BR>
<p id="ParaOne"></p>
<BR>
<input type="text" id="TextInput" Value="" onsubmit="Test">
<script>
var CharOne = ["name"]
function Test() {
document.getElementById("ParaOne").innerHTML = "Working";
}
document.getElementById("ParaOne").innerHTML = "Enter Name:";
</script>
</HTML>
Ideally I would able to save whatever they entered into a variable and then display the entered name but as of now I can't get anything to work. not even a basic function to update the paragraph to sy working.
There is no onsubmit event for the textbox. You can use that event on the form (which I don't see in your question). Although not required, I would also add a submit button, because that's a better design.
Also it's wasteful to assign an initial value to ParaOne in JavaScript, simply type the value inside the element.
<form onsubmit="Test();">
<p id="ParaOne">Enter Name:</p>
<input type="text" id="TextInput">
</form>
<script>
function Test() {
document.getElementById("ParaOne").innerHTML = "Working";
}
</script>
Important note: Although the code above is how you should do it, I don't really see the point. The form will be submitted immediately after changing the text of ParaOne which will reload the page and you will see the initial value again (and probably think it didn't work). It will work but very fast so nobody will really see it, so what's the point?
You can use the javascript methods onchange or onkeydown to trigger input from the input field, you don't need to submit a form. But in case you needed just that I added the example. I used jQuery instead of plain javascript to write the functions because now they practically become one-line functions.
onchange will wait for the user to press enter or for the input element to loose focus to call the function.
onkeydown will call the function on every key press.
e.preventDefault() cancels the default action of the element, which in this case is a submit action, and lets us make the decision through code whether to submit or not.
Below are some javascript/jQuery test functions and a sample HTML file so you can test out what works best for you.
EDIT: I added some examples on how to store the current value of an input field into a variable
// get the Value of input element directly into a variable
var myVariable = $('#theInput_1').val();
// myVariable will return empty string since the input element is empty
console.log('This is the starting value of the 1st input element: ' + myVariable);
// Function for onkeydown test
function testKeyDown()
{
// stored in a variable which is not available outside the function
var myVariable = $('#theInput_1').val();
$('#paraOne').text(myVariable);
// test output - $('#theInput_1').val() will return empty
console.log('This is the changed value of the 1st input element: ' + myVariable);
}
// Function for onchange test
function testOnChange()
{
$('#paraTwo').text($('#theInput_2').val());
}
// Function for submit test
$( "#submit" ).on( "click", function(e)
{
e.preventDefault(); // Prevents default action of submit
$('#paraThree').text($('#theInput_3').val());
});
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<p id="paraOne">This text will be replaced on success.</p>
<input type="text" id="theInput_1" onkeydown="testKeyDown();" size="50" value="" placeholder="onkeydown test" />
<p id="paraTwo">This text will be replaced on success.</p>
<input type="text" id="theInput_2" onchange="testOnChange();" size="50" value="" placeholder="onchange test" />
<p id="paraThree">This text will be replaced on success.</p>
<form>
<input type="text" id="theInput_3" size="50" value="" placeholder="form submit test" />
<input type="submit" id="submit" value="Submit me" />
</form>
</body>
</html>

how to click on an input filed on a web page automatically as the page loads

I am making attendance system that require attendance to be taken by bar code reader. On a page I have an input box that requires the student id to be scanned by bar code reader. But as after one attendance the page reloads, I have to click the input field again and then scan by the bar code reader. Is there a way that as when the page loads, the input field is automatically clicked, so that I just scan the student id?
I have tried the following thing but it does not work:
<body onload="myFunction()" >
<form action="daily_attendance2_b.php" method="get">
SID : <input type="number" id="box" name="roll_no"min=10000000 max=19999999 placeholder="Valid ID" >
<input type="submit">
</form>
<script>
function myFunction() {
document.getElementById("box").click();
}
</script>
</body>
Use the focus() method:
<script>
function myFunction() {
document.getElementById("box").focus();
}
</script>
Also note that placing this in a function is redundant as you've placed the code just before </body>, so you could remove the onload attribute and execute the line of code within the script block.
If browser supports autofocus attribute (IE10+, FF4+, Chrome 5+), then you can make the input to be automatically focused on page load:
<input type="number" id="box" name="roll_no"min=10000000 max=19999999 placeholder="Valid ID" autofocus >
Otherwise you can use JS to focus it:
<script>
if (document.addEventListener) document.addEventListener('DOMContentLoaded', myFunction )
else if (document.attachEvent) document.attachEvent( 'onreadystatechange', myFunction );
function myFunction() {
document.getElementById("box").focus();
}
</script>

Submit form using a hyperlink and a button

I have form and the form submission can be done by either clicking on a hyper link or on a submit button. However I want my server to realize what has been used for form submission.
Current code snippet looks like this:
<a href=javascript:{} onclick="formSubmit()";>Next</a>
<input type="button" name="search" value="Get Result" onclick = "formSubmit();">
And my formSubmit() looks like this
<script type="text/javascript">
function formSubmit()
{
document.getElementById('form1').submit();
return false;
}
Any pointers as to how to go about it.
Thanks
Use a hidden parameter in your form.
< input type="hidden" value="0" name="flag"/>
When the form is submitted using javascript change flag value to '1' in the script.
function formSubmit()
{
document.form1.flag.value="1";
document.getElementById('form1').submit();
return false;
}
in case submit button is pressed the flag = '0'.
you can get this parameter on the server to determine how the form is submitted
edit : change your button type to 'submit' or call different scripts for both actions.
Pass a value (say an int or boolean) into the function. The value passed can be used to determine the source.
you invoke the same function to submit the form,so if you want your server to realize what has been used for form submission,i think you must pass a parameter to your server
You can use event.target to get the source that triggered the event and then set a flag to pass to server. See the example below:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(e)
{
alert(e.target);
}
</script>
</head>
<p>
Click on a paragraph. An alert box will alert the element that triggered the event.</p>
<p>
<strong>Note:</strong> The target property returns the element that triggered the event, and not necessarily the eventlistener's element.</p>
This Link Click will return "javascript:{}"
<a href=javascript:{} onclick="myFunction(event)";>Next</a>
<p>
This Button Click will return "[objectHTMLInputElement]"
<input type="button" name="search" value="Get Result" onclick = "myFunction(event);">
</p>
</body>
</html>

Page Redirection

I'm working on a script where all I want it to do (right now) is redirect the user based on which button they press. Eventually it will take form input and incorporate that into the redirect, but right now I'm just trying to get the buttons to send the user off to the appropriate site. However, My redirects aren't working.
<html>
<head>
<title>
Home
</title>
</head>
<body>
<script type="text/javascript">
<!--
var textstring;
var btnWhichButton;
//Gets the text from the form
function getQ() {
textstring = document.forms['Search'].elements[0].value;
}
//Does a Google Search
function googleSearch() {
window.location ="http://www.google.com";
}
//Does a YouTube Search
function youtubeSearch() {
window.location = "http://youtube.com";
}
//Figure out which button was pressed
function whichButton() {
if (btnWhichButton.value == 'Google Search' ) {
googleSearch();
} else if (btnWhichButton.value == 'YouTube Search' ){
youtubeSearch();
}
}
//main function to run everything
function main() {
getQ();
whichButton();
}
// -->
</script>
<form name="Search" >
<input type="text" name="q" size="31" maxlength="255" value="" />
<input type="submit" value="Google Search" onclick="btnWhichButton=this; main();" />
<input type="submit" value="YouTube Search" onclick="btnWhichButton=this; main();" />
</form>
</body>
</html>
When either button is clicked, the page just reloads with ?q= appended to the url, it doesn't redirect. Any help?
You want to use a button not an input type='submit'. Your current buttons are submitting the form, not performing their onclick actions.
Or block the submit action in some way. Or you could use your functions to set the form action to the url and just let it submit.
Your scripts seem highly overcomplicated. Why not have three functions: getQ, googleSearch, and youTubeSearch? Then inside the onClick event you can call the exact function, including this.value inside the input parameters and calling getQ from inside that function? Your method seems highly inefficient. If you're going to have separate functions for each of them anyways, there's no use in going through two other functions in order to get to them.
A submit button will always submit the form without a return false at the end of the onClick event, and since the default posting method is GET, its attaching ?q= to the end of your URL because that field is blank and it's the only input field in the form.
For redirecting to new page you no need to use the big javascript function.
<html> <body>
<input type="button" value="Google Search" onclick="javascript:window.location.href='http://www.google.com'" />
<input type="button" value="You tube Search" onclick="javascript:window.location.href='http://youtube.com'" />
</body></html>
Please check whether it helps you.
Well as jasonbar says, change your input to be of type 'button' and not 'submit'. Plus, I'd rather use window.location.href instead of window.location only. I don't know possible this is good practice...happy programming.

Categories