How do I assign value of the clicked button - javascript

I have the following on jsfiddle. What I need to accomplish is when I click on a button the respective value is inserted in the blank.
https://jsfiddle.net/aminbaig/jefee77L/
Here is the Code:
HTML:
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change()" />
<input type="submit" id="byBtn1" value="Truck" onclick="change()" />
<input type="submit" id="byBtn2" value="Trash" onclick="change()" />
Javascript:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}

You can do like this
JS
get the value of the button from the function parameter
function change(value) {
var title = document.getElementById('title');
title.innerHTML = value;
}
HTML
change button type='submit' to type='button', Also pass the value as the function parameter
<input type="button" id="myTextField" value="something" onclick="change(this.value)" />
<input type="button" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="button" id="byBtn2" value="Trash" onclick="change(this.value)" />
DEMO

use like this onclick="change(this.value)" .send the value of the input via click function
function change(val) {
if (val.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = val;
}
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change(this.value)" />
<input type="submit" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="submit" id="byBtn2" value="Trash" onclick="change(this.value)" />

Related

Adding elements dynamically

I'm trying to add elements dynamically through javascript but whenever I try opening up the page they appear for a split second then disappear
I take a number of process from the input tag and run a loop to create each element individually
I tried removing everything from the event and only call a function which I placed the code in but didn't work
const numberOfProcesses = document.getElementById("numberOfProcesses").value;
const timeQuantum = document.getElementById("timeQuantum").value;
const start = document.getElementById("start");
const processDiv = document.getElementById("processDiv");
const burstDiv = document.getElementById("burstDiv");
start.addEventListener("click", (event) => {
for (let i = 0; i < numberOfProcesses; i++) {
let pLabel = document.createElement("label");
pLabel.setAttribute("id", `process ${i}`);
pLabel.innerText = `Process ${i}`;
let pInput = document.createElement("input");
pInput.setAttribute("type", "number");
pInput.setAttribute("id", `process ${i}`);
let bLabel = document.createElement("label");
bLabel.setAttribute("id", `burstTime ${i}`);
bLabel.innerText = `Burst Time ${i}`;
let bInput = document.createElement("input");
bInput.setAttribute("type", "number");
bInput.setAttribute("id", `burstTime ${i}`);
processDiv.appendChild(pLabel);
processDiv.appendChild(pInput);
burstDiv.appendChild(bLabel);
burstDiv.appendChild(bInput);
console.log(pLabel, pInput, bLabel, bInput);
}
});
<form action="">
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button id="start">Start</button>
</form>
</section>
<br /><br />
<section>
<form action="">
<div id="processDiv">
<label for="process0">P0</label>
<input type="number" name="process" id="process0" />
</div>
<div id="burstDiv">
<label for="burstTime0">Burst Time</label>
<input type="number" name="burst time" id="burstTime0" />
</div>
<button id="excute">Execute</button>
</form>
Remove action="" and set type attribute to button if nothing is submitted. The behaviour you describe is due to the form being submitted.
Do like this and you can see you console log for other errors:
<form>
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button type="button" id="start">Start</button>
</form>

How can I make this calculator work

I am having trouble, as you can see in code, for the result3 as id i have op1, what I would like to have there so that it works is that id changes depending on the button pressed, how can I do that? because now every button is like a +.
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<script>
function getResult()
{
var result1 = document.getElementById("number1").value;
var result3 = document.getElementById ("op1").value;
var result2 = document.getElementById("number2").value;
calculate (result1,result3,result2);
}
function calculate(num1,operator,num2)
{
if (operator== '+')
{
var res1 = parseFloat(num1)+parseFloat(num2);
alert(res1);
}
else if (operator== '-')
{
var res2 = parseFloat(num1)-parseFloat(num2);
alert(res2);
}
else if (operator== '*')
{
var res3 = parseFloat(num1)*parseFloat(num2);
alert(res3);
}
else if (operator== '/')
{
var res4 = parseFloat(num1)/parseFloat(num2);
alert(res4);
}
else
{
alert("Nothing from above!");
}
}
</script>
<body>
<form action="get" method="#">
<input type="text" name="text1" value="" id="number1" /> <br/>
<input type="text" name="text2" value="" id="number2" /> <br/>
<input type="button" name="o1" value="+" id="op1" onclick="getResult();"/>
<input type="button" name="o2" value="-" id="op2" onclick="getResult();"/>
<input type="button" name="o3" value="*" id="op3" onclick="getResult();"/>
<input type="button" name="o4" value="/" id="op4" onclick="getResult();"/>
<input type="button" name="calc" value="Calculate" onclick="getResult();"/>
</form>
</body>
</html>
You are always calling the value of input with id="op1", which is + in your case. Why not pass the value?
getResult(id) {
var result1 = document.getElementById("number1").value;
var result3 = document.getElementById (id).value;
var result2 = document.getElementById("number2").value;
calculate (result1,result3,result2);}
The id is passed when calling the function:
<input type="button" name="o1" value="+" id="op1" onclick="getResult(id);"/>
<input type="button" name="o2" value="-" id="op2" onclick="getResult(id);"/>
<input type="button" name="o3" value="*" id="op3" onclick="getResult(id);"/>
<input type="button" name="o4" value="/" id="op4" onclick="getResult(id);"/>
Calculate button won't work this way, but this is a quick fix with your setup. Good luck.

Passing array input values to code.gs on google app scripting

I have a form with input array and I want to initialized the input value by another Global array value and pass the value to code.gs .
But I couldn’t get the value I passed in code.gs.
Would you help me please?
Thank you!
Html part
<form id="downloadpdf">
<input id="urlclass" type="text" name="urlname[]" />
<input type="submit" value="Download" />
</form>
Javascript
<script>
var urllink=[]; // Global variable a return from another function
$(document).ready(function() {
function another(){
var url=[]; // it is a dynamic value I get it from another function eg. url[0]=”www.abc.com” ,url[1]=”www.abcd.com”, url[2]=”www.abcde.com”....
urllink.push(url); // Assigning the global array value by the urls
}
$("#downloadpdf").submit(function() {
$("#urlclass").val(urllink); // assigning the input value by the Global array value.
google.script.run.withSuccessHandler(function(retsearch){
}).downloadthefile(this);
});
});
</script>
Code.gs
function downloadthefile(urlpass){
Logger.log(urlpass.urlname); // I couldn’t get the urls here
}
This is a simple HTML file communicating with Google Apps Script contained in a Spreadsheet. I test it a lot as a dialog and I also run it as a web app. The HTML file and the Google Apps Script communicate with each other and I pass the contents of 4 textboxes back to the Google Script as an array.
The Code.gs file:
function doGet()
{
var html = HtmlService.createHtmlOutputFromFile('index');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}
function getData(a)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "M/d/yyyy' 'HH:mm:ss");
a.splice(0,0,ts);
var ss=SpreadsheetApp.openById('SPREADSHEETID')
ss.getSheetByName('Form Responses 1').appendRow(a);
return true;
}
function getURL()
{
var ss=SpreadsheetApp.openById('SPREADSHEETID');
var sht=ss.getSheetByName('imgURLs');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var urlA=[];
for(var i=1;i<rngA.length;i++)
{
urlA.push(rngA[i][0]);
}
return urlA;
}
The index.html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="data">
<br />Text 1<input name="t1" type="text" size="15" id="txt1" placeholder="Text 1" />
<br />Text 2<input name="t2" type="text" size="15" id="txt2" placeholder="Text 2" />
<br />Text 3<input name="t3" type="text" size="15" id="txt3" placeholder="Text 3" />
<br />Text 4<input name="t4" type="text" size="15" id="txt4" placeholder="Text 4" />
<br /><input type="radio" name="Type" value="Member" checked />Member
<br /><input type="radio" name="Type" value="Guest" />Guest
<br /><input type="radio" name="Type" value="Intruder" />Intruder
<br /><input type="button" value="submit" id="btn1" />
<br /><img id="img1" src="" alt="img1" width="300" />
</div>
<div id="resp" style="display:none;">
<h1>Response</h1>
<p>Your data has been received.</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#btn1').click(validate);
$('#txt4').val('');
$('#txt3').val('');
$('#txt2').val('');
$('#txt1').val('')
google.script.run
.withSuccessHandler(setURL)
.getURL();
});
function setURL(url)
{
$('#img1').attr('src',url[0]);
}
function setResponse(a)
{
if(a)
{
$('#data').css('display','none');
$('#resp').css('display','block');
}
}
function validate()
{
var txt1 = document.getElementById('txt1').value || '';
var txt2 = document.getElementById('txt2').value || '';
var txt3 = document.getElementById('txt3').value || '';
var txt4 = document.getElementById('txt4').value || '';
var type = $('input[name="Type"]:checked').val();
var a = [txt1,txt2,txt3,txt4,type];//This gets passed as an array;
if(txt1 && txt2 && txt3 && txt4)
{
google.script.run
.withSuccessHandler(setResponse)
.getData(a);
return true;
}
else
{
alert('All fields must be completed.');
}
}
function loadTxt(from,to)
{
document.getElementById(to).value = document.getElementById(from).value;
}
function radioValue()
{
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++)
{
if(radios[i].checked)
{
return radios[i].value;
}
}
}
console.log('My Code');
</script>
</body>
</html>

