Creating Id using javascript - javascript

I want to create staffid from three different textboxes values by getting their first letter & adding auto increment number atlast.
eg "staffname", "gender", "designation" result staffid: sgd01 & I want to auto display in the staff id textbox while staffid textbox is disabled. Here is the code below:
<input name="staffname" id="staffname" size="30" type="text" value placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
Script
function quick() {
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname');
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg;
document.getElementById('staffid').value = val;
}

You have a missing .value for var staffname. It should be
var staffname = document.getElementById('staffname').value;
Also your function needs to be called on every keyup on each of the 3 input boxes so that updated values can be processed
Here is a working sample: http://jsbin.com/vobikejejo/1/
Hope this helps :)

You can try by updating your function as below:
<script>
var num=01;
function quick() {
num+=1;
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname').value;
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg + num;
document.getElementById('staffid').value = val;
}
By default there is no value, so it is not working. Try by setting the default value.
<input name="staffname" id="staffname" size="30" type="text" value="staffname" placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
<input name="gender" id="gender" size="30" type="text" value="gender" placeholder=" Staff Name" class="formTxtInput">
<input name="desg" id="desg" size="30" type="text" value="desg" placeholder=" Staff Name"class="formTxtInput">
<input name="staffid" id="staffid" size="30" disabled="disabled" type="text" value placeholder=" Staff Name" class="formTxtInput">
YOu can view demo here 1

Related

How to pass form data to GAS

I am trying to pass data from a form into a Google Apps Script but when I press submit I am greeted by I blank screen.
Form:
<div id="nameDiv">
<form action="https://script.google.com/a/umbc.edu/macros/s/AKfycbztum1ImJZeXXYt0fFhwOAMUsB5zCsJQohrum4W7qiH/dev">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="google.script.run.nameSearch()">
</form>
</div>
Script:
function nameSearch(){
try {
var firstName = document.getElementById("fname").value
var lastName = document.getElementById("lname").value
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15]
}
}
document.getElementById('nameDiv').innerHTML =
"<center>Last Name:" + lastName + "</center>" +
"</br><center>First Name:" + firstName + "</center>"
} catch(e) {
alert(e)
}
}
I am trying to pass this data to the script so that it can use it to search a google sheet so I cannot just place the script in the html as a client side script. Any thought?
All the HTML-related methods (getElementById, innerHTML, etc.) should be in client-side script, and Apps Script methods should be in the server-side.
If I understand you correctly, you want to do the following:
When this form gets submitted, look for the row whose columns K and L match the inputted fields (indexes 10 and 11 from inputData array).
For this row, return data from columns O and P (indexes 14 and 15 from inputData array).
Write this returned data to the HTML.
If all this is correct, then you could do this:
Add an onclick event in the submit input that will fire a client-side function (a function that is declared inside the tags in the HTML). There is no need to use a for this. The HTML body could be something like this:
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
From this client-side function called clientNameSearch(), retrieve the values from fname and lname, and use these as parameters when you call a server-side function called nameSearch):
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
This server-side function iterates through all rows with content in the spreadsheet, and returns the result for the first row whose columns K and L match the inputted data:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
This result is then passed as a parameter to a client-side function called onSuccess via a success handler. This is necessary since server-side functions called by google.script.run don't return anything directly, as specified here. Then onSuccess writes the result to the HTML:
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
Full code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
</body>
<script>
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
</script>
</html>
And the Code.gs would be like:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("your-html-name");
}
I'm not sure you want to write the result to the HTML, but in any case, at this point it shouldn't be difficult to modify this so that it writes exactly what you want and where you want.
Reference:
google.script.run.myFunction(...) (any server-side function)
withSuccessHandler(function)
I hope this is of any help.
Try this:
Launch the dialog fill the text boxes and click submit. The view logs and see the next dialog.
function launchADialog() {
var html='<form><br /><input type="text" name="Name" /> Name: <br /><input type="text" name="Age" /> Age: <br />';
html+='<select name="Children" ><option value="0">None</option><option value="1">One</option><option value="2">Two</option></select> Children:<br />';
html+='<input type="button" value="Submit" onClick="google.script.run.processForm(this.parentNode);" /></form>';
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The Form");
}
function processForm(form) {
Logger.log(JSON.stringify(form));
var s=Utilities.formatString('<br />Name: %s <br />Age:%s <br />Number Of Children: %s', form.Name, form.Age, form.Children);
s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Form Data")
}

I cannot connect javascript function with html <input> tags and onclick doesn't work

