Javascript passing variable to inline function in input element - javascript

I am trying to pass an object, totalArray into an input element, id=fullReport so that I will be able to use the variable totalArray within a function: printFullReport.
The input element is concatenated in a string so that it can be eventually created into a table.
I am unable to pass totalArrays into onclick="printFullReport('+ totalArray+ ')"> possibly due the string concatenation, in my console I recieve:
"Uncaught SyntaxError: Unexpected identifier" which implies a missing ; or '
but it appears to fine to me.
So this is my initial attempt:
<script type="text/javascript">
console.log(totalArray); //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
var str = "";
str += '<td>
<input id ="fullReport"
class="button"
type="button"
value="Full Report"
onclick="printFullReport('+ totalArray+ ')">
TOTAL (GBP):</td>';
</script>
this is my second attempt after reading and following the top answer:
Inline onclick JavaScript variable
<script type="text/javascript">
var str = "";
console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
function init(){
document.getElementById('fullReport').onclick=function(){
printFullReport(totalArray);
};
}
window.onload=init;
str += '<td><input id ="fullReport" class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>
but now this is returning: Uncaught ReferenceError: init is not defined.
I am possibly not understanding scope when having html elements in javascript strings.

For second attempt, you are missing the closing double-quote "
<script type="text/javascript">
And you need to assign the onclick from where the totalArray is accessible. (now that you clarified in comments that totalArray is not globally scoped.)
Demo
<script type="text/javascript">
var str = "";
totalArray ={ "1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
//console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
function init(){
document.getElementById('fullReport').onclick=function(){
printFullReport(totalArray);
};
}
window.onload=init;
str += '<td><input id ="fullReport" class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>
<input id ="fullReport" class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):

Related

Dynamically add textbox and assign it's value from a function

