Cannot reset readonly input text - javascript

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!

Related

Unable to submit data from php jquery page posting data to another page

I'm creating a php form using jquery. Trying to dynamically add rows and then submit to another page which inserts the data.
It is a store inventory form to supply multiple products in a single form rather than adding one product and going over the process back again. I have another form to submit same data which inserts single row of data and it works fine.I am trying to improve the same. If I comment out add row & delete row functions, submit works but for only one row. Vice versa, if I comment out submit button & function, I can dynamically add & delete rows. How to post data for multiple rows by connecting ajax to php for posting data is not clear. Also I need to post attached file which will be in pdf format for input id=Annexure.
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<form action="insert_indents.php" method="post" name="indform" id="indform">
<label for="Part_No">Part No.:</label>
<input type="text" id="Part_No" name="Part_No" placeholder="Part No">
<label for="Part_Make">Part Make:</label>
<input type="text" id="Part_Make" name="Part_Make" placeholder="Part Make">
<label for="Annexure">Attach File:
<input type="hidden" id="MAX_FILE_SIZE" value="30000" />
<input id="Annexure" name="Annexure" type="file" class="form-control" style='width:20em'/>
</label>
<input type="button" class="add-row" value="Add Row">
<input type="button" id="Submit" class="ind-row" id ="Submit" value="Submit" onclick="add_indent_details()" />
</form>
<table>
<thead>
<tr>
<th>Select</th>
<th>Part No</th>
<th>Part Make</th>
<th>Attached File</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
<script src="js/jquery-1.4.1.min.js"></script>
<script src="js/ajax.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add-row").click(function(){
var Part_No = $("#Part_No").val();
var Part_Make = $("#Part_Make").val();
var Annexure= $("#Annexure").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + Part_No +"</td><td>" + Part_Make +"</td><td>" + Annexure+ "</td></tr>";
$("table tbody").append(markup);
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
<script>
$(document).ready(function(){
$("#Submit").click(function(){
var Part_No = $("#Part_No").val();
var Part_Make = $("#Part_Make").val();
var Annexure= $("#Annexure").val();
$.ajax({
url:'insert_indents.php',
type :'post',
data :{Part_No:Part_No,Part_Make:Part_Make,Annexure:Annexure},
datatype :'text',
success:function(data)
{
alert(data);
}
});
}
}
</script>
</body>
</html>
I want to insert the data along with attached file into my database posting this data to a different page which contains insert query.
Thanks for your help.
I'm a newbie to PHP & ajax.

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

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()">

I cannot get 2 usually simple javascript functions to work with my PHP files

I am setting up a simple php form to collect entries and insert/show them to a myphpmyAdmin db, this works fine. The little problem I'm having is when i try to put in a small bit of js to clear text and also give a popup alert, neither will work, can somebody help me please.
Here is my Javascript file:
function clear(){
document.getElementById("in1", "in2", "in3", "in4", "in5",).value= "";
}
function saved() {
alert("Well done yourself, you have saved an entry to the database.");
}
And here is my php file:
<html>
<head>
<meta charset="utf-8">
<title>CS230 Assignment 3</title>
<link rel="stylesheet" href="style1.css" type="text/css" media="all" />
<script src="myjs.js" type="text/javascript"></script>
</head>
<body>
<h3>Diary:</h3>
<form action="insert.php" method="post">
<div id="table">
<table>
<tr>
<th>When/Where</th>
<th>Event</th>
<th>Emotion</th>
<th>Automatic Thoughts</th>
<th>Rational Response</th>
</tr>
<tr>
<td><input type="text" style="height:500px;" name="in1" id="in1"></td>
<td><input type="text" style="height:500px;" name="in2" id="in2"></td>
<td><input type="text" style="height:500px;" name="in3" id="in3"></td>
<td><input type="text" style="height:500px;" name="in4" id="in4"></td>
<td><input type="text" style="height:500px;" name="in5" id="in5"></td>
</tr>
</table>
</div>
<div id="buttons">
<input type="submit" name="save" id="save" value="Save Entry" onclick="saved()">
</div>
</form>
<div id="clearButton">
<button id="clear" onClick="clear();">clear</button>
</div>
<form action="show.php" method="post">
<input type="submit" name="show" id="show" value="Show Diary">
</form>
</body>
</html>
The document.getElementById() function takes one argument. If you want to fetch a list of elements, you can use .querySelectorAll():
var elements = document.querySelectorAll("#in1, #in2, #in3, #in4, #in5");
That returns a node list, so you'll have to iterate to perform an operation on each one:
function clear(){
var elements = document.querySelectorAll("#in1, #in2, #in3, #in4, #in5");
for (var i = 0; i < elements.length; ++i)
elements[i].value = "";
}
edit — you'll probably want to use a name other than "clear" as "clear" is likely to collide with something; in-line event handlers are highly susceptible to that sort of issue. Alternatively you could explicitly reference window.clear():
<button id="clear" onClick="window.clear();">clear</button>

Set form action dynamically depending on the field filled in by user

I'd like to have a few different options that all map to different actions, but I only want one submit button. I cannot for the life of me get this to work. Here is the code I have so far:
<!DOCTYPE html>
<html lang="en-US">
<head>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/main.css') }}">
<meta charset="UTF-8">
</head>
<body>
<script type=text/javascript>
function clicked() {
document.getElementById('id').action = "/query";
document.getElementById('filename').action = "/fname";
document.getElementById('dep').action = "/dependency";
return true;
}
</script>
<div id="header">
<h1>TestPy</h1>
</div>
<hr>
<div id="wrapper">
<div class="query-menu" id="nav">
<form name="query_form" id="query" onsubmit="clicked()" method=post>
<fieldset class="fieldset-auto-width">
<legend>Query</legend>
<table style="width:25%">
<tr>
<td>Plugin ID:</td>
<td><input type=text name=script_id id="id" placeholder="19506"></td>
</tr>
<tr>
<td>Filename Search:</td>
<td><input type=text name=filename id="fname" placeholder="test.file"></td>
</tr>
<tr>
<td>Dependency:</td>
<td><input type=text name=dep id="dep" placeholder="dependency"></td>
</tr>
<tr>
<th rowspan="2"><td><input type=submit value=Query class="btn"></td></th>
</tr>
</table>
</fieldset>
</form>
</div>
<div class="content" id="section">
{% block body %}{% endblock %}
</div>
</div>
</body>
</html>
What I'd like to do is have those three form fields each map back to a separate url, however I cannot get this to work. If I take the javascript out and hard code the URL, it works fine. HTML/JavaScript are not my strong language at all so I appreciate any feed back you can provide. Thanks!
I used the OnBlur method that triggers whenever a user leaves the input field.
<td><input type=text name=filename id="fname" onblur="myFunctionY()" placeholder="test.file"></td>
<td><input type=text name=dep id="dep" onblur="myFunctionY(this)" placeholder="dependency"></td>
<td><input type=text name=script_id id="id" onblur="myFunctionY(this)" placeholder="19506"></td>
In Javascript:
function myFunctionY(vari) {
console.log(vari.id);
if(vari.id=="fname")
{
var x = document.getElementById("fname");
var link='http://www.google.com?q='+x.value;
console.log("This is the URL "+link);
document.query_form.setAttribute("action",link);
}
if(vari.id=="id")
{
var x = document.getElementById("id");
var link='http://www.google.com?q='+x.value;
console.log("This is the URL "+link);
document.query_form.setAttribute("action",link);
}
if(vari.id=="dep")
{
var x = document.getElementById("dep");
var link='http://www.google.com?q='+x.value;
console.log("This is the URL "+link);
document.query_form.setAttribute("action",link);
}
}
You can have 3 functions/ as per your requirement.Upon submitting, it goes to the new action link.
Using jQuery, I'd do something like this:
$('#query').submit(function (e) {
// prevent the default action of form submission
e.preventDefault();
// create a variable using the 3 field values
$form_action = '/'+$('#id').val()+'/'+$('#fname').val()+'/'+$('#dep').val();
// set the form action attribute to the variable value
$(this).attr('action') = $form_action;
// submit the form as normal now that the action is changed
$(this).submit();
});

Forms inside td html

My html code is:
<table><tr><td onclick="submit_form_patient();")>
<form name="select_patient" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="27" />27</form>
</td></tr>
<tr><td onclick="submit_form_patient();")>
<form name="select_patient" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="49" />49</form></td></tr>
My Java script is:
<script>
function submit_form_patient()
{
document.forms["select_patient"].submit();
}
</script>
My form gets submitted but if I use $_POST to retrieve the values I get 27 all the time namely the first value I never get the other values.
Yours forms have same name. You need to name them differently.
And modify js code:
<script>
function submit_form_patient(formName)
{
document.forms[formName].submit();
}
</script>
And html code need to be like this
<table>
<tr>
<td onclick="submit_form_patient('select_patient');")>
<form name="select_patient" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="27" />27</form>
</td>
</tr>
<tr>
<td onclick="submit_form_patient('select_patient2');")>
<form name="select_patient2" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="49" />49</form>
</td>
</tr>
The name of the forms is the same. I don't know whether the standard handles this, but browsers pick the first matching item. So it's always going to be the first.
Create only one form, and based on the click POST the right value.
When you use document.forms["select_patient"].submit();, JS will find first form/element with that name.
Try this:
<script>
function submit_form_patient()
{
document.getElementsByName("select_patient")[0].submit();
document.getElementsByName("select_patient")[1].submit();
}
</script>
you can also create a for block to be more consistent.

Categories