I've got a piece of code that duplicates a <table> but in the process changes id's. It took hours but I eventually got this to happen with:
var lookFor = 'url' + parseInt(uploadCount);
++uploadCount; //used to create a unique id
var replaceWith = 'url'+parseInt(uploadCount);
var regex = new RegExp(lookFor, 'g');
var tableHTML = '<table class="user-url-table" style="opacity:0;" id="url' + uploadCount + '">' + $('table.user-url-table').first().html().replace(regex, replaceWith) + '</table>';
$(tableHTML).insertAfter($('table.user-url-table').last());
However, the following doesn't work:
var lookFor = 'url' + parseInt(uploadCount);
var tableHTML = '<table class="user-url-table" style="opacity:0;" id="url' + uploadCount + '">' + $('table.user-url-table').first().html() + '</table>';
++uploadCount;
var replaceWith = 'url'+parseInt(uploadCount);
var regex = new RegExp(lookFor, 'g');
tableHTML = $('table.user-url-table').first().html().replace(regex, replaceWith);
But shouldn't they do exactly the same job....? The first piece of code surely just does everything in one line, whereas the second forms the <table> and then changes all instances of the id in it.
There are two errors on the second code. First, when you do tableHTML = $('table.user-url-table').first().html().replace(regex, replaceWith); on the last line, you throw away the preparation you did. You override the value of tableHTML.
The second error is that the result is not appended to the document, like you did with insertAfter in the first code.
To make if work, replace the last line with $('table.user-url-table').after(tableHTML.replace(regex, replaceWith));. This will insert tableHTML with the replaced id's after the first table.
Another way, much simpler, of doing the same thing is this:
var firstTable = $("#url1 tbody").html();
var result = "";
for (i = 2; i < 10; i++) {
result += '<table class="user-url-table" style="opacity:0.2;" id="url'
+ i + '">' + firstTable.replace("url1", "url" + i) + '</table>';
}
$("#url1").after(result);
Fiddle: http://jsfiddle.net/bortao/ydEPr/
Related
I added a select to a column of table cells with an ID. Using console.log I can see the select with the ID I gave it but when I try to set the value of the box using the ID I get a NULL reference error. What would the correct reference be for the box? Thanks.
JavaScript
function GetProc_Responce(r, responce) {
var table = "<tr><th>Emp</th><th>RA</th><th>PI</th><th>First Name</th><th>Last Name</th><th>Is A</th><th>Date Created</th><th>Date Modified</th></tr>";
strXml = new XMLSerializer().serializeToString(responce);
//console.log("returnString: " + strXml);
var oParser = new DOMParser();
oDOM = oParser.parseFromString(strXml, "text/xml");
//console.log(oDOM.getElementsByTagName("EmployeeID").length);
var l = oDOM.getElementsByTagName("EmployeeID").length;
for (i = 0; i <= l - 1; i++) {
a = oDOM.getElementsByTagName("Emp")[i];
_Emp = a.childNodes[0].nodeValue;
b = oDOM.getElementsByTagName("RA")[i];
_RA = b.childNodes[0].nodeValue;
c = oDOM.getElementsByTagName("PI")[i];
_PI = c.childNodes[0].nodeValue;
d = oDOM.getElementsByTagName("FirstName")[i];
_FirstName = d.childNodes[0].nodeValue;
e = oDOM.getElementsByTagName("LastName")[i];
_LastName = e.childNodes[0].nodeValue;
f = oDOM.getElementsByTagName("IsA")[i];
_IsA = f.childNodes[0].nodeValue;
g = oDOM.getElementsByTagName("DateCreated")[i];
_DateCreated = g.childNodes[0].nodeValue;
h = oDOM.getElementsByTagName("DateModified")[i];
_DateModified = h.childNodes[0].nodeValue;
table += "<tr><td>" +
a.childNodes[0].nodeValue + "</td><td>" +
b.childNodes[0].nodeValue + "</td><td>" +
c.childNodes[0].nodeValue + "</td><td>" +
d.childNodes[0].nodeValue + "</td><td>" +
e.childNodes[0].nodeValue + "</td><td>" +
//f.childNodes[0].nodeValue + "</td><td>" +
"<select id=\"s1\"><option value=\"0\">0</option><option value=\"1\">1</option></select>" + "</td><td>" +
g.childNodes[0].nodeValue + "</td><td>" +
h.childNodes[0].nodeValue + "</td></tr>";
document.getElementById('Proc').rows.item(3).cells(5).value = 1;
//OR
document.getElementById('s1').selectedValue = 1;
//NEITHER ONE WORKS
}
document.getElementById("Proc").innerHTML = table;
console.log(document.getElementById('Proc').rows(3).cells(5));
}
HTML
<div><center>
<table id="Proc"></table>
</center></div>
You must assign unique id values. Your code assigns all of them the id value s1 which is invalid in HTML.
Change your code as follows to assign s0, s1, s2 ... etc. For clarity I don't repeat the code that is not concerned:
for (i = 0; i <= l - 1; i++)
{
// ...
table += "<tr><td>" +
// ...
e.childNodes[0].nodeValue + "</td><td>" +
"<select id=\"s" + i + "\"><option value=\"0\">0</option><option value=\"1\">1</option></select>" + "</td><td>" +
// ...
}
You can access one of the select elements by its id with getElementById:
var element = document.getElementById('s' + i);
Where i is a number from 0 to the last one assigned in the loop.
You can get or set the value of a select element via its value attribute. For example, to set its value to 1, do:
document.getElementById('s' + i).value = '1';
Here we'll get div object
var div = document.getElementById('test');
Here we'll get table object
var table = div.getElementsByTagName('table')[0];
Here we'll add new select to td
table.rows[0].cells[0].innerHTML += '<select id="s2"></select>';
Search existed select (with id="s1")
var select_1 = table.rows[0].cells[0].getElementsByTagName('select')[0];
console.log(select_1);
Search all selects in td
var select_array = table.rows[0].cells[0].getElementsByTagName('select');
console.log(select_array);
https://jsfiddle.net/e59dzhsy/
document.getElementById('Proc').rows.item(3).cells(5) references a td, which does not have a value.
document.getElementById('s1') references the select box
you want document.getElementById('Proc').rows.item(3).cells(5).children[0] to reference the select
A better method would be to use some of the built in tag finding functions such as document.getElementById('Proc').rows[3].getElementsByTagName('select')[0]. Then you don't have to deal with what column the select is in. Of course, if you have more than one select on the row, then you'll need to do something different. At that point, I'd suggest adding class names to your selects so you can use document.getElementById('Proc').rows[3].getElementsByClassName('select1')[0]
I have a set of urls that i need to get a specific part of . The format of the url is :
http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg
I need to get the 1234567 bit and store that in a var.
Well you can do splits
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".split("/").pop().split("_").shift()
or a regular expression
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".match(/\/(\d+)_\d+\.jpg$/).pop()
You should be able to get it to work with your JSON string by checking the URL with a function. Something like this should work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
$.get("test.php", function (data) {
// now you can work with `data`
var JSON = jQuery.parseJSON(data); // it will be an object
$.each(JSON.deals.items, function (index, value) {
//console.log( value.title + ' ' + value.description );
tr = $('<tr/>');
tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
//tr.append("<td>" + value.description + "</td>");
tr.append("<td> £" + value.price + "</td>");
tr.append("<td class='temperature'>" + value.temperature + "</td>");
tr.append("<td>" + "<a href='" + value.deal_link + "' target='_blank'>" + "View Deal</a>" + "</td>");
myvar = checkForMatches(value.deal_link);
if(myvar == false) {
myvar = value.deal_link; //if no matches, use the full link
}
tr.append("<td>" + "<a href='" + myvar + "' target='_blank'>" + "Go To Argos</a>" + "</td>");
$('table').append(tr);
});
});
Earlier, more basic examples.
You can use a regular expression to find the match.
Something like this would work:
var str = "http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg";
var res = str.match(/.*\/(.*)_1.jpg/);
alert(res[1])
If you wanted to go a little further with it, you could create a function and pass the strings you wanted to test, and it would return the matched value if found, or boolean false if no matches exist.
Something like this would work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
alert(checkForMatches("http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg"))
alert(checkForMatches("this is an invalid string"))
You can see it working here: https://jsfiddle.net/9k5m7cg0/2/
Hope that helps!
var pathArray = window.location.pathname.split( '/' );
to split 1 / 2/ 3/ 4...
So to get path 2 it would be:
var setLocation = pathArray[1];
Well This should do
function getLastFolder(){
var path = window.location.href;
var folders =path.split("/");
return folders[folders.length-1]);
}
Here's the idea: take everything that comes after the final / character, and then take everything within that substring that comes before the first _ character.
var getUrlTerm = function(url) {
var urlPcs = url.split('/');
var lastUrlPc = urlPcs[urlPcs.length - 1];
return lastUrlPc.split('_')[0];
}
You can attribute the url to an 'A' element and use javascript's built in methods to make your life easier:
var parser = document.createElement('a');
parser.href = "YOUR URL HERE";
var fileName = parser.pathname.split('/').pop();
var code = fileName.split('_')[0];
code will have the value you want.
I would use a regular expression and sense it seems you are looking for numbers you can do the regex filter for that.
var path = window.location.pathname,
regFilter = /\d*/g,
filter = regFilter.exec(path);
The regular expression \d narrows your filter search to only look for digits. And the * grabs the group of digits.
Your result is in the filter var. The only thing about this is that the exec returns an array with your original string and the returned result which will be at the 1 index so you'll have to grab it from there like so.
filter[1];
I'm having a small problem with a regexp pattern. I don't have regexp knowledge, so I couldn't solve it.
I have this text:
var text = "this (is) some (ran)dom text";
and I want to capture anything between (). So after following this tutorial I came up with this pattern:
var re = /(\(\w*\))/g;
which works fine. But what I want to do now is replace the found matches, or rather modify. I want to wrap the found matches with a span tag. So I used this code:
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
text.replace(re, spanOpen + text.match(re) + spanClose);
even though the code works, I don't get the result I want. It outputs:
as HTML
this <span style="color: silver;">(is),(ran)</span> some <span style="color: silver;">(is),(ran)</span>dom text
as text
this (is),(ran) some (is),(ran)dom text
You can check the example in fiddle. How can I fix this?
The code in fiddle:
var text = "this (is) some (ran)dom text";
var re = /(\(\w*\))/g;
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
var original = "original: " + text + "<br>";
var desired = "desired: this " +spanOpen+"(is)"+spanClose+ " some " +spanOpen+"(ran)"+spanClose+ "dom text<br>";
var output = "output: " + text.replace(re, spanOpen + text.match(re) + spanClose);
var result = original + desired + output;
document.body.innerHTML = result;
If the title is wrong or misleading, I'll change it.
The .replace() method can take a function as the 2nd parameter. That will come in handy here.
var output = "output: " + text.replace(re, function(match){
return spanOpen + match + spanClose
});
The function will be called for each individual match.
You can also use '$&' in your replace string to reference each match
var output = "output: " + text.replace(re, spanOpen + '$&' + spanClose);
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
text.match(re) is returning an array of the result, so what you can do is loop this array and replace your string with each items, like this:
var matches = text.match(re);
var output = "output: " + text;
for (var i = 0; i < matches.length; i++)
{
output = output.replace(matches[i], spanOpen + matches[i] + spanClose);
}
See this FIDDLE
I have an array object that needs another array object added to it. So i have details of the object that need the rows in a table to be added to that object as an array. I have tried a few suggestions on stackoverflow , but none seems to be working, and i am not sure this has something to do with the fact that the table is created by js.
// Adding Cosignment number
$('#parcel-overview').append(
// Add main tables which will display the added packages
'<table border="1">' +
'<thead><tr><th>Packages</th><th>Weight</th> <th>Vol Weight</th><th>Charge Weight</th> <th>Price</th></tr></thead><tbody id="parcels-added-overview"></tbody> ' +
'</table>'
);
for (var i = 0; i < packageNum; i++) {
var ii = (i + 1).toString();
// Working out volemetric weight
wei = $('#added-parcels #weighting-' + ii + ' input').val();
len = $('#added-parcels #lengthing-' + ii + ' input').val();
wid = $('#added-parcels #widthing-' + ii + ' input').val();
hei = $('#added-parcels #heighting-' + ii + ' input').val();
//Calculating Volumetric weight
tot = ((len * wid * hei) / 5000).toFixed(1);
pri = (tot * 23).toFixed(2);
chr = (tot * 12).toFixed(2);
$('#parcels-added-overview').append(
'<tr>' +
'<td class="par-id">' + (i + 1).toString() + '</td>' +
'<td class="par-weight">' + wei.toString() + ' kg\'s</td>' +
'<td class="par-vol-weight">' + tot.toString() + ' kg\'s</td>' +
'<td class="par-charge-weight">R ' + chr.toString() + '</td>' +
'<td class="par-price">R ' + pri.toString() + ' </td>' +
'</tr>'
);
}
I then want to add the values of that table that have been added dynamically to an object array that is then added to the primary object array.
var parcelObj = new Object();
$.each($('#parcels-added-overview tr'),function (index) {
parcelObj.parcelId = $(this).children('.par-id').text();
parcelObj.totalWeight = $(this).children('.par-weight').text();
parcelObj.volWeight = $(this).children('.par-vol-weight').text();
parcelObj.chargeWeight = $(this).children('.par-charge-weight').text();
parcelObj.overallPrice = $(this).children('.par-price').text();
parcelsArr.push(parcelObj);
});
consignmentObj.parcels = parcelsArr;
consignmentsArr.push(consignmentObj);
I might be a n00b , but this code (although i think its fairly verbose ) should work.
Does the $(this).children not identify directly on each() row that it is iterating over?
When i add console.log(consignmentsArr); i get the array within the object as it should be but the values for the parcel object are just repeating the last row of the table.
1: Object
deliName: ""
deliStreet: ""
docType: "Document"
insurance: "None"
parcels: Array[2]
0: Object
chargeValue:"R34.43"
overallPrice:"R43.54"
parcelId:"2"
totalWeight:"65 kg's"
volWeight:"63 kg's"
1: Object
chargeValue:"R34.43"
overallPrice:"R43.54"
parcelId:"2"
totalWeight:"65 kg's"
volWeight:"63 kg's"
Why can I not get the first row values to be added to parcels[0]?
Thanks
Try to declare parcelObj object inside the function.
$.each($('#parcels-added-overview tr'),function (index) {
var parcelObj = new Object();
parcelObj.parcelId = $(this).children('.par-id').text();
parcelObj.totalWeight = $(this).children('.par-weight').text();
parcelObj.volWeight = $(this).children('.par-vol-weight').text();
parcelObj.chargeWeight = $(this).children('.par-charge-weight').text();
parcelObj.overallPrice = $(this).children('.par-price').text();
parcelsArr.push(parcelObj);
});
consignmentObj.parcels = parcelsArr;
consignmentsArr.push(consignmentObj);
I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}