Hi I am working on a website and i stumbbled across an annoying thing. I cannot, for the love of anything, get to work my form to be able to do some maths and insert them into tag.
P.S nothing works for me, even GetElementsById... or other callouts :(
<script type="text/javascript">
function price(this.form){
var amount = form.elements[1].value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = (amount/gold_price) + " M";
window.alert("price_calc");
form.elements[5].value = price_calc;
}
</script>
//this is input that i would like to get a number to work with in the function
<div>
<input type="text" id="amount" value="10" onchange="price(this.form)" onclick="price(this.form)" maxlength="4" required/>
</div>
//this is input I would like to write in in after function is done functioning :)
<input type="text" id="total_price" placeholder="Total:"/>
thanks for any help in advance.
thanks again,...
Declare your price function to receive an input parameter. Actually this.form as parameter is an invalid statement and leads to an error.
Instead pass this (inside your on* property) and select the input value.
// select #total_price
const totalPrice = document.getElementById( 'total_price' );
function price( input ) {
// Convert value to a number
var amount = +input.value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = ( amount / gold_price ) + " M";
totalPrice.value = price_calc;
}
<input type="text" id="amount" value="10" oninput="price( this )" onclick="price( this )" maxlength="4" required/>
<br>
<input type="text" id="total_price" placeholder="Total:" />
This code working:
<input type="text" value="10" oninput="price(this)" maxlength="4" />
<input type="text" id="total_price" placeholder="Total:" />
<script>
function price(el){
var amount = parseInt(el.value);
var gold_price = 0.17;
var price_calc = (amount / gold_price) + " M";
window.alert("Total: " + price_calc);
document.getElementById('total_price').value = "Total: " + price_calc;
}
</script>

JS code for autocomplete while box checked

We need to enable auto-complete on this form. Whenever the checkbox is checked, the code should automatically copy the values from Shipping Name and Shipping Zip into the Billing Name and Billing Zip. If the checkbox is unchecked, the Billing Name and Billing Zip should go blank.
HTML Code
<pre>
<form>
<fieldset>
<legend>Shipping Information</legend>
<label for ="shippingName">Name:</label>
<input type = "text" name = "shipName" id = "shippingName" required><br/>
<label for = "shippingZip">Zip code:</label>
<input type = "text" name = "shipZip" id = "shippingZip" pattern = "[0-9]{5}" required><br/>
</fieldset>
<input type="checkbox" id="same" name="same" onchange= "billingFunction()"/>
<label for = "same">Is the Billing Information the Same?</label>
<fieldset>
<legend>Billing Information</legend>
<label for ="billingName">Name:</label>
<input type = "text" name = "billName" id = "billingName" required><br/>
<label for = "billingZip">Zip code:</label>
<input type = "text" name = "billZip" id = "billingZip" pattern = "[0-9]{5}" required><br/>
</fieldset>
<input type = "submit" value = "Verify"/>
</form>
</pre>
JS Code
<pre>
function billingFunction(){
var bn, bz, sn, sz;
if (document.getElementById('same').checked){
bn = document.getElementById('billingName').text;
sn = document.getElementById('shippingName').text;
bz = document.getElementById('billingZip').text;
sz = document.getElementById('shippingZip').text;
bn = sn;
bz = sz;
}
}
</pre>
This should work:
function billingFunction(){
var bn, bz, sn, sz;
bn = document.getElementById('billingName');
bz = document.getElementById('billingZip');
if (document.getElementById('same').checked){
sn = document.getElementById('shippingName').value;
sz = document.getElementById('shippingZip').value;
bn.value = sn;
bz.value = sz;
} else {
bn.value = '';
bz.value = '';
}
}
If you can use jquery you can simplify the function like this.
$('#same').change(function(){
var name, zip;
if ($('#same').prop('checked')){
name = $('#shippingName').val();
zip = $('#shippingZip').val();
}
$('#billingName').val(name);
$('#billingZip').val(zip);
});

how to pass calculated values using javascript

the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
{ // getting the text field the values and calculated
var valueCom = document.getElementById("computer").value ;
var valueMon = document.getElementById("monitor").value ;
var valueTv = document.getElementById("tv").value ;
var valueLap = document.getElementById("laptop").value ;
var valueCel = document.getElementById("cell").value;
var finalCom = valueCom * 0.1818937134 ;
var finalMon = valueMon * 0.056842 ;
var finalTv = valueTv * 0.056842 ;
var finalLap = valueLap * 0.090947 ;
var finalCel = valueCel * 0.045473 ;
var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;
var totalCarbon = totalTonnes * 1 ;
var totalTree = totalTonnes * 17.1969 ;
var totalPetrol = totalTonnes * 286.396 ;
var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield
}
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here
how to pass this values using java script to the text field. can anyone help me please
you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">
then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;
and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......
or,
document.getElementById("plastic").setAttribute('value',totalCarbon);
.....
Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);
set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;
and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >
Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
If your controls are in a form, like:
<form>
<input type="text" name="carbon">
<input type="text" name="tree">
<input type="text" name="petrol">
<input type="text" name="plastic">
...
</form>
then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...
Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).
//globally i declared carbon, tree, petrol, plastic
document.getElementById("carbon").value = carbon ;
document.getElementById("tree").value = tree ;
document.getElementById("petrol").value = petrol ;
document.getElementById("plastic").value = plastic ;

