Why is my "add row to table" function not working? - javascript

I'm trying to create a function which adds a new row, and values to a table each time a form is submitted:
Appointment booking HTML page:
<div class="contact-form">
<form action="https://formspree.io/MYEMAIL" id="book_appt"
method="POST">
<label>Name: </label><input id="customerName" class ="form-control"
type="text" name="Name of Customer" required></input>
</br>
<label>Email Address: </label><input id="customerEmail" class="form-
control" type="email" name="Email Address" required></input>
</br>
<label>Phone no.: </label><input id="customerPhone" class ="form-
control" type="number" name="Phone No." required></input>
</br>
<label>Date & Time of Test Drive: </label><input id="customerDate"
class ="form-control" type="datetime-local" name="Date & Time of
Test Drive" required></input>
<input type="submit" value="Submit" onclick="addData()">
</form>
</div>
Appointment table html page:
<table id="tblAppts" style="width:60%; border: 1px solid black"
border="1"
align="center">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Date/Time of Appt</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Javascript:
function addData() {
var name = document.getElementById("customerName").value;
var email = document.getElementById("customerEmail").value;
var phone = document.getElementById("customerPhone").value;
var date = document.getElementById("customerDate").value;
var tableRef =
document.getElementById('tblAppts').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var nameCell = newRow.insertCell(0);
var emailCell = newRow.insertCell(1);
var phoneCell = newRow.insertCell(2);
var dateCell = newRow.insertCell(3);
nameCell.innerHTML = name;
emailCell.innerHTML = email;
phoneCell.innerHTML = phone;
dateCell.innerHTML = date;
var newText = document.createTextNode('New row');
}
When I click the Submit button on appt booking page, I am sent a default email (I have not attached this function as it's probably not relevant) but I would like it to also carry out the addData(), which it is not. Can anyone see what the problem may be?

You specified the next URL in your form's action attribute.
<form action="https://formspree.io/MYEMAIL" id="book_appt" method="POST">
input[type="submit"]'s base operation is to pass form-data to the next page (in the action attribute)
So if you don't want to change the page, prevent its default action
like below:
<input type="submit" value="Submit" onclick="addData(); return false;">

To test if your addData function is working, change the input type of 'submit' to 'button'. If everything is right then it should work fine.
The reason you are not able to see the result of addData function call is because it is attached to an onclick handler of a submit input button. It causes the form to submit and take you to new URL.
If I understand correctly what you are trying to do, there are two ways you can go about:
You can try to submit the form as an AJAX request(Send information
without changing the page url) and not the way you are currently
doing. When the request is successful you can call your addData()
function.
Or your submission can create a new row entry in your backend
database (assuming you have one) while also triggering a page
refresh. This page, when loading, should populate the entries that
are there in the backend database.

Assuming your addData() function is working, you can try to change your submit button like so:
<input type="button" value="Submit" onclick="addData()">

Related

Cannot reset readonly input text

I have an input text which i use to show results of computation:
<input type="text" id="total" readonly/>
The total gets populated inside a function on a js file as follows:
//Inside a .js file
function calculate(){
document.getElementById("total").setAttribute("value", document.getElementById("amount").value * 45);
}
and i also have a reset button which resets the form, but it doesn't reset the readonly input text:
<input type="reset" value="Reset"/>
I have tried changing the reset to button and wrote my function to disable readonly, reset then enable readonly but it doesn't work as well:
<input type="button" value="Reset" onclick="resetForm(this.form.name);"/>
//Inside .js file
function resetForm(formName){
document.getElementById("total").readonly = false;
document.forms[formName].reset();
document.getElementById("total").readonly = true;
}
Does anyone know a workaround of this case? I am new to javascript and i am doing this as a learning purpose only.
Heres the complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="allJsCodesHere.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1> <strong>CDs Purchase Order</strong></h1>
<form name="ex2Form" action = "">
<table>
<thead>
<tr>
<th>
Number of CDs ordered:
</th>
<td>
<input type="text" id="amount" value="0"/>
</td>
<td>
<input type="button" value="Calculate" onclick="calculate();"/>
</td>
</tr>
</thead>
<tbody>
<td colspan="3">
At the rate of AED 45 for each CD
</td>
</tbody>
<tfoot>
<tr>
<th>
Total Order:
</th>
<td>
<input type="text" id="total" readonly/>
</td>
<td>
<input type="button" value="Reset" onclick="resetForm(this.form.name);"/>
</td>
</tr>
</tfoot>
</table>
</form>
<footer>
<p>Created by Mir Adnan Siraj</p>
</footer>
</body>
</html>
The calculate function:
function calculate(){
document.getElementById("total").setAttribute("value", document.getElementById("amount").value * 45);
}
Document.forms returns a collection of all of the forms within a particular page. Writing document.forms["myForm"] will return the form with the name "myForm" from that collection. So what you need to do is this. Say for example your form name is myForm with an id of myForm.
<form id="myForm" name="myForm">
<input id="email" name="email" value="some#email.com" />
</form>
Now to access this form, you have to do this.
document.forms["myForm"].reset()
This will reset your form successfully. So to be clearly, you are doing everything perfectly just console.log and check the parameter passed. You dont need to reset all the fields manually by assigning them empty string. Thats wrong!
//Inside .js file
function resetForm(formName){ //==========> this needs to return the form name. console.log and check if its returning the formname
document.getElementById("total").readonly = false;
document.forms['formName'].reset();
document.getElementById("total").readonly = true;
}
Assuming that you have your inputs inside a form you'll need to prevent the default behavior of a form, which is to send a request to any URL you might pass and refresh the page, which you don't want, I suppose. To do this, if you are triggering your reset function by attaching a listener to the submit event on a form, you'll need to use the event and call the .preventDefault method - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Your function:
//Inside .js file
function resetForm(formName){
document.getElementById("total").readonly = false;
document.forms[formName].reset();
document.getElementById("total").readonly = true;
}
Try changing it to this:
//Inside .js file
function resetForm(){
const form = document.getElementById("formName");
const totalInput = document.getElementById("total");
form.reset() // Resetting form
totalInput.readOnly = false; // Making readonly false so input is editable
}
Here's a codesandbox where you can try this out
https://codesandbox.io/s/lucid-frost-4pnbz?fontsize=14&hidenavigation=1&theme=dark
Hope this helps!

Event listener seems not to be listening or getting the necessary/expected values

Event listener isn't receiving any meaningful data. Complicated to explain. I click a "function button" in my page - which fires off an ajax request and loads a form into a div on the page called 'ajaxDiv'.
When I submit that form, I want to use e.preventDefault() and for the event listener to get the form data ie, the values entered to each form field. So far I only get the specific input field ID but not the others and none of the values entered to the form.
Below is the listener so far.
console.log(); seems to show that only the id of the form is being returned. Not any IDs of the form fields and none of the data entered to the form.
document.getElementById("ajaxDiv").addEventListener("submit", function(e) {
e.preventDefault();
var record_id = e.target.id;
var target = e.target;
console.log( 'target = ' + target);
console.log( 'record_id ' + record_id );
if ( record_id ) {
if ( record_id === email_address1 ) {
var email_address1 = e.target.id;
}
}
});
The value returned to the console is "start_layaway_form"
The form html is next.
<div id='initiate-layaway-form'>
<form id='start_layaway_form'>
<input type='hidden' name='order_function' value='initiate-layaway' />
<input type='hidden' name='order_id' value="$order_id" />
<input type='hidden' name='business_id' value="$business_id" />
<table>
<tr>
<td>
<p>Enter email address</p>
<label for='email_address1'></label>
<input type='text' id='email_address1' name='email_address1' placeholder='Enter email address' />
</td>
</tr>
<tr>
<td>
<p>Re-enter email address</p>
<input type='text' id='email_address2' name='email_address2' placeholder='Re-enter email address' />
</td>
</tr>
<tr>
<td>
<p>OR</p>
</td>
</tr>
<tr>
<td>
<p>Enter Post Code</p>
<input type='text' id='post_code' name='post-code' placeholder='Enter Post Code' />
</td>
</tr>
<tr>
<td>
<p>Enter House Number</p>
<input type='text' id='house_number' name='house-number' placeholder='Enter House Number' />
</td>
</tr>
<tr>
<td>
<input type='submit' id='submit' value='Start Layaway' />
</td>
</tr>
</table>
</form>
</div>
So, with my form already generated by ajax, and pushed into the div "ajaxDiv", I want to capture the values entered to the form in the listener so I can input those values to my database, again, via ajax.
Can't yet seem to grasp the listener concept. :(
Any assistance would be greatly appreciated.
Bazz

DecodeForHTML during document.GetElementByID('input').value = 'data[0]', with dynamic array data

Good Afternoon.
So I learned today that a web application I developed, for my office to track some security report data, is suffering from the ability to add html tags into the mitigation field. These are saved to the database as a varchar, which is perfect. However, when the page reloads, and they are read again for display, it errors out because ColdFusion is reading those tags and stopping my DataTable from initializing properly.
After some playing I settled on <td>#EncodeForHTML(queryValue)#</td> for the DataTable initialization, which allows it to be visible. However the next step is getting that row data, from the DataTable, on click into the popup inputs that I am using for row modifications to be decoded. If I leave it as it is now, which is below, it will open the popup with the encoded data and is very hard to read. I've tried to use DecodeForHTML(data[#]), with and without outputs. Inside outputs I get an error that data is undefined on page load, because the array isn't created until you click on a row, and without outputs I get a syntax error.
To put it more clearly, my question is how can I decode this string when I display it in the <textarea> in my popup?
DataTable Creation Code:
<div id="allFindings" style="max-height:50%">
<table id="dt_table_findings" class="display" style="table-layout:fixed; width:100%; font:calibri; font-size:11px; text-align:left;">
<thead>
<tr>
<th style="width:4%">Task Num</th>
<th style="width:5%">App</th>
<th style="width:5%">Priority</th>
<th style="width:5%">Vuln ID</th>
<th style="width:7%">Task</th>
<th style="width:5%">Status</th>
<th style="width:5%">Category</th>
<th>Document</th>
<th>Reasoning</th>
<th>Mitigation</th>
<th>Resources</th>
<th>Comments</th>
<th style="width:5%">Milestone Date</th>
<th style="width:5%">Follow-Up Date</th>
<th style="width:6%">Planned Completion</th>
<th style="width:5%">Closed</th>
<th style="width:5%">Last User</th>
</tr>
</thead>
<tbody>
<!---Fill datatable with Findings--->
<cfloop query="#findingsQuery#">
<tr style="">
<td>#TASK_NUM#</td>
<td>#APPLICATION#</td>
<td>#PRIORITY#</td>
<td>#VULN_ID#</td>
<td>#TASK#</td>
<td>#STATUS#</td>
<td>#TASK_CATEGORY#</td>
<td>#DOCUMENT#</td>
<td>#REASONING#</td>
<td>#EncodeForHTML(MITIGATION)#</td>
<td>#RESOURCES#</td>
<td>#COMMENTS#</td>
<td>#MILESTONE_DATE#</td>
<td>#FOLLOWUP_DATE#</td>
<td>#PLANNED_COMPLETION#</td>
<td>#CLOSED#</td>
<td>#LAST_USER#</td>
</tr>
</cfloop>
</tbody>
</table>
</div>
Popup Div:
<div id="edit_findings" class="modal" style="min-width:550px;">
<cfform id="form_updateFindings">
<!---Hidden Popup Identifier for Submit Page--->
<cfinput type="hidden" name="view" id="view" value="findings">
<!--- Hidden Task Num --->
<cfinput type="hidden" name="h_taskNum" id="h_taskNum" />
<!---Shown Task Number--->
<p><label>Task Num: </label>
<cfinput type="text" name="taskNum" id="taskNum" disabled="disabled" /></p>
<!---Shown Application Name--->
<p><label>App: </label>
<cfinput type="text" name="app" id="app" /></p>
<!---Shown Priority--->
<p><label>Priority: </label>
<cfinput type="text" name="priority" id="priority" /></p>
<!---Shown Vulnerability ID--->
<p><label>Vuln ID: </label>
<cfinput type="text" name="vuln_id" id="vuln_id" /></p>
<!---Shown Task--->
<p><label>Task: </label>
<cfinput type="text" name="task" id="task" size="45" /></p>
<!---Shown Status--->
<p><label>Status: </label>
<cfinput type="text" name="status" id="status" /></p>
<!---Shown Category--->
<p><label>Category: </label>
<cfinput type="text" name="category" id="category" /></p>
<!---Shown Document Location--->
<p><label>Document: </label>
<cfinput type="text" name="document" id="document" size="45" /></p>
<!---Shown Resources--->
<p><label>Resources: </label>
<cfinput type="text" name="resources" id="resources" size="45" /></p>
<!---Shown Reasoning Box--->
<p><label>Reasoning: </label>
<textarea name="reasoning" id="reasoning" cols="35" rows="5"></textarea></p>
<!---Shown Mitigation Box--->
<p><label>Mitigation: </label>
<textarea name="mitigation" id="mitigation" cols="35" rows="5"></textarea></p>
<!---Shown Milestone Date Box--->
<p><label>Milestone Date: </label>
<textarea name="milestone" id="milestone" cols="35" rows="5"></textarea></p>
<!---Shown Comments Box--->
<p><label>Comments: </label>
<textarea name="comments" id="comments" cols="35" rows="5"></textarea></p>
<!---Shown Follow Up Date--->
<p><label>Follow-Up Date: </label>
<cfinput type="text" name="followup" id="followup" /></p>
<!---Shown Planned Completion--->
<p><label>Planned Completion: </label>
<cfinput type="text" name="plannedcomplete" id="plannedcomplete" /></p>
<!---Shown Closed--->
<p><label>Closed: </label>
<cfinput type="text" name="closed" id="closed" /></p>
<!---Shown Last User--->
<p><label>Last User: </label>
<cfinput type="text" name="lastuser" id="lastuser" disabled="disabled"/></p>
<br />
<!---Submit Button for Update Query--->
<cfinput type="button" class="btn" id="submitEditFindings" name="submitEditFindings" value="Submit" onClick="fn_updFindings();">
</cfform>
</div>
DataTable Initialization Script and Row Click action:
$(document).ready( function () {
var table = $('#dt_table_findings').DataTable( {
"bLengthChange": false,
"pageLength": 10,
"dom": 'frti<"toolbar">p',
initComplete: function(){
$("div.toolbar").html('<input type="button" name="addButton" class="add-new-button" onclick="fn_OpenModal()"><input type="submit" name="downButton" class="download-button">');
}
} );
<!--- Actions on Datatable Row Click --->
$('#dt_table_findings tbody').on('dblclick', 'tr', function () {
var data = table.row( this ).data();
<!--- Set hidden variables for popup
alert(data);--->
document.getElementById('h_taskNum').value = data[0];
document.getElementById('taskNum').value = data[0];
document.getElementById('app').value = data[1];
document.getElementById('priority').value = data[2];
document.getElementById('vuln_id').value = data[3];
document.getElementById('task').value = data[4];
document.getElementById('status').value = data[5];
document.getElementById('category').value = data[6];
document.getElementById('document').value = data[7];
document.getElementById('comments').value = data[11];
document.getElementById('reasoning').value = data[8];
document.getElementById('mitigation').value = data[9];
document.getElementById('resources').value = data[10];
document.getElementById('milestone').value = data[12];
document.getElementById('followup').value = data[13];
document.getElementById('plannedcomplete').value = data[14];
document.getElementById('closed').value = data[15];
document.getElementById('lastuser').value = data[16];
<!--- Show popup --->
$('#edit_findings').modal();
} );
} );
If I'm reading your question and code properly, you are getting html tags in the mitigation field and then experiencing problems when displaying them in the form that gets popped up. If you are encoding the output for html, then it looks bad and perhaps unreadable because what would have been an html tag will get turned into something like %lt;b%gt;something%lt;/b%gt;. I think you have a couple of alternatives here...
Strip out all html tags or
Use a control/wysiwyg editor that will be able to interpret the html.
The easiest of these two is option 1. If you run the text through something like this:
REReplaceNoCase(text, "<[^[:space:]][^>]*>", "", "ALL");
that will strip out all of the html tags and allow you to display the base information without any styling to the users. Option number 2, you would need to see if you could install and get CKEditor working as part of the popup (more difficult, but likely not impossible).
edit
Since you indicated that you would like to keep the html tags present in the string, then as you said, the best way to go would be to take out the < > values so the text will render.
REReplaceNoCase(text, "<|>", "", "ALL");
one thing to be aware of though is that this will remove all > and < values through the string. so if someone uses those values outside of the string, you'll end up missing out on those values. ie x >= 34 would end up being x = 34.

Ajax works only once

I have this form with some input fields, where upon submitting the form the data gets appended to a table, more like a list. The data gets appended to the table list and also gets sent to the data base using ajax, both action takes place when I click on submit. Below is the form.
<div id ="product_calculator" style="border: 1px solid gray; padding: 10px; display:none;margin-top: 5px;"><br>
<div class="row">
<div class="col-md-2">
<label>Product Name</label>
<input class="form-control" name="productname" type="text" id="productname" value=""><br>
</div>
<div class="col-md-2">
<label>Width</label>
<input class="form-control" name="width" step ="any" type="text" id="width" value=""><br>
</div>
<div class="col-md-2">
<label>Height</label>
<input class="form-control" name="height" step ="any" type="text" id="height" value=""><br>
</div>
<div class="row">
<div class="col-md-1">
<input type="button" class="btn btn-default" name="submit" class="submit" id="submit" class="btn btn-info" value="ADD TO LIST" />
</div>
</div>
This is table where the data gets appended,
<div>
<table class="table table-hover">
<thead>
<tbody class="details">
</tbody>
<tfoot>
</tfoot>
</table>
</div>
This is the jquery and ajax where I append the data to the list and send it to the database as well, you can also I attach a remove button to each of my appended list item
$('#submit').on("click" , function(){
var productname = $('#productname').val();
var width = $('#width').val();
var height = $('#height').val();
$.ajax({
url:"item_list_process.php",
method:"POST",
data:{productname:productname,width:width,height:height},
success:function(data){
$("#list_message").html(data)
}
})
var tr = '<tr>'+
'<td><input type="text" name="product_name[]" required class="form-control product_name" value="'+productname+'"></td>'+
'<td><input type="text" name="width[]" required class="form-control width" value="'+width+'"></td>'+
'<td><input type="text" name="height[]" required class="form-control height" value="'+height+'"></td>'+
'<td><input type="button" name="remove" class="btn btn-danger remove" value="Remove"></td>'+
'</tr>';
$('.details').append(tr);
})
Now you can see I attach a remove button to each of my list item, upon clicking on the button I remove the list item from the table as well as from the data base using ajax and jquery. The code is below, I use the data from the appended list to send it to php for it to recognize which line of item to delete
$('.details').on('click','.remove',function(){
var con = confirm("Do you want to remove it ?");
if(con){
var pro = $('.product_name').val();
var wid = $('.width').val();
var hei = $('.height').val();
$.ajax({
url:"item_list_delete.php",
method:"POST",
data:{pro:pro,wid:wid,hei:hei},
success:function(data){
$("#delete").html(data)
}
})
$(this).parent().parent().remove();
}
});
Now the problem is when I delete the data, ajax seems to be only working once when deleting the data from the data base, after that it dosent work, for example lets say I have 4 items, lets say I clicked on the 3rd item, the item gets deleted from database and also gets removed from the list, but when I click on the first item after deleting the 3rd item, the ajax dosent work anymore, nor does it work on any more of my list items when I click on thier remove button.
Check what is been passed to the id='delete' via this $("#delete").html(data).
Because any data if you are manipulating via ajax thous class will not be consider for next action.
You can check weather action triggers when you click on it by adding alert('test');
for each row you can consider different id's by appending row id's to it. When you are preforming any action on remove button you can remove particular row based on the unique ids.
like

Html Textinput in Table Data

Our teacher want us to create a website that will recieve text from the user (textfield) and send it to table data and it need to be in <form>
When i use <form> i input text in textfield the text and submit it the text that i enter is showing in table data at the same time its gone like in the text field i know that this is because of <form> when i remove the <form> the text is showing in table data.
Here is my code :
<form>
Name: <input action="f1.document.getElementById("first_name");" id="first_name" size="30" type="text" >
<button class="okok" name="myBtn" type="submit" value="Submit Data" onClick="ajax_post();">COMPUTE </button>
</form>
<table>
<tr>
<td style="color:white;" id=f1 > </td>
</tr>
</table>
in script
:
function ajax_post(){
var fn = document.getElementById("first_name").value;
var table = document.getElementById("f1");
table.innerText = fn;
}
That's because the button is 'submitting' the form, which is like refreshing to page in that it will clear the values.
You have to stop the form submitting, like this:
<form onsubmit="return false;">

Categories