javascript.i want to fix input of textbox through javascript function - javascript

Hello guys I want to fix my textbox input
Here is my HTML code
<marquee behavior="slid" direction="right">Wellcome To Our Medicine Store</marquee>
<div id="inps">
Search Medicine: <input type="text" name="n1" id="n1">
<button onclick="search()" >Search</button>
<br><br>
Quantity Of Medicine:<input type="text" name="n3" id="n3">
<br><br>
Remaining Stock:<input type="text" name="n2" id="n2">
<br><br>
Total Bill:<input type="text" name="n4" id="n4">
</div>
Here is my function
<script>
var database=[];
// var total_quantity=100;
// var counter=0;
var panadol={
medicine_name:"panadol",
price:12,
total_stock:2000
};
var favrine={
medicine_name:"favrine",
price:38,
total_stock:1200
};
var rivotril={
medicine_name:"rivotril",
price:24,
total_stock:1500
};
database.push(panadol);
database.push(favrine);
database.push(rivotril);
console.log(database);
function search()
{
var searchmedi=document.getElementById("n1").value;
var getQuantity=document.getElementById("n3").value;
var medilist=" ";
var result="";
var remaing_stock;
for(var i=0;i<database.length;i++)
{
if(database[i].medicine_name==searchmedi)
{
// medilist +='<li>' + database[i].medicine_name +" ::" + "</li>";
// document.getElementById("result").innerHTML=medilist;
result= getQuantity*database[i].price;
document.getElementById("n4").value=result;
remaing_stock=database[i].total_stock-getQuantity;
document.getElementById("n2").value=remaing_stock;
} else {
console.log("not found");
}
}
}
</script>
I want only one thing when I enter my medicine name if its name exceeded to 10 alphabets it gives me error message.
How can I do this please help. How I check this condition.
I am new in this language and facing very problems please people help me.

Here you go, remember always to break for loop if you found your item.
You can use .length function to get the length of the string and use if statement to check if it is what you expect
var database=[];
// var total_quantity=100;
// var counter=0;
var panadol={
medicine_name:"panadol",
price:12,
total_stock:2000
};
var favrine={
medicine_name:"favrine",
price:38,
total_stock:1200
};
var rivotril={
medicine_name:"rivotril",
price:24,
total_stock:1500
};
database.push(panadol);
database.push(favrine);
database.push(rivotril);
console.log(database);
function search(){
var searchmedi=document.getElementById("n1").value;
if(searchmedi.length<10){
var getQuantity=document.getElementById("n3").value;
var medilist=" ";
var result="";
var remaing_stock;
for(var i=0;i<database.length;i++)
{
if(database[i].medicine_name==searchmedi)
{
result= getQuantity*database[i].price;
document.getElementById("n4").value=result;
remaing_stock=database[i].total_stock-getQuantity;
document.getElementById("n2").value=remaing_stock;
break; // remember to break if you found your item
}
else if(i==database.length-1){
console.log("Medicine not found");
}
}
}
else{
console.log("Name is too long");
}
}
<marquee behavior="slid" direction="right">Wellcome To Our Medicine Store</marquee>
<div id="inps">
Search Medicine: <input type="text" name="n1" id="n1">
<button onclick="search()" >Search</button>
<br><br>
Quantity Of Medicine:<input type="text" name="n3" id="n3">
<br><br>
Remaining Stock:<input type="text" name="n2" id="n2">
<br><br>
Total Bill:<input type="text" name="n4" id="n4">
</div>

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")
}

validate form for dynamically created inputs count

I am dynamically creating the inputs in the form
I want user to enter at least 'n' elements.
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input id='my-div-"+counter+"' type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
document.getElementById('my-div-'+counter).focus();
counter++;
}
}
function validateForm(){
var frm = document.forms['simples'];
a = parseInt(frm.elements['myInputs_1[]'].length)
var sum = parseInt(frm.elements['myInputs_1[]'].length)
if(parseInt(sum) < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
</script>
</head>
<body>
<form name="simples" action="part.php" align="center" onsubmit="return validateForm()" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
<input type="submit" value="show me what is next">
</form>
</body>
</html>
The method validateForm() works only if number text boxes are greater than equal to 2, for 0 and 1 it does not work.
Please not that this is minimal example, in real website, I have many such divs collecting input in multiple arrays, so I am summing them over something like:
var sum = parseInt(frm.elements['myInputs_1[]'].length) + parseInt(frm.elements['myInputs_2[]'].length) + parseInt(frm.elements['myInputs_3[]'].length)
but it may happen that few of the arrays are empty.
How do I check that collectively there are atleast n inputs?
frm.elements['myInputs_1[]'] has a different behavior for each of the cases.
for no elements entered, it will be undefined
for 1 element, it only contains that element, so it does not have a length
for two elements onwards it is an object of type RadioNodeList, which is inherited from NodeList and has a length attribute.
so the validate form method changes to:
function validateForm(){
var frm = document.forms['simples'];
ele = frm.elements['myInputs_1[]'];
if(typeof ele === 'undefined'){
alert('no element at all..');
return false;
}
else if(ele.value == ""){
if (ele.length < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
else{
alert('contains one element');
return false;
}
return true;
}
and it works!

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>

i want to search a string from the json object in javascript

I want to search the House Name from all the input the user provided.
so if the user details are as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"},{"houseName":"band","houseType":"small","houseFloors":"two","houselocation":"washington DC"}]
If i provide search as man ,it should give me as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"}]
The code is as :
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>
You may use Array.prototype.filter.
In ur case it will look like
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
If u would like to search it with an input box, there will be a little bit more work to do:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful

"NaN" result when multiplying more than one value in an array by a number

Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>

Categories

Resources