Form in Javascript return me an "undefined" alert

I'm a begginner in Javascript and I made a little form as a test. But I can't get the value of the input tags. I always get the alert as "undefined".
var id1, id2, id3, id4, id5, id6, id7, notabx, op1, op2, mu1, mu2;
var doc = document;
var id1 = doc.getElementById("1").value;
var id2 = doc.getElementById("2").value;
var id3 = doc.getElementById("3").value;
var id4 = doc.getElementById("4").value;
var id5 = doc.getElementById("5").value;
var id6 = doc.getElementById("6").value;
var id7 = doc.getElementById("7").value;
var op1 = doc.getElementById("op").value;
var op2 = doc.getElementById("op2").value;
var bx = doc.getElementById("bx").value;
function init() {
var FG = ( id1 + id2 + id3 + id4 + id5 ) / 5 ;
var FE = ( id6 * op1 ) + ( id7 * op2 );
var result = (bx * (60/100)) + (FG * (40/100)) + FE;
}
function result() {
alert(result);
}
window.onload = init();
</head>
<body>
<form>
<label for="bx">1st Cours:</label><input type="text" id="bx" value=""><p>
<br>
<p>FASE GENERAL</p>
<label for="1">Subject #1 </label><input type="text" id="1" maxlength="5" value="">
<label for="2">Subject #2 </label><input type="text" id="2" maxlength="5" value="">
<label for="3">Subject #3 </label><input type="text" id="3" maxlength="5" value="">
<label for="4">Subject #4 </label><input type="text" id="4" maxlength="5" value="">
<label for="5">Subject #5 </label><input type="text" id="5" maxlength="5" value="">
<p>FASE ESPECÍFICA</p>
<label for="6">Subject #6 </label><input type="text" id="6" maxlength="5" value=""><p>
<select name="" id="op">
<option value="0.1">0.1</option>
<option value="0.2">0.2</option>
</select>
<label for="7">Subject #7 </label><input type="text" id="7" maxlength="5" value="">
<select name="" id="op2">
<option value="0.1">0.1</option>
<option value="0.2">0.2</option>
</select>
<button onclick="result();">Calculate</button>
</form>
</div>
I'm spanish so I tried to calculate the academic results by following a method used here, don't loot at it. I'm focusing in I can not caltulate the result.
Lines like this
var id1 = doc.getElementById("1").value;
only work if the element can be found in the document. This means that either the script needs to be loaded at the bottom of the page, or you have to move this code inside the init function that you call on window.onload.
Also, the variable result is local to the init() function, which means you cannot read it outside of it. So the value that is alerted is not assigned either. You can declare result outside of the functions, so both functions can read or set it.
So in short, you script could look like this:
var result; // Make global, so both functions can reach it.
function init() {
// Var declaration is not needed if you add the `var` keyword later.
// var id1, id2, id3, id4, id5, id6, id7, notabx, op1, op2, mu1, mu2;
var doc = document;
var id1 = doc.getElementById("1").value;
var id2 = doc.getElementById("2").value;
var id3 = doc.getElementById("3").value;
var id4 = doc.getElementById("4").value;
var id5 = doc.getElementById("5").value;
var id6 = doc.getElementById("6").value;
var id7 = doc.getElementById("7").value;
var op1 = doc.getElementById("op").value;
var op2 = doc.getElementById("op2").value;
var bx = doc.getElementById("bx").value;
// Shouldn't mu1 and mu2 get a value too?
var FG = ( id1 + id2 + id3 + id4 + id5 ) / 5 ;
var FE = ( id6 * mu1) + ( id7 * mu2 );
// Remove the 'var' keyword below. You want to set the global, rather than
// declare a new local variable.
result = (bx * (60/100)) + (FG * (40/100)) + FE;
}
function showResult() {
// Alert the global result variable.
alert(result);
}
window.onload = init();
Alternatively, you could choose to do the calculation only when you click the button. Maybe that's even what you want. If you calculate it onload, the calculation will only be made with the values that are initially in the form. Any changes are not taken into account in the result.
As Anonymous mentioned in the comment, having a variable and a function both named result is asking for problems. So I renamed the function to showResult. You should change this in the HTML too, of course:
<button onclick="showResult();">Calculate</button>

Categories

Resources