Html Textinput in Table Data - javascript

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;">

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!

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

Appended input field elements are not working in angularjs

I am creating form in angularjs. In that, I am creating add more fields functionality by clicking on "Add more" button. I've implemented add more functionality using javascript.
Below is the code for HTML:
<form method="POST" name="form" ng-submit="insert(user)" role="form">
<div class="top_gets" id="innerdivs">
<input ng-model="user.amount" type="text"/>
<input ng-model="user.description" type="text"/>
<input type="submit" onclick="addMore();" value="Add more"/>
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
Below is Javascript Code:
<script>
var counter = 0;
function addMore() {
counter += 1;
var div = document.getElementById('innerdivs');
var innerdiv = '<div id="innerdivs"><!-- Same Form Field Elements---></div>';
$('#innerdivs').append(innerdiv);
}
</script>
My problem is, whenever I add more fields by clicking on "Add more" button and submit the form, then only first loaded input fields posts/sends the data means newly appended field input does not posts the data. Whatever the fields are appended using javascritpt that won't works that is form does not sends/posts the inputs. This works with core PHP but it does not works in angularjs. Is there any way to fix this in angularjs?
You are doing it absolutely wrong. You shall not add dom elements manually. Instead, you shall have array in controller and push new object in it:
<form name="form" ng-submit="save(users)" role="form" ng-controller="addUserCtrl">
<div class="top_gets" ng-repeat="user in users">
<input ng-model="user.amount" type="text" />
<input ng-model="user.description" type="text"/>
<input type="button" ng-click="addMore();" value="Add more" />
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
In controller:
angular.module(<module_name>).controller('addUserCtrl', ['$scope', function (scope) {
scope.users = [{}];
scope.addMore = function () {
scope.users.push({});
};
scope.save = function () {
// send `scope.users` to server with $http or $resource
};
}]);

How to add hyphen in between strings in url

I have a form in which there is one text field and ine submit button.on click of submit button,it goes to next PHP page.The user can enter text in the text field.The text field can contain n number of text string separated by space.like a user enters text as
MY name is peter
I want text to change as MY-name-is-peter in url.
when user clicks on submit button.the url should become like submit.php?search=MY-name-is-peter
<form action="submit.php" method="get">
<input type="text" name="search" id="search">
<input type="submit" name="submit" value="submit">
</form>
PLease guide on how to add hyphen in the strings in url.
<script>
var handler = function (element) {
element.form.search.value = element.form.search.value.replace(/ /g, '-');
};
</script>
<form action="" method="get">
<input type="text" name="search" id="search" />
<input type="submit" onclick="handler(this);" name="submit" value="submit" />
</form>
str_replace will work or if you want to use regex you can try preg_replace("/[-]/", " ", $yourString)
You should encode URL before submit it:
$('form').submit(function(){
var val = $(this).find('#search').val();
$(this).attr('action','submit.php'+encodeURI(val))
})
Example : http://jsfiddle.net/e3L3a/

dataTables search messed up by input from another form

hello i have a form like this
<form id="ricerca" enctype="application/x-www-form-urlencoded" method="post" action=""><table class="inserisci_modifica">
<tr class="visualizza_dati">
<td class="nome_campo"><label for="ragsoc_denominazione">Ragione sociale o denominazione</label></td>
<td class="valore_campo">
<input type="text" name="ragsoc_denominazione" id="ragsoc_denominazione" value="" tabindex="1" /></td>
<td class="nome_campo"><label for="piva">Partita IVA</label></td>
<td class="valore_campo">
<input type="text" name="piva" id="piva" value="" tabindex="9" /></td></tr>
then i have an html table to which i apply dataTables
and then i have this code
$("#ricerca").submit(function(event) {
event.preventDefault();
oTable.fnClearTable();//Empty the entire table of current row information.
oTable.fnDraw();
});
the problem is when i type something in my form, it's as if it gets auto submited as dataTables's search field, and then i can see the same text in dataTables search field, i can't understand why
nevermind i find the bug, i am using a plugin, and in dataTableExt.oApi.fnSetFilteringDelay
i had to change
anControl = $( 'input', _that.fnSettings().aanFeatures.f );
to
anControl = $( 'table.dataTables input', _that.fnSettings().aanFeatures.f );

Categories