Javascript - How to use variable when writing table - javascript

I'm trying to print the value of a variable in the first column of my table, but when I run the method, I get the name of the variable instead
I have the following code
function writeTable() {
var table;
var uInput = document.test.input.value;
table = "<table><tr><th colspan=3>Table Header</th></tr>";
table += "<tr><th>Column1</th><th>column2</th><th>column3</th></tr>";
table += '<tr><td>uInput</td><td>Value2</td><td>value3</td></tr>';
document.write(table);
}
<form name="test">
<input type="text" name="input">
</form>
<input type="submit" name="submit" value="Write Table" onclick="writeTable()">

You need to change this line:
table += '<tr><td>uInput</td><td>Value2</td><td>value3</td></tr>';
To use template literal:
table += `<tr><td>${uInput}</td><td>Value2</td><td>value3</td></tr>`;
Or standard concatenation
table += '<tr><td>' + uInput + '</td><td>Value2</td><td>value3</td></tr>';

You need to concatenate the string:
table+= '<tr><td>'+uInput+'</td><td>Value2</td><td>value3</td></tr>';
Remember that everything between single or double quotes is interpreted as a string. However your uInput is a variable. To make sure JavaScript get's the variable you need to concatenate. That means pasting the string parts and the variable together using the +. Purgatory's answer has a nice ecmascript 6 solution too.

In print statement, you have to concatenate variable with "+" sign. Your function 2nd last row looks like:
table+= '<tr><td>'+ uInput + '</td><td>Value2</td><td>value3</td></tr>';

use
table+= '<tr><td>' + uInput + '</td><td>Value2</td><td>value3</td></tr>';
to concatenate your string.As well as for the standards ,use
uInput = document.getElementsByName('input').value
in your javascript

Related

How do I add a radio button to HTML table via jquery