Javascript Calculator Memory function

Here is my HTML
<script type="text/javascript" src="./The Desktop Calculator_files/calc.js"></script>
<style type="text/css"></style>
</head>
<body onLoad="checkBrowser()">
<form id="calcForm">
<div id="calc">
<input type='hidden' id='param1' value='0' />
<input type='hidden' id='operator' value='' />
<div id="display">
<input type="text" name="disp" id="disp" class="disp" size="36" value="0">
</div>
<div id="buttons">
<div class="row">
<input type="button" value="7" onclick="isNum();appendMe(this.value)">
<input type="button" value="8" onclick="isNum();appendMe(this.value)">
<input type="button" value="9" onclick="isNum();appendMe(this.value)">
<input type="button" value="/" onClick="isNum();setOp(this.value)">
<input type="button" value="CE">
</div>
<div class="row">
<input type="button" value="4" onclick="isNum();appendMe(this.value)">
<input type="button" value="5" onclick="isNum();appendMe(this.value)">
<input type="button" value="6" onclick="isNum();appendMe(this.value)">
<input type="button" value="*" onClick="isNum();setOp(this.value)">
<input type="button" value="C" onclick="clearAll()">
</div>
<div class="row">
<input type="button" value="1" onclick="isNum();appendMe(this.value)">
<input type="button" value="2" onclick="isNum();appendMe(this.value)">
<input type="button" value="3" onclick="isNum();appendMe(this.value)">
<input type="button" value="-" onClick="isNum();setOp(this.value)">
<input type="button" value="M" onClick="isNum();set_getMem()">
</div>
<div class="row">
<input type="button" value="0" onclick="isNum();appendMe(this.value)">
<input type="button" value="+/-" onclick="isNum();plusMinus()">
<input type="button" value="." onclick="isNum();appendMe(this.value)">
<input type="button" value="+" onClick="isNum();setOp(this.value)">
<input type="button" value="=" onClick="isNum();calcMe()">
</div>
</div>
<div id='warning'>Your Browser Can't Handle The Truth!</div>
</div>
</form>
</body></html>
Here is my JavaScript
function appendMe(val)
{
//alert(val);
//document.getElementById("disp").value+=val;
//alert(val);
if(document.getElementById("disp").value=='0')
{
document.getElementById("disp").value=val;
}
else if(val=='.' && document.getElementById("disp").value.indexOf('.')>-1) //do nothing, because we already have a decimal point
{
}
else //in any other case, we just append
{
document.getElementById("disp").value+=val;
}
}
function clearAll()
{
//alert(val);
document.getElementById("disp").value=0;
}
function checkBrowser()
{
alert("checking");
document.getElementById("warning").style.display="none";
}
function plusMinus()
{
document.getElementById("disp").value=(document.getElementById("disp").value*-1);
}
function setOp(val)
{
//first, set aside the initial value as entered
document.getElementById("param1").value=document.getElementById("disp").value;
//next, clear out that first number entered
document.getElementById("disp").value=0;
//finally, store the operation
document.getElementById("operator").value=val;
}
function calcMe()
{
var param1 = document.getElementById("param1").value;
var operator = document.getElementById("operator").value;
var param2 = document.getElementById("disp").value;
document.getElementById("disp").value = eval(param1+operator+param2);
}
function isNum()
{
//start as true
var isN = true;
if(isNaN(document.getElementById("disp").value))
{
isN=false;
alert("Non-numeric Data!");
}
return isN;
}
function set_getMem()
{
var memvalue;
//{
//isNum()
//}
if(memvalue == null ) //nothing in there, so set it
{
memvalue = document.getElementById("disp").value;
}
else //something in there, so display it
{
document.getElementById("disp").value = memvalue;
}
}
The part I am having problems with is getting the M button to function properly. What I want to happen is that I can click M and it will save whatever is in the display except when there is already a number stored I want it to display that number.
Currently I click the M button and it doesn't appear to save a number or display a number.
Edited: Based on feedback I got the Memory function to work but now I need a function that can clear the value of the global variable.
function clear_All()
{
var memvalue=0;
document.getElementById("disp").value=0;
var param1=0;
var param2=0;
}
When I put the memvalue to 0 in the function it doesnt clear it from memvalue. When I put it outside the function it just breaks the storing capabilities of the memvalue.
Here might be the problem:
function set_getMem()
{
var memvalue;
You define memvalue as a local variable inside set_memGet(), therefore this variable is gone once the function returns.
Define this variable out of the function.

Javascript dynamically created form field validation

I have created a form with a dynamically created field and i am trying to find a way to validate all the fields with javascript. I just want to alert the user that a field is null. Here is my code:
<script>
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form['field[]'];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I was expecting that will work but i was obviously wrong:(
With this code if i haven't pressed the "New field" button and press submit i will get the alert as expected. But on all other cases i am not getting anything!
Thanks for your time anyway, and sorry if i have made grammar mistakes!
<script type="text/javascript">
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form[i];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I don't understand this line: field=form['field[]'];, so I changed it to field=form[i];
http://jsfiddle.net/sZ4sd/

Categories

Resources