string interpolation for dynamic html attributes - javascript

Is it possible to use string interpolation for the below (Note the dynamic attributes)
document.body.innerHTML += <form id="digSigForm" action="${myObj.Url}" method="post"><input type="hidden" name="data" value="${myObj.someVal}"></form>

You should use the backticks to define a string with string interpollation: ``
Like this:
console.log(`1 and 1 make ${1 + 1}`);
This is from the typescript documentation :
Another common use case is when you want to generate some string out
of some static strings + some variables. For this you would need some
templating logic and this is where template strings get their name
from. Here's how you would potentially generate an html string
previously:
var lyrics = 'Never gonna give you up';
var html = '<div>' + lyrics + '</div>';
Now with template strings you can just do:
var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;
Note that any placeholder inside the interpolation (${ and }) is
treated as a JavaScript expression and evaluated as such e.g. you can
do fancy math.
console.log(`1 and 1 make ${1 + 1}`);

document.body.innerHTML += `<form id="digSigForm" action="${myObj.Url}" method="post"><input type="hidden" name="data" value="${myObj.someVal}"></form>`;
You forgot the backticks

This currently doesn't work.
I have a string like this, where the row's data attribute is relied upon for some functionality.
`<tr class="row ${rowHiddenClass}" data-someId="${this.someId}">
<td class="cell">${this.Notes}</td>
<td class="cell amount">$${this.Amount}</td>
</tr>`
And it outputs like this within the attribute strings, which breaks that functionality.
<tr class="row $" data-someId="$">
<td class="cell">A nice note</td>
<td class="cell amount">$4.00</td>
</tr>
We may have to do some concatenation for the time being.
I'm not sure yet what the cleaner, simpler solution is.
This works.
`<tr class="row ` + rowHiddenClass + `" data-someId="` + this.someId + `">
<!-- ... -->
</tr>`

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.

Javascript - How to use variable when writing table

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

Random commas in my HTML

I have commas between my HTML buttons and i don't know where they come from.
The div in which i create the buttons is empty before the buttons are being created.
In my JavaScript, i don't have any commas that could be put between the buttons as you can see below.
Here is a picture:
I create the buttons with JavaScript like so:
var f = "'";
contents[0]='<button class="btn" onclick="check('+ f + randomChar0 + f +');">' + randomChar0 + '</Button>';
contents[1]='<button class="btn" onclick="check('+ f + randomChar1 + f +');">' + randomChar1 + '</Button>';
contents[2]='<button class="btn" onclick="check('+ f + randomChar2 + f +');">' + randomChar2 + '</Button>';
ranNum0 = randomize(2);
document.getElementById("response").innerHTML = contents;
My HTML looks like this before i insert the buttons:
<div id="response" class="center-children">
</div>
And like this after i insert the buttons:
<div id="response" class="center-children">
<button class="btn" onclick="check('B');">B</button>,
<button class="btn" onclick="check('S');">S</button>,
<button class="btn" onclick="check('E');">E</button>
</div>
If i check in the Browser, it looks like this:
I checked my whole JavaScript, even tried to delete all the CSS and HTML but the commas remain there...
Does anyone have a clue what might cause this?
The problem is that you are assigning the string value of your array to .innerHTML and the string value of an array has commas between the elements.
In order to combine the values in your array, use .join():
document.getElementById("response").innerHTML = contents.join('');
Or better yet, don't use string manipulation to create DOM elements.
You're setting innerHTML to be an array, but it's supposed to be a string. Implicitly, .toString() is being called on your array, which leaves commas. Try it out, [1,2,3].toString() evaluates to "1,2,3".

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?

JavaScript not replacing all elements

I'm trying replace the index of form elements. I have the following
var test = "<input name='[1].Id' value='598' type='hidden' /><input name='[1].OrderItemId' value='867' type='hidden' />";
alert(test.replace('[1]', '[2]'));
I'm getting curious results. The first hidden field is replaced by the second is ignored
ie my response is something like this:
"<input name='[1].Id' value='598' type='hidden' /><input name='[2].OrderItemId' value='867' type='hidden' />"
EDIT:
OK, thanks these methods worked on my simple example. However in reality my string is a bit more complex. Here is the contents of "var lastRow "
<td>
<a class="deleteAddress" href="#">
<img alt="remove" src="/images/icons/delete_button.gif">
</a></td>
<td class="p-5" width="100">
<input name="[1].Id" value="612" type="hidden">
<input name="[1].OrderItemId" value="868" type="hidden">
<input class="itemAddressQuantity" name="[1].Quantity" value="" type="text">
</td>
<td class="p-5" width="100">
<select name="[1].AddressId"><option value="2">address1</option></select>
</td>
and here is the js function
$('#addNewAddress').click(function (event) {
event.preventDefault();
var length = $('.table-item-address tbody').find('tr').length;
var previousLength = length - 1;
var previousIndex = "/\[" + previousLength + "\]/g";
var currentIndex = "[" + length + "]";
var lastRow = $('.table-item-address tbody tr').last();
alert(lastRow.html()); // html is shown above
var newRow = lastRow.html().replace(previousIndex, currentIndex);
$('.table-item-address tr').last().after('<tr>' + newRow + '</tr>');
AdjustValues();
});
In JavaScript, passing a string as the first parameter to replace() will only replace the first occurrence. You need to use a regex, with the global flag:
test.replace(/\[1\]/g, '[2]');
The extra backslashes (\) escape the brackets ([ and ]).
Edit: responding to the OP's edit, if you want to dynamically build a regex, you can't use a regex literal - that's the thing delimited by forward slashes (/), not quotes (") as in your edit. You're passing a string into replace(), I'm passing in a regex literal. Use the JavaScript RegExp() constructor to fix yours:
// The first argument is the regex, the second is a string of flags.
var previousIndex = new RegExp("\\[" + previousLength + "\\]", "g");
// Then, it's exactly the same as before.
// The second argument to replace is still a string.
var newRow = lastRow.html().replace(previousIndex, currentIndex);
Note the difference in character escaping.
See here: http://www.w3schools.com/jsref/jsref_replace.asp
Check the 3rd sample where they talk about global replace
change the replace to this replace(/[1]/g, '[2]');
This does a global replace. However I'm not sure [] and . are legal characters for ids/names.

Categories

Resources