This is a project for uni for PHP/JavaScript. The concept is that we create an empty table, then get an input from the user and put this text in the odd lines of the table. Thing is, I've created the table and I can't get to pass the text to multiple paragraphs located inside the cells of the odd lines. I tried with getElementById to fill the cell's paragraph but I found out that each paragraph needs a unique id and so it fills only the first cell. Then I tried getElementsByClassName but this doesn't work cause there's no .innerHTML for it. Basically, all I want to do is take the same input and distribute it to multiple paragraphs or directly to the cells if there's a way. Code is at the bottom. The script doesn't work right now, I just left it in.
Thank you
<body>
<p class="p1">5th excercise Php</p><br><br><br>
<input type="button" id="btn" value="Give Input"><br><br>
<?php
echo "<table>";
for($i=1;$i<=10;$i++){
echo "<tr>";
for($j=1;$j<=10;$j++){
if($i % 2 == 0){
echo "<td style='background-color:green;color:green;'>"."<p>"."."."</p>"."</td>";
}
else{
echo "<td style='background-color:red; color:red;'>"."<p>"."."."</p>"."</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
<script>
document.getElementById("btn").onclick= function(){f()}
function f(){
var x= prompt("Give input");
document.getElementById("").style.color = "black";
document.getElementById("").innerHTML= x;
}
</script>
</body>
Since this is a homework assignment from school, I won't share any code samples.
Solution 1:
I would consider that the php loop already knows which rows are odd and even, so leveraging this with a class attribute would be easy enough.
Then use getElementsByClassName() to create a variable that can be iterated over in the javascript to fill in the values.
Solution 2:
Use getElementsByTagName() in your javascript to iterate over the TR's and calculate which rows are even or odd and make changes accordingly to the TD elements within .
This requires more work but will teach you more about how the getElement-style functions work.
You could add an id element to your paragraphs like this
"<p id='id_{$j}'>"
The 'id_{$j}' part will lead to to strings like id_0, id_1, etc.
Then you'd have to iterate through all columns in the JavaScript part and using those ids to set their innerHtml.
The difficulty you can meet, is that getElementByClassName renders an HTMLCollection, that is a pseudo collection but not something you can easily iterates over.
But you can steal (JS power!) the behavior of Array to that purpose. Like that:
const allCells = document.getElementsByClassName("first");
Array.prototype.forEach.call(allCells, function(elt) {
elt.innerHTML = choice;
});
So you just have to add a class name ("first" in my example) in the table cell you want (= the odd lines cells).
This can be achieved in different ways. Here i am giving you simple solution which simply add two classes even and odd in paragraph tag and using querySelector we can get all odd rows and add innerHtml easily.
document.getElementById("btn").onclick = function() {
f()
}
function f() {
var x = prompt("Give input");
document.querySelectorAll('.odd').forEach(p => {
p.innerHTML = x;
p.style.color='black';
});
}
<body>
<p class="p1">5th excercise Php</p><br><br><br>
<input type="button" id="btn" value="Give Input"><br><br>
<table>
<tr>
<td style='background-color:green;color:green;'>
<p class='even'></p>
</td>
</tr>
<tr>
<td style='background-color:red;color:red;'>
<p class='odd'></p>
</td>
</tr>
<tr>
<td style='background-color:green;color:green;'>
<p class='even'></p>
</td>
</tr>
<tr>
<td style='background-color:red;color:red;'>
<p class='odd'></p>
</td>
</tr>
<tr>
<td style='background-color:green;color:green;'>
<p class='even'></p>
</td>
</tr>
<tr>
<td style='background-color:red;color:red;'>
<p class='odd'></p>
</td>
</tr>
</table>
</body>
Here i have removed php code as i am not aware how to add it on stackoverflow but you can add your rows using php and it will work for you.
Related
My question is whether I can structure my HTML/JS to require less hardcoding in of ids. (this is what I had in mind by "efficiently").
As of now, I have a <table> with many <tr> table rows. Within each row are two cells( <td> table data elements). The first cell contains a checkbox, and an anchor link. The second <td> cell is just a text description of the link. They look like this:
<tr>
<td class="codecol">
<input type="checkbox">
<a title="I&C SCI 33" onclick="return showCourse(this, 'I&C SCI 33');">I&C SCI 33</a>
</td>
<td>Intermediate Programming</td>
</tr>
However, I want to strike through the link and text description if the checkbox is checked (and unstrike if unchecked). So I wrote a JS function as follows:
function checkStrikethrough(checkboxElemnt, rowData) {
//strikethrough text if checked
if (checkboxElemnt.checked) {
for(var i = 0; i < rowData.length ; i++) {
var elemnt = document.getElementById(rowData[i]);
elemnt.style.setProperty("text-decoration", "line-through");
}
}
// normal text if not checked
else {
for(var i = 0; i < rowData.length ; i++) {
var elemnt = document.getElementById(rowData[i]);
elemnt.style.setProperty("text-decoration", "none");
}
}
}
The problem I'm having with this is hardcoding in changes in the HTML file: the id's to pass as parameters. There's just so many rows that I began to wonder if there was a better way than modifying like this:
<tr>
<td class="codecol">
<input type="checkbox" onchange='checkStrikethrough(this, ["icsci33Link", "icsci33Td"]);'>
<a id="icsci33Link" title="I&C SCI 33" onclick="return showCourse(this, 'I&C SCI 33');">I&C SCI 33</a>
</td>
<td id="icsci33Td">Intermediate Programming</td>
</tr>
<tr>
<td class="codecol">
<input type="checkbox" onchange='checkStrikethrough(this, ["icsci45cLink", "icsci45cTd"]);'>
<a id="icsci45cLink" title="I&C SCI 45C" onclick="return showCourse(this, 'I&C SCI 45C');">I&C SCI 45C</a>
</td>
<td id="icsci45cTd">Programming in C/C++ as a Second Language</td>
</tr>
So, I am wondering -- is there some way to implement this that would require the least amount of effort to change the HTML? Ideally, is there a solution that would require only one or two uses of a "find-and-replace" in a text editor to change all the HTML?
Yes, you can do it with some simple DOM traversing.
Markup
<input type="checkbox" onchange="checkStrikethrough(this)">
JS
function checkStrikethrough(element) {
var elementToDelete = element.parentElement.nextElementSibling; // traversing the DOM, moving up to parent td, then on to next sibling td
element.checked ? elementToDelete.style.color = 'red': elementToDelete.style.color = 'black';
}
Please keep in mind that this solution requires your HTML structure to remain constant through all iterations of the table rows. Also, I'm just changing the font color in JS: you can style as you wish, now that you know how to target the element.
So I made this sliding puzzle using html, css and JavaScript:
this is a table and my question is how do I swap 2 table elements?
Let's say the one with the face (id = tile-2) and the white empy one (id = empty)
Hmm... try this:
https://jsfiddle.net/h7sp1ey8/
<button onclick='swap();'>
Swap
</button>
<table>
<tr>
<td id='f1'>
Contents of td 1
</td>
</tr>
<tr>
<td id='f2'>
Contents of t2
</td>
</tr>
</table>
<script>
function swap()
{
var f1 =document.getElementById('f1');
var f2=document.getElementById('f2');
var initialinner = f1.innerHTML;
f1.innerHTML=f2.innerHTML;
f2.innerHTML=initialinner;
}
</script>
Post your code if you want an exact solution. Here is how you program should work:
get id of box to swap
get id of box to swap to
swap them using method I gave in jsfiddle
I am using PHP Simple HTML DOM Parser for my project.
I am trying to find specific data and echo it after I parse my .php file from a URL Website which contains data inside HTML table element, example is below:
<table class="example">
<tbody>
<tr>
<td>
Heading #1
<p>Description of heading #1 here ...</p>
</td>
<td>Example of data #1</td>
</tr>
<tr>
<td>
Heading #2
<p>Description of heading #2 here ...</p>
</td>
<td>Example of data #2</td>
</tr>
</tbody>
</table>
My question:
How can I get value "Example of data #1" from the second TD cell element in first TR row element by knowing that the first TD cell in the same TR row contains value "Heading #1 ..." from this kind of a table?
I have parsed URL, now I need to find value based on the other value which is next to it.
Should I use some regex and make some pattern for that? strpos() and array?
You would need to give the table divisions an ID for JavaScript to be able to get the data for submission and put it into hidden inputs with names and IDs so that PHP will get them using POST.
<script language="javascript">
function transfer_data(){
documentGetElementById('ex1_hidden').value = documentGetElementById('ex1').innerHTML;
documentGetElementById('ex2_hidden').value = documentGetElementById('ex2').innerHTML;
submit();
}
</script>
<table class="example">
<tbody>
<tr>
<td id="hdg1">
Heading #1
<p>Description of heading #1 here ...</p>
</td>
<td id="ex1">Example of data #1</td>
</tr>
<tr>
<td>
Heading #2
<p>Description of heading #2 here ...</p>
</td>
<td id="ex2">Example of data #2</td>
</tr>
</tbody>
</table>
In your form which submits to wherever you want it to go using method="post" you would need:
<input type="hidden" name="ex1_hidden" id="ex1_hidden" />
<input type="hidden" name="ex2_hidden" id="ex2_hidden" />
<input type="button" value="Submit" onClick="transfer_data()" />
In PHP you would pick them up with $_POST['ex1_hidden'] and $_POST['ex2_hidden'] (remember to clean up submitted data.)
This is not a method which would be suitable for for secure data.
You could add an ID to the heading and make it conditional in your script:
if(documentGetElementById('hdg1').innerHTML == "Heading #1"){
documentGetElementById('ex1_hidden').value = documentGetElementById('ex1').innerHTML;
}
You might need to trim the whitespace off the heading perhaps by using something like
var str=documentGetElementById('hdg1').innerHTML.replace(/^\s+|\s+$/g,'');
Credit #Paul on how do I strip white space when grabbing text with jQuery?
Lots of useful ideas on other ways here How to get a table cell value using jQuery?
If this is scraped data from another website which you don't have control over at all, but which you already have in a PHP variable, you could explode() it by <td> and work out which array positions contain the data you want. Ref: http://php.net/manual/en/function.explode.php
This is what I think you are really looking for - might be a nice idea to ask the owner of the site if it is OK first but that is up to you. You were on the right track with strpos(); and arrays (tested using your table):
// only works if fopen is allowed on the site's server and in PHP5+
$handle = fopen("http://websiteyouwanttoscrape.com/file.html", "r");
$contents = stream_get_contents($handle);
$contents_array = array();
$bit_i_want = array();
// give yourself a chance
$contents = htmlspecialchars($contents);
// swap these if you don't use htmlspecialchars();
$contents_array = explode('<td>',$contents);
//$contents_array = explode('<td>',$contents);
$counter = 0;
while($counter < count($contents_array)){
if(strpos($contents_array[$counter], 'Heading #1') > 0 ){
// swap these if you don't use htmlspecialchars();
$bit_i_want = explode('</td>',$contents_array[$counter+1]);
//$bit_i_want = explode('</td>',$contents_array[$counter+1]);
echo $bit_i_want[0] . '<br />';
// uncomment break; to stop the loop if you don't
// want to look for any more instances of "Heading #1" if there were any
//break;
}
$counter++;
}
fclose($handle); //close the file
I am trying to get the value of a hidden input inside a tag in html table element through javascript in a MVC view. i have get the respective value of the hidden input which is in a loop,when the the respective row is clicked. I have tried many codes but it returns the value of the first row alone for all the rows in the table. i tried the following:
#foreach (var item in Model)
{
<tr>
<td hidden><input value="#item.QuoteId" id="QuoteID" class="QuoteID"> </td>
</tr>
}
javascript:
$("tr").click(function () {
var quoteid=document.getElementById("#QuoteID").innerHTML
alert(quoteid);
alert($('.QuoteID').val());
}
if my db contains 3 values for quote,say 12,17,18.. it alerts 12 for all the row clicks.. Pls help,I am literally stuck. I have been trying it from 3 days,i cant figure it out. I guess it is some simple mistake from my side. Pls help. I am not able to finish the work assigned to me because of this simple error.
You're using the same id multiple times. The ID has to be unique!! To make this to work you could call the unique id, or put a onclick on the specific row and call your function with this. In your function you can use this.value.
<script>
function ShowMeThePower(myElement) {
alert(myElement.innerHTML);
}
</script>
<div onclick="ShowMeThePower(this);">This is great!</div>
http://jsfiddle.net/3RJVd/
Edit:
To satisfy the OP:
<table>
<tr>
<td><input type="text" id="show1" value="test1" /></td>
</tr>
<tr>
<td><input type="text" id="show2" value="test2" /></td>
</tr>
</table>
<script>
for (var i = 1; i < 3; i++){
alert(document.getElementById('show' + i).value);
}
</script>
If you see, it's the same logic. Just be sure to use unique id's.
http://jsfiddle.net/4gMy6/
Is it possible to replace a table cell without deleting it with javascript or jQuery? For example, if I have a table with several rows, each row having 5 cells, could I change the first cell of the first row through assignment instead of removing the cell and then inserting a new one?
EDIT (simplified):
<table>
<tr id="currentRowId1" name="currentRowId1">
<td style="text-align:center">
</td>
<td style="text-align:center">
</td>
<td style="text-align:center">
<input type="submit" onclick="changeOrder()" />
</td>
<td style="text-align:center">
</td>
<td>
</td>
</tr>
<tr id="currentRowId2" name="currentRowId2">
<td style="text-align:center">
</td>
<td style="text-align:center">
</td>
<td style="text-align:center">
<input type="submit" onclick="changeOrder()" />
</td>
<td style="text-align:center">
</td>
<td>
</td>
</tr>
</table>
js
function changeOrder(){
var row = document.getElementById("currentRowId1");
var otherRow = document.getElementById("currentRowId2");
row.cells[0] = otherRow.cells[0];
}
There is acutally no need to work with innerHTML here. You could replace the two elements like this:
var
a = document.getElementById('currentRowId1').cells[0],
e = document.getElementById('currentRowId2').cells[0],
e1 = e.nextSibling;
a.parentNode.replaceChild(e, a);
e1.parentNode.insertBefore(a, e1);
demo: http://jsfiddle.net/X4zzb/1/
There are multiple ways to do this. You can set the inner html of the cell as fabianhjr pointed out. You can also build a new element in javascript/jquery and use jquery's replaceWith() method.
You can use other jquery methods that will replace the cells, clone() and before() or after() I know this isn't what you asked for just pointing out other options.
Example #1:
var me = $("#cellId");
var newHtml = $("<div>blah blah blah</div>");
me.replaceWith(newHtml);
Example #2:
var me = $("#cellId");
var clone = me.clone();
// do some cool things with the clone change html whatever
me.replaceWith(clone);
If you just want to change whats inside it you can use..
document.getElementById('nameofyourcell').innerHTML = 'content';
You can't just assign the cell equal to something else like you tried in this line:
row.cells[0] = otherRow.cells[0]; // doesn't work
However, once you have a reference to the cell you can change what is inside it, e.g., to copy the contents from one cell to another:
row.cells[0].innerHTML = otherRow.cells[0].innerHTML;
You can also create, amend or remove the children of the cell via the reference to the cell.
If you are using jQuery there are a number of methods that achieve the same sort of thing, e.g., the following is equivalent to the above (but less efficient):
$(row.cells[0]).html( $(otherRow.cells[0].html() );