I want to create n number of textboxes dynamically based upon the user input.
Each textbox must populate with a serial number.Here, what I have tried so far.
function generateSerial(sender,eventArgs){
debugger;
//var rw_Serail = stockin.rw_Serail;
if(eventArgs.get_newValue()!="0"){
if(eventArgs.get_newValue()!=eventArgs.get_oldValue()){
create(eventArgs.get_newValue());
//OpenWindow(null,null,"rw_Serial");
}
}
}
Create will call a function and it's job is to create textboxes and assign a value.
function create(param) {
debugger;
var s= "";
for(var i = 0; i < param; i++) {
s+= `<input type="text" style="width:72%" name="txtSerial" value=${generateLicense()}>`
`<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML
}
document.getElementById("dvserialNo").innerHTML=s;
}
as name suggests generateLicense() will return a serial number..
function generateLicense() {
return "abcd1234Etc..";
}
Now while running this code, I am getting this error..
In chrome
Uncaught TypeError: generateLicense(...) is not a function
In firefox
TypeError: (("<input type=\"text\" style=\"width:72%\" name=\"txtSerial\" value=" + (intermediate value)) + ">") is not a function
Note: I want to create and assign it's value at the same time.
Concatenate the two elements in s+. And, of course, as one of the answers suggested include quotes for value="${generateLicense()}"
s+= `<input type="text" style="width:72%" name="txtSerial" value="${generateLicense()}">`
+ `<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML

How to escape a javascript variable in a thymeleaf attribute

Currently using javascript to create a dynamic form for image url's, but I can't seem to figure out how to escape the javascript var the right way. The problem is with the th:field="*{imageUrl['+iterator+']}"
Code:
<script type="text/javascript" th:inline="javascript">
var info = 1;
var iterator = 0;
function add_fields() {
info++;
iterator++;
var objTo = document.getElementsByClassName('form-group')[0]
console.log(objTo);
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="form-group"><label class="col-lg-3 control-label">Field'+info+' </label><div class="col-lg-9"> <input type="text" th:field="*{imageUrl['+iterator+']}" class="form-control" name="field1" /></div></div>';
objTo.appendChild(divtest)
}
</script>
But i'll get the following error:
java.lang.NumberFormatException: For input string: "'+iterator+'"
Thanks in advance
well, looks weird cause its a java error and you have javascript code.
But try to call method toString on your number.
var nbr = 10;
var foo = 'your text' + nbr.toString() + ' more text';
I just created a javascript function which makes a input form visible and putted the thymeleaf variables in the hidden input forms

Passing string parameter in JavaScript function

I was trying to pass a string to a JavaScript function.
As it's mentioned here - Pass a string parameter in an onclick function
I'm using this simple code-
<!DOCTYPE html>
<html>
<body>
<script>
name = "Mathew";
document.write("<button id='button' type='button' onclick='myfunction(\''" + name + "'\')'>click</button>")
function myfunction(name)
{
alert(name);
}
</script>
</body>
</html>
But in the console it's giving an error like Uncaught SyntaxError: Unexpected token }.
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
Rename your variable name to myname, bacause name is a generic property of window and is not writable in the same window.
And replace
onclick='myfunction(\''" + name + "'\')'
With
onclick='myfunction(myname)'
Working example:
var myname = "Mathew";
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');
function myfunction(name) {
alert(name);
}
The question has been answered, but for your future coding reference you might like to consider this.
In your HTML, add the name as an attribute to the button and remove the onclick reference.
<button id="button" data-name="Mathew" type="button">click</button>
In your JavaScript, grab the button using its ID, assign the function to the button's click event, and use the function to display the button's data-name attribute.
var button = document.getElementById('button');
button.onclick = myfunction;
function myfunction() {
var name = this.getAttribute('data-name');
alert(name);
}
DEMO
document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)
Better to use `` than "". This is a more dynamic answer.
You can pass string parameters to JavaScript functions like below code:
I passed three parameters where the third one is a string parameter.
var btn ="<input type='button' onclick='RoomIsReadyFunc(" + ID + "," + RefId + ",\"" + YourString + "\");' value='Room is Ready' />";
// Your JavaScript function
function RoomIsReadyFunc(ID, RefId, YourString)
{
alert(ID);
alert(RefId);
alert(YourString);
}
Use this:
document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')
Try this ...
onclick="myfunction('name')";

Removing specific form element using javascript

I'm trying to create to remove a form element using javascript. When I remove an element, it removes the topmost element. I'm trying to remove a specific element. Here is a link to the page and below is the code. Any help would be appreciated, thanks!
http://training.cvrc.virginia.edu/test.html
<script type="text/javascript">
var patient = 0;
function add_patient() {
patient++;
var add= document.createElement('patientdiv');
add.innerHTML += "<div id=removepatient></br>Patient "+patient+" Name/ID:<input type=text name=patients[] ><input type=button id=more_fields onclick=removepatient(); value='Remove' ></div>";
document.getElementById('patientdiv').appendChild(add);
return false;
}
function removepatient() {
var elem = document.getElementById('removepatient');
elem.parentNode.removeChild(elem);
return false;
}
</script>
<div id=patientdiv></div>
<input type=button id=more_fields onclick=add_patient(); value='Add Patient'></br></br>
You should generate a unique ID for each element you are adding to the page.
You can use a variable and increment this variable each time an element is added. In your exemple, the variable 'patient' is enough.
add.innerHTML += "<div id=removepatient_"+patient"></br>Patient "+patient+" Name/ID:<input type=text name=patients[] ><input type=button id=more_fields"+patient+" onclick=removepatient("+patient+"); value='Remove' ></div>";
You must also add a param to your delete function :
function removepatient(patient) {
var elem = document.getElementById('removepatient_'+patient);
elem.parentNode.removeChild(elem);
return false;
}
I hope it helps you

innerHTML with For Loop in Javascript

this is my coding. in this coding i want to print table in innerHTML in paragraph tag.This is working but the problem is when i click submit button this result show only last value like this "10*10=100" but i want to run full loop which i define in code from 1 till 10. Please solve this issue.
<html>
<head>
<title>Table Program</title>
</head>
<body>
<input type="text" id="table" placeholder="Enter table"/>
<input type="button" value="Submit" onClick="table()"/>
<p id="demo"></p>
<!----------------------------------------------------------------------------------------------->
<script type="text/javascript">
function table()
{
var value = document.getElementById("table").value;
var demop = document.getElementById("demo");
var a;
for(a=1; a <= 10;++a)
{
demop.innerHTML=(value+"*"+ a +"="+ value*a);
}
}
</script>
</body>
</html>
Your for loop is overwriting the innerHTML of demop each time it is executing.
So when your for loop reaches last iteration a will be 10 and hence you only get the last value "10*10=100"
So you should append the result every time you iterate your for loop
just make it like this
demop.innerHTML += (value + "*" + a + "=" + (value*a) + "<br />");
So you will get your output on seperate lines.
When you call demop.innerHTML = something you overwrite it each time.
You should either:
Put the entire string in a temporary result variable and then give it to innerHTML
Concatenate the different results by doing
demop.innerHTML = demop.innerHTML + (value+"*"+ a +"="+ value*a);

Categories

Resources