Change script to enter text in a div, not textarea - javascript

I'm working on a job with a developer who is taking care of coding that's beyond my ability; mostly PHP and more complex Javascript (I'm only okay at jQuery).
Part of the work the developer has been doing involves checking a database and dynamically entering results into the page. The problem is that currently these results are entered into a <textarea>, which is not ideal as it means that if it's readonly, the results cannot be deleted if the user changes their mind. If it's not readonly, the user can enter any text they like into the textarea, rendering the page unusable. In addition, I'm unable to apply any CSS to the results within the textarea.
Also, the developer is using tables, one of my pet hates.
I would like the <textarea> to be instead a <div> containing a <div> for each database result found.
The developer is currently away for a few weeks and I would prefer to get this done sooner rather than later. I've tried changing "td" simply to "div" but obviously that didn't work.
I'd really appreciate some help. I've included the code below. Unfortunately, I'm unable to give access to the live/testing site (beyond my control) and apologise for that.
if(answer)
{
var newRow = document.getElementById("target_table");
var Row = newRow.rows.length;
var row1 = newRow.insertRow(Row);
var index=row1.rowIndex;
var td1= document.createElement("TD")
var td2= document.createElement("TD")
td2.innerHTML = "
<INPUT TYPE='hidden' NAME='course"+Row+"' id='course"+Row+"' value='"+answer+"'>
<INPUT TYPE='hidden' NAME='ary"+Row+"' id='ary"+Row+"'>
<INPUT TYPE='hidden' NAME='Dary"+Row+"' id='Dary"+Row+"'>
<p class='courseName'>"+answer+"</p>
<div id='boxRw"+Row+"' class='boxyHolder'>
<TABLE border=1 cellspacing=2>
<TR>
<TD>
<INPUT TYPE='button' name='Add a favourite to this course' value='Add a favourite to this course' onclick='javascript: window.open(\"<?=$path?>add-my-favourites/"+Row+"\",\"mywindow\",\"left=550,top=200,width=400,height=350,toolbar=1,resizable=0\");'>
</TD>
</TR>
<tr>
<td colspan=2>
<TABLE border=1>
<TR>
<TD valign=top>Favourites:</TD>
<TD>
<TEXTAREA class='fav-box' NAME='reps"+Row+"' id='reps"+Row+"' ROWS=4 COLS=45></TEXTAREA>
<input class='fav-box' TYPE='hidden' NAME='repsId"+Row+"' id='repsId"+Row+"' value=''>
</TD>
</TR>
</TABLE>
</td>
</tr>
</TABLE>
</div>";
row1.appendChild(td1);
row1.appendChild(td2);
document.getElementById("h").value=Row;
}
function setVal(){
var r = "<?=$_GET['hVal']?>";
var y = "reps"+r;
var y1 = "repsId"+r;
window.opener.document.getElementById(y).value+=document.frm.favourites.value+',';
window.opener.document.getElementById(y1).value+=document.frm.recp_listId.value+',';
window.close();
}
Edit: I believe these are the lines I need to change:
window.opener.document.getElementById(y).value+=document.frm.recipes.value+',';
window.opener.document.getElementById(y1).value+=document.frm.recp_listId.value+',';
I think the problem is that these lines are adding the value to what is currently a <textarea>. When I change the textareas to divs, the values are not applied to the divs. So I need to change the code so that it enters the results as text in the divs - not values.

If you use a div, use its textContent property, not value like you'd use for form controls such as textarea and input. You are getting no error because you're ending up creating a value property on the div.
Code snippet #1
var div = document.createElement('div');
div.textContent = document.frm.recipes.valu‌​e;
window.opener.document.getElementById(y).appendChild(div);

Related

Attempting to Overwrite HTML with JavaScript

I am doing an inventory table with html and I am attempting to overwrite a paragraph. I saw that it was possible to do
document.getElementById(“Myid”).innerHTML= variable;
And this worked on the online coding environment they demonstrated it on.
However. I’m attempting to do this for a website.
In a table that looks like
function myfunction(){
console.log(“howdy”);
const form =document.getElementById(“form1”);
const formN = form.elements[0];
let formNval = Number(formN.value);
document.getElementById(“Myid”).innerHTML= formNval;
}
<table>
<tr>
<td>
<p id=“Myid”>69</p>
</td>
<td>
<form id=“form1” onsubmit=“myfunction()” method=“post” action=“#”>
<input type=“number” min=“1”>
<button type=“submit” value=“Submit”>
</form >
</td>
</tr>
</table>
I previously tried to give my table data element an ID in order to do this but I switched it to adding a p element inside the table data element because that’s what the example showed. I run this on VSCode debugger and a go live extension but it only appears for a second then goes back to the original content. How can I make the change stay? Is there a way to place a variable inside the p element specifically made to save changes while running on a server?
My full JavaScript is just a test function that contains a console log for testing and the document. GetElementById line.

Change div color on checking all check boxes in hidden form

Have several problems and can't find solution. My code https://jsfiddle.net/46qybyrh/2/
Upper table HTML
<div class="block">
<table>
<tr>
<th>Nr.</th>
<th style="width: 200px">Task</th>
<th>Progresas</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>Air port scedules</td>
<td>0/3</td>
<td>
<button onclick="showDiv()">Expand</button>
</td>
</tr>
</table>
Hidden div
<div id="popup" class="popupbox">
<table class="block">
<tbody>
<tr>
<td></td>
<form>
<td>XML</td>
<td>
<span>Comment</span><br>
<textarea></textarea>
</td>
<td>
<span>Deadline</span>
<input type="date" value="2017-08-24">
</td>
<td>Done:<input type="checkbox"></td>
<td><input type="submit" value="Apply"></td>
</form>
</tr>
<tr>
<td></td>
<form>
<td>Scedules</td>
<td>
<span>Comment</span><br>
<textarea></textarea>
</td>
<td><span>Deadline</span>
<input type="date" value="2017-08-10">
</td>
<td>Done:<input type="checkbox"></td>
<td><input type="submit" value="Apply"></td>
</form>
</tr>
<tr>
<td></td>
<form>
<td>Infobox</td>
<td>
<span>Comment</span><br>
<textarea></textarea>
</td>
<td><span>Deadline</span>
<input type="date" value="2017-08-14">
</td>
<td>Done:<input type="checkbox"></td>
<td><input type="submit" value="Apply"></td>
</form>
</tr>
</tbody>
</table>
<button onclick="hideDiv()">close</button></div>
Main aims of this code should be:
When press apply on each row, hidden div should not hide. Only information like comment, date, check box should change.
When all 3 check boxes are selected, upper tables first row (1 Air port scedules 0/3) should change its background color.
If deadline is close (let say 5 days till deadline) entire row should change background color.
If deadline is passed entire row should change its background color.
I know its a lot to ask but maybe someone of you will guide me on each of this steps.
I took your fiddle and put it into a codepen and messed around with it for a while. I was able to do what you wanted with a lot of jQuery. To learn jQuery, try www.w3schools.com/jQuery.
Here is the codepen:
https://codepen.io/pen/Ojxzje
In a few short steps:
I removed all the <form> tags, <input type='submit'>, and <tbody> to make the code cleaner (the submit button was causing problems with hiding the div as mentioned by #AngeLOL.
I reformatted the lower table a bit just to make it cleaner for my jQuery to work nicely. (I added a header row and removed the text from the blocks)
I included the jQuery library
I renamed your jQuery functions and created one more (open(), close(), and apply(). They are called by the buttons respectively.
Inside the open() function, I showed the rows in the second table with the class if items-[ID OF LIST WE ARE IN]. This way there could be a clean list of all of the tasks instead of having a new table for every new list.
The open() function also changes the button from expand to hide which calls the close function.
The close() function just hides the second table and changes the name of the button back to expand.
The apply() function is run whenever you press the Apply button. It performs two checks:
Checks all of the checkboxes in the table rows labeled .details-[ID WE ARE WORKING WITH] and if they are all checked, selects the list's row in the upper table. It adds a green color to the background.
It then finds all the dates and compares them with today's date (thanks again #angeLOL. If the date is within 5 days, it selects the row the date was on and changes the color. If the date has passed or is today, it colors the row red.
It's a lot of code and a bunch of reorganization, so let me know if you are having trouble understanding it and I can help walk through my steps.
use <button type="button">Apply</button> instead <input
type="submit" value="Apply">
Give to those elements you want to change its color an "id" attribute, so change its color by using style propierty of element
document.getElementById("elementID").style.backgroundColor = "#colorcode"
Here is an example of how to compare dates.
Hidden div is initially hidden. When you submit the form, you reload the page, so it is hidden again. You may want to handle click on button or form submit, prevent default behavior, submit data via AJAX request and then update your UI without page reload.
<form onsubmit="return handleSubmit(this);">
...
<input type="checkbox" onchange="updateCheckboxesState();">
</form>
<script>
function handleSubmit(form) {
// send AJAX request here...
// manipulate DOM if needed in AJAX callback
return false; // prevent submit
}
function updateCheckboxesState() {
var checkboxes = document.querySelectorAll("form input[type=checkbox]");
for (var i = 0; i < checkboxes.length; i++) {
if (!checkboxes.item(i).checked) return; // break on first unchecked
}
// highlight the row here...
}
</script>
Similar flow can be applied to date inputs. The main idea is to update UI when value has been changed.
Background change can be achieved via changing element's inline style or changing it's class
var el = document.querySelector("div.block > table > tr");
el.style.backgroundColor = "#FF0000"; // inline
el.className = "highlighted"; // element class
Hope, this helps...

Can't find form after injecting it with jQuery(I think)

Im adding the form, in an on-click event, to a row in a table using (Sorry about the really long row):
$('#row'+rowvalues[0]).html('
<form id="updform'+rowvalues[0]+'">
<td>'+rowvalues[0]+'</td>
<td>
<input type="text" name="namn'+rowvalues[0]+'" value="'+rowvalues[1]+'">
</td>
<td>
<input type="text" name="ingred'+rowvalues[0]+'" value="'+rowvalues[2]+'">
</td>
<td>
<input type="number" name="pris'+rowvalues[0]+'" value="'+rowvalues[3]+'">
</td>
<td>
<input type="number" name="fampris'+rowvalues[0]+'" value="'+rowvalues[4]+'">
</td>
<td>
<Button class="upddatasave" id="sub'+rowvalues[0]+'">Submit</button>
</form>
</td>
');
intialiseUpdatebutton();
then I initialize the button using the fuction called intialiseUpdatebutton();
that function looks like:
function intialiseUpdatebutton() {
$(".upddatasave").on("click", function() {
var butid = $(this).attr('id');
var dataid = parseInt(butid.slice(3));
console.log(dataid);
console.log($('#namn'+dataid).val());
var formvalues = $('#updform'+dataid).serializeArray();
console.log(formvalues);
});
}
It finds the button and it works, but I can't find the form. My guess was that it cant find the injected form, but if that's the case how do I fix it? like I do with the initialise function for the button.
What Im trying to do: Im displaying data from an SQL table in a table in html - It has 2 buttons 1 update and 1 delete. Im trying to fix the update button so that when I press it the cells with the values change into a form with textfields and the values in there and then you can just change the values and press submit to save the changes.
Edit: jsfiddle.net/rh8deo79/2 <- jsfiddle
By editing your formmatting job to break up the massive one-liner, I found that you end your <form> before your <td>, which is invalid html and probably your source of error.
You need to reorganize your tags. You can't have <tr><form><td>, as described here.
You might try creating a new table inside each form.

Get javascript calulations to post as form data and display in php page

I am somewhat familiar with JavaScript and php and very familiar with HTML but have limited experience in getting them to work together. I have looked at many examples and am either not understanding or other posts do not specifically address my situation. I am trying to accomplish two things at the time of form submission. One is to retrieve the information from a div populated by innerHTML to post with the form and the other is to generate a unique number for the transaction at form posting and then display.
I have an HTML form that displays a generated list, each of which has a check box beside it. When a check box is selected I am using onclick="calTotal()" to calculate and display the total of all boxes checked. Code listed below.
The display script works perfectly and displays a value such as Total $125.00. What I need to do is post that total value when I post the form. The only value being passed at this time is the last check box value. Should that total be assigned within the JavaScript or should it be assigned within an input field?
The second part of my question is with the value of my algorithm that creates a unique transaction number. I want to generate that number upon submission of the form but then need to have it display on the php page. I have tested my algorithm separately and know it works correctly when I hard code the values in. I need to take values from the form and use them to calculate the transaction number. Once calculated it needs to be passed to the php page. Again I am not completely sure where to assign the value so that it passes to the next page.
Anything that will get me pointed in the right direction is appreciated.
<script type="text/javascript">
function calTotal() {
var ch, i=0;
var total=0;
while(ch=document.getElementsByName("amt")[i++]) {
if (ch.checked)
{
total=total+Number(ch.value);
}
}
var div=document.getElementById('divTotal');
total="$"+total.toFixed(2);
div.innerHTML= "Total: " +total;
return total;
}
function calTrans(x,y,z)
{
do calculations here
// concatenate into Trans number
var transNum=rm.concat(em,tm,am);
return transNum;
}
</script>
<form id="frmcheckout" action="out.php" method="post" onsubmit=calTrans()>
<table cellspacing="25">
<tbody>
<tr>
<th>Selection</th>
<th>Title</th>
<th>Cost</th>
</tr>
<tr>
<td>
<input type="checkbox" name="amt" value="$cost" onclick="calTotal()"></td>
<td>$Title</td>
<td>$cost</td>
</tr>
#end
</tbody>
</table>
<table>
<tbody>
<tr>
<td colspan="2">
E-mail address:<input type="text" name="email" value="E-mail required">
</td>
</tr>
<tr>
<td>
<div id="divTotal"></div>
</td>
<td>
<input type="submit" value="Submit";>
</td>
</tr>
</tbody>
</table>
</form>
Have you tried using hidden fields? e.g.
<input type="hidden" name="total" id="total" value="" >
You can use the same method for your unique transaction id. Then you can populate the hidden fields when you populate your "divTotal" div. e.g
document.getElementById("total").value = total;
This way when the form is submitted, the value will be passed to the script as "total" (in my example above). You can get values in php like this:
<?php
$total = $_POST["total"];
$amount = $_POST["amount"];
$email = $_POST["email"];
$transactionId = generateTransId(<<someparams>>);//YOUR FUNCTION TO CREATE TRANS ID
?>
Then to display your transaction id or output it anywhere on your php page, this is one example:
<div id="transId"><?php echo $transactionId; ?></div>

Using Javascript to add to the existing text in a textarea

I need to have an "Add Features" button that will append the following text to the already existing text in a textarea:
<b>Features:</b>
<ul>
<li>Feature 1 here</li>
<li>Feature 2 here</li>
</ul>
It needs to appear in html form, so that the user can see the tags as well as their contents. Here is the HTML I'm using:
<tr class="addItemFormDark">
<td class="descriptionLabel">
<p>Description:</p>
</td>
<td>
<textarea name="description" id="addItemDescription" cols="77" rows="6"></textarea>
</td>
</tr>
<tr class="addItemFormDark">
<td colspan="2">
<input type="button" onclick="addFeatures('addItemDescription')" value="Add Features"/>
</td>
</tr>
...and here is the JavaScript I'm using:
function addFeatures(id) {
var contents = document.getElementById(id).innerHTML;
contents += "<b>Features:</b>\r<ul>\r\t<li>Feature 1 here</li>\r\t<li>Feature 2 here</li>\r</ul>";
document.getElementById(id).innerHTML = contents;
}
Now here is that part I'm having trouble with. If the textarea is empty, as it is to begin with, the desired text will be added to the textarea fine, and this can be repeated multiple times with each block of text being successfully added after the last.
However, if the user types anything in the box, whether into the empty text area, or after the successful addition of one of the desired blocks of code, this completely disables the button. It will then no longer add anything to the textarea until the page is refreshed.
I got exactly the same result if I used JQuery's .append method and gave the textarea and button an id.
Can anyone help?
innerHTML is not the correct property to use for setting a textarea's value. Use value instead.
function addFeatures(id) {
var textarea = document.getElementById(id);
textarea.value += "<b>Features:</b>\r<ul>\r\t<li>Feature 1 here</li>\r\t<li>Feature 2 here</li>\r</ul>";
}
With jquery I would use this:
var appendData = //the HTML text you want to add
var currentData = $("#textboxID").val();
var newData = currentData+appendData;
$("#textboxIS").val(newData);

Categories

Resources