I'm using Jquery $.post to get string array from SQL based on selection from a drop-down that I'm then reading into an HTML table. Each time they change selection on drop down, it clears all but the header row from the table and reloads new values. That is working fine.
It is just a basic 3 row table; a unique identifier, a value and a count shown as string. Every record has all 3, so I'm just using for loop with counters to control start/end of rows. In my form it's header is defined as such:
<div class="col-md-10">
<table id="attEditTable" style="width:100%" cellpadding="0" cellspacing="0" border="1" class="row">
<tbody>
<tr style="background-color: #F0F8FF;">
<th></th>
<th>Attribute Value</th>
<th>Item Count</th>
</tr>
</tbody>
</table>
</div>
I'm now trying to change the 1st cell of each row to a radio button with the value set to the value I was displaying in that cell.
Currently when the view displayed it is showing [object Object] in the first cell of every row instead of a radio button.
Sorry I am a newb at this with no training on Java or MVC - so hoping just a simple syntax issue...
Trying this basic one returned syntax error on input:
<input type="radio" name="SelERow" value='+editValues[i]+' />
I've also tried (both had same result of [object Object]):
$("input:radio[name=\"SelERow\"][value="+editValues[i]+"]")
$('<input type="radio" id="ERow" name="SelERow" value='+editValues[i]+' />')
Per David's suggestions I've now also tried (both resulted in no data and no error):
'<input type="radio" name="SelERow" value='+editValues[i]+' />'
var tblCell = $('<td />'); // create an empty <td> node
if (x == 1 || (x - 1) % 3 == 0) {
var input = $('<input />', { type: 'radio', id: 'ERow', name: 'SelERow', value: editValues[i] });
tblCell.append(input); // append an <input> node to the <td> node
} else {
tblCell.text(editValues[i]); // or just set the text of the <td> node
}
With the 2nd one I also changed the line: tblRow = tblRow + ""; to instead be tblRow = tblRow + tblCell + "";
Current Script
<script>
$(function () {
$("#EditAttributeName").change(function () {
var selectedName = $(this).val();
// Delete all but first row of table
$("#attEditTable").find($("tr")).slice(1).remove();
var url2 = "EditDD2changed?selectedName=" + selectedName;
$.post(url2, function (editValues) {
var x = 0;
var tblRow = "<tr>";
for (var i=0; i < editValues.length; i++)
{
x++;
if (x == 1 || (x - 1) % 3 == 0) {
tblRow = tblRow + "<td>" + $('input:radio[name="SelERow"][value="' + editValues[i] + '"]');
}
else {
tblRow = tblRow + "<td>" + editValues[i] + "</td>";
}
if (x % 3 == 0)
{
tblRow = tblRow + "</tr>";
$("#attEditTable").append(tblRow);
tblRow = "<tr>";
}
}
})
});
});
</script>
Console is showing no error messages.
Looks like it's close. To start, there's an important difference in the two attempts. This is a jQuery selector syntax:
$('input:radio[name="SelERow"][value="' + editValues[i] + '"]')
So it's not creating an <input/>, but looking for an <input/>. Which isn't what you want in this case. Your other attempt uses the syntax for creating an element:
$('<input type="radio" id="ERow" name="SelERow" value=editValues[i] />')
Though an issue here (which may have just been a copy/paste error in posting the question? but for completeness and for future readers it may as well be addressed...) appears to be that the editValues[i] is just part of the string. You want to concatenate it into the string. There are a couple ways to do that. Either direct concatenation:
$('<input type="radio" id="ERow" name="SelERow" value="' + editValues[i] + '" />')
Or string interpolation (take note of the different overall quotes, using back-ticks this time):
$(`<input type="radio" id="ERow" name="SelERow" value="${editValues[i]}" />`)
The latter is newer syntax but should be widely enough supported by now. (Though in any given business environment who knows what ancient browsers one may need to support.) Could just be personal preference between the two.
it is showing [object Object]
The main issue producing the result you've observing is that you're concatenating the result of that jQuery operation directly as a string:
tblRow + "<td>" + $('<input type="radio" id="ERow" name="SelERow" value="' + editValues[i] + '" />')
(Coincidentally, whether you're creating an element or looking for an element, this observed output would be the same because both operations return an object.)
The result of an $() operation is not itself a string, but a more complex object. When concatenated with a string it has to be interpreted as a string, and unless the object has a meaningful .toString() implementation (this one doesn't appear to) then the default string representation of a complex object is exactly that: "[object Object]"
There are a couple approaches you can take here. One would be to just use strings entirely, you don't necessarily need a jQuery object here:
tblRow + '<td><input type="radio" id="ERow" name="SelERow" value="' + editValues[i] + '" /></td>'
Since you're using jQuery later to append the result to the HTML, you can just build up all the HTML you like as plain strings and let jQuery handle turning them into DOM objects when you send them to .append().
The other option, if you definitely want to "use jQuery" in this situation or are otherwise being instructed to, would be to build the hierarchy of HTML elements as jQuery objects and then pass that hierarchy to .append(). Constructing such a hierarchy can look something like this:
var tblCell = $('<td />'); // create an empty <td> node
if (x == 1 || (x - 1) % 3 == 0) {
var input = $('<input />', { type: 'radio', id: 'ERow', name: 'SelERow', value: editValues[i] });
tblCell.append(input); // append an <input> node to the <td> node
} else {
tblCell.text(editValues[i]); // or just set the text of the <td> node
}
Note that each $() operation creates an HTML element node, and you can supply attributes for it as a second argument to the $() function. Then those nodes can be .append()-ed to each other just like you .append() the HTML string to $("#attEditTable").
In your particular case this may get a little more cumbersome because your loop isn't just looping through cells or just through rows, but through both and using a hard-coded count to determine whether it's reached the end of a row or not. So, as part of learning/practicing jQuery, it may be worth the effort to try this approach. But I suspect the shortest path to getting your code working with minimal changes would be the string concatenation approach above.
Side note: This code is using the same id value for the radio buttons created within this loop. The result is that there is expected to be multiple elements on the page with the same id. This is technically invalid HTML. If you ever try to use that id to reference an element, the resulting behavior will be undefined. (It might work in some cases, might not in others, purely coincidentally.) Though if you don't need to use that id to reference the elements, you may as well remove it entirely.

Getting variable into JS via PHP assigned id

I have the following Javascript to generate a silent call to another sheet to update a database value without refreshing the page
function UpdateDB(table,column,type){
var value = $("#Assigned").val();
$.post("UpdateValuation.php?Table=" + table + "&Value=" + value + "&Column=" + column + "&Type=" + type, {}).done();
};
This works perfectly but only for the "Assigned" table row since it is statically assigned.
I use the following php to generate the table entry with button
print "<tr><td>" . $stuff['Status'] . "</td><td ><input type=\"text\" id=\"" . $stuff['Status'] . "\" name=\"" . $stuff['Status'] . "\" value=". $stuff['Value'] ." size = \"4\" style = \"text-align: center\"/><button onclick=\"UpdateDB('NOCstatus','Status','". $stuff['Status'] ."');\">Update</button></td></tr>";
Which after variables are assigned looks like this for my "Pending" row
<input id="Pending" type="text" style="text-align: center" size="4" value="120" name="Pending"> </input>
<button onclick="UpdateDB('NOCstatus','Status','Pending');">
Update
</button>
My problem is that passing "this.value" or trying to use a variable in the javascript portion I always come up with a blank value, the only time I can get a value to be correct is by statically assigning the "#Assigned" or "#Pending" in the value field. I have hundreds of entries so I don't want to write the function over for each of these. I know there is probably something extremely simple I am missing but I cannot get the pieces to fit.
I need to pass the typed in value in the input field to the function to update the database. Please help.
function UpdateDB(table,column,type){
var value = $('#'+type).val();
$.post("UpdateValuation.php?Table=" + table + "&Value=" + value + "&Column=" + column + "&Type=" + type, {}).done();
};
?

how to concatenate string in javascript

I need to convert a mailto element to have subject and body element in a javascript.
var matterDetail = "?Subject=Potential New Matter";
try{strContact = strContact + "<TD>" + EMailNode.item(0).firstChild.nodeValue + "</TD>";}
This outputs the html to <a href="mailto:some#email.com" ?Subject="Potential" Matter="" New="">
Any ideas what is wrong with string concatenation?
Classic asp is not written in c#, so i dont know what you are using, but as it seems you are using c#, i would use string.format:
strContact += string.Format(
"<td>{2}</td>",
EMailNode.item(0).firstChild.nodeValue,
matterDetail,
EMailNode.item(0).firstChild.nodeValue
);
EDIT ok, i mistook js for c#!
Your problem is missing quotes in the html attributes, try this:
strContact += "<td>" + EMailNode.item(0).firstChild.nodeValue + "</td>";
Note the extra (escaped) quotes around the href attribute
For concatination & is used in classic asp:
var a = "ehsan " & "sajjad";
See HERE

Using jQuery to create a number of input fields, based on value entered

I have a form in which I ask the user how many file inputs they need, and I'd like to generate the suitable number of file browsing inputs dynamically based on the answer.
Here is my attempt:
$("#howmany").change(function()
{
var htmlString = "";
var len = $(this).val();
for (var i = 0; i <= len; i++)
{
htmlString += "
<tr>
<td>
<input name="ufile[]" type="file" id="ufile[]" size="50" />
</td>
</tr>
";
}
$("#dynamic_upload").html(htmlString);
}
HTML
<input id="howmany" />
<table id="dynamic_upload">
</table>
The idea being that repeating "units" of inputs will be generated based on the number entered.
But it isn't working, any idea where I'm going wrong?
EDIT: More clarity on "it isn't working" (apologies). When I include this code, after entering the number into the field "howmany" there is no visable reaction. No error messages appear, although - is there an error log somewhere I don't know how to read? (new to this)
It's not possible to create a string like that. Try:
htmlString += "<tr>";
htmlString += "<td>";
htmlString += '<input name="ufile[]" type="file" id="ufile[]" size="50" />';
htmlString += "</td>";
htmlString += "</tr>";
Also remember you need to use single quotes around the string if it contains double quotes, or escape them.
You are also missing ); from the end of the function:
$("#dynamic_upload").html(htmlString);
} <--- this should be });
You can't have newlines in JavaScript strings. Moreover, you are using double-quotes within the string (i.e. for the <input> attributes). Possible rewrite:
htmlString += '<tr><td><input name="ufile[]" type="file" id="ufile[]" size="50"></td></tr>';
In the future, please give a more descriptive problem than "it isn't working" -- for example, do you get any error messages?

Variable within quote within quote?

Im trying to use inner html and dynamically set an onclick statement that contains a variable:
cell5.innerHTML="<input type='button' value='Remove' onclick='removerow('manual_" + (num) + "')' />"
So lets say the num variable was set to 4. The output should be onclick="removerow('manual_4')"
Any help?
The best thing would be to avoid all this:
var input = document.createElement('input');
input.type = 'button';
input.value = 'Remove';
input.onclick = function() {
removerow('manual_' + num);
};
cell5.appendChild(input);
Depending on the relationship between the button, the cell and the row to be removed, you could also do DOM traversal inside the handler to get a reference to the row.
You can escaped nested quotes using \:
"...onclick=\"removerow('manual_" + (num) + "')\"..."
cell5.innerHTML='<input type="button" value="Remove" onclick="removerow(\'manual_' + (num) + '\')" />'
You can escape the quotes using \
So
onclick=\"removerow('manual_" + (num) + "')\"
Consider using a click event instead. It makes that sort of thing clearer:
$(".cell5") // whatever selector you want
.html('<input type="button" value="Remove"/>')
.click(function(){
removerow('manual_' + row);
});
Also consider using the row number as the input instead of a string. If they all have the same form you can simplify things with just:
removerow(row);
Clearly that is an API design decision, but it would simplify this expression if it makes sense.

Categories

Resources