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.
Related
I have the following code:
function addComma() {
// get textarea's content
var content = document.getElementById('myTextArea').value;
// replace all newline's with ';\n'
var replaced = content.replace(/\n/g, '\',\n');
// rewrite the content with the new content
document.getElementById('myTextArea').value = replaced;
}
<textarea id='myTextArea' rows='5' cols='30'>
First Line
Second Line
Third Line
</textarea>
<input type='button' onclick='addComma()' value='Add Comma' />
http://jsfiddle.net/jw7t68f5
How can I add an ' at the beggining of each line BUT remove the comma on the last line. (I will be having more than three rows.)
Thanks in advance!
Here's a slightly different approach that I think get's the result you're looking for:
var replaced = content.split('\n').map(l => "'" + l + "'").join(',\n')
What this will do is split the content into an array (by the new line), the map function will basically loop through each line and add ' at the start and end, finally join will join the array back into a string using a comma and new line
My filter makes sure there are no empty lines; No need for substring fiddling around.
var replaced = content.split('\n').filter(p=>p!="").map(p=>'\''+p).join(',\n');
Use split and map:
function addComma() {
var content = document.getElementById('myTextArea').value;
//Add in commas and speech marks
var replaced = content.split("\n").map(e => `'${e}',`).join("\n");
//Remove last comma
replaced = replaced.substring(0, replaced.length - 1);
//Put text back into page
document.getElementById('myTextArea').value = replaced;
}
<textarea id='myTextArea' rows='5' cols='30'>
First Line
Second Line
Third Line</textarea>
<input type='button' onclick='addComma()' value='Add Comma' />
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
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>`
I am trying to remove the last characters from the following html code
<tbody><tr><tr>1<td><label for='depart1'>Department 1</label><br /><input type='text' id='depart1' class='textbox large' value='IT' /><br><label for='Courses_for_depart1'>Course for Department 1</label><br /><textarea id='Courses_for_depart1' class='textarea large' >OS</textarea></td></tr></tbody>
with the following code
addHtml.slice(0,-13);
It should remove </tr></tbody> But it removes only ></tbody>
how to get rid of this strange behavior.
update
addHtml=$("#departments").html();
<table id="departments">
<tbody><tr><tr>1<td><label for='depart1'>Department 1</label><br /><input type='text' id='depart1' class='textbox large' value='IT' /><br><label for='Courses_for_depart1'>Course for Department 1</label><br /><textarea id='Courses_for_depart1' class='textarea large' >OS</textarea></td></tr></tbody> </table>
The above snippet is copied form view source code of chrome.
There are probably white space between the closing </tbody> tag and the </tr> tag. Try something like this:
addHtml = addHtml.trim();
var tbody = '</tbody>';
var t1 = addHtml.indexOf(tbody)+tbody.length;
var t2 = addHtml.lastIndexOf('</tr>');
var len = t1-t2;
var newString = addHtml.slice(0,-len); // This will have the string without the </tr> </tbody>
Since your addHTML contains spaces at the end and the beginning, so you need to trim all the spaces at start and end before using slice function so use
$.trim(addHtml).slice(0,-13);
Working demo
As a possibly safer alternative, you could do this in two steps:
1) find the last </tbody> in the string, then slice up to it.
2) find the last </tr> in the remaining string, then slice up to that.
String.prototype.lastIndexOf()
I've got this error being reported in firebug, but I have no idea what it means:
Identifier starts immediately after numeric literal
Here is my webpage:
http://www.austintreeexperts.com/maps/optionUpdateMap.cfm?zoom=15
When the page and map loads, click on one of the blue or green markers. Then click on one of the check boxes to get the error. I have an onclick= for the input checkboxes.
Your string concatenation is broken. You need to wrap your method parameters in quotes
var statusForm = '<input id="tU'+Aid+'" type="checkbox" onclick="optionAUpdate(tU'+Aid+', '+color+', '+optionB+')"/> option A | <input id="iU'+Aid+'" onclick="optionBUpdate(iU'+Aid+', '+color+', '+optionA+')" type="checkbox"/> options B';
From here ----------------------------------------------------------------------------^
Corrected version
var statusForm = '<input id="tU' + Aid + '" type="checkbox" onclick="optionAUpdate(\'tU' + Aid + '\', \'' + color + '\', \'' + optionB + '\')"/> option A'
Note : I've treated all your params as strings
Your onclick needs to be:
optionAUpdate('tU20238', '75AB5F', 0)
Note that I wrapped the params in quotes as they are strings.
This message also appears if you've tried to name a variable starting with a numeral. eg.
var 2ndString = 'abc';
<input
id="is-ib-checkbox"
value='+accWidgetData[count]["userAccountNumber"]+'
onchange="addaUserAccount(\'' + accWidgetData[count]["userAccountNumber"] + '\' );"
value="true"
checked="checked"
type="checkbox"
/>
For this case, in my code:
html.input()
.onclick("selectItem(" +"'"+cons.getIdentificacion().toString()+"'" + ");")
.type("radio")
.name("selectedItem")
.style("vertical-align: text-bottom")
.close();
works Fine.