I am new to Javascript. I am hacking one application wherein I
need to get the values from the form and do processing on it :
icode=document.forms[0].intcode;
lamt=document.forms[0].lnamt.value;
nom =document.forms[0].nomon.value;
and update the values in the other fields in the form depending on the
above three values like this :
document.forms[0].monpmt.value=Math.round(mamt);
document.forms[0].totamt.value=totamt;
Note: these values must automatically appear in the form depending on the above three
values entered by the user.
function setTotamt() {
icode=document.forms[0].intcode;
lamt=document.forms[0].lnamt.value;
nom =document.forms[0].nomon.value;
intrate=icode.options[icode.selectedIndex].myvalue;
if(lamt >0 && nom>0 && intrate>0) {
document.forms[0].monpmt.value=Math.round(mamt);
document.forms[0].totamt.value=totamt;
}
}
I am doing this on Linux platform and tomcat.
> icode=document.forms[0].intcode;
> lamt=document.forms[0].lnamt.value;
> nom =document.forms[0].nomon.value;
Variables should be declared with var to keep them local (presuming the above is intended to be in a function). The syntax is more or less correct, it suggests an HTML structure like:
<form ...>
<input name="intcode" ... >
<input name="lnamt" ... >
<input name="nomon" ... >
...
<input name="monpmt" ...>
<input name="totamt" ...>
</form>
So if you have a button in the form that runs a function to get some values and update the value of some other control, it might look like:
<input type="button" onclick="updateForm(this);" ...>
and the update function might look like:
function updateForm(el) {
var form = el.form; // store a reference to the form
var icode = document.forms[0].intcode; // reference to element named "intcode"
// Get the value of some controls
var lamt = document.forms[0].lnamt.value;
var nom = document.forms[0].nomon.value;
// Do something with the values
var mamt = ...;
...
var totamt = ...;
// Set some values in the form
// Have a reference to the form so use it
form.monpmt.value = Math.round(mamt);
form.totamt.value = totamt;
}
Note that form control values are always strings and that you should test the values you get to make sure they are what you expect. If you want to update values without the user pressing a button[1] you can use the blur event to call updateForm.
You will need validation of input values and to deal with errors (updates before the user has filled in all the fields and invalid data being the obvious ones). Also you'll likely want to format the data when putting it back, such as formatting numbers to two decimal places perhaps.
A button is best as it can be a submit button so that if javascript is disabled or not working, the form is submitted and updated at the server and an updated form returned. If scripting is available, you can cancel the submit and do the processing on the client. You could have the update on the blur event and button if you want.
Related
Good evening,
Today I've encountered a question/problem. I'll get right into it. So basically I have form which is used to create meal. Meal table (migration) looks like this:
$table->uuid('id')->primary();
$table->uuid('restaurant_id')->nullable();
$table->string('name_lt', 100);
$table->string('name_en', 100);
$table->string('name_ru', 100);
$table->smallInteger('prep_time');
$table->string('image', 150);
$table->boolean('visibility')->default(0);
$table->boolean('deleted')->default(0);
$table->timestamps();
$table->foreign('restaurant_id')->references('id')->on('restaurants')->onDelete('cascade');
Aside the there's tons of other stuff, like ingredients and stuff, which are related to that specific meal. In the form page I have 3 different forms for different languages that is my native lithuanian, english and russian. There is tab buttons for changing form to other language, all it does is just hide current form and show another (there is 3 identical forms in 1 page).
What I'm trying to achieve is if I fill in lithuanian language's inputs, I want english and russian inputs to be filled also (that can be achieved with jquery or javascript change function), but it should fill in translated text.
Simple example:
In first form I fill in text name_lt = 'Obuolys', so name_en and name_ru should get filled too, but in different language, in this case name_en = 'Apple', name_ru = 'яблоко'
I never used translation api's so I'm wondering what would be the best way, I'm thinking of using DeepL as it is quite cheap.
If someone could give me some advices or simple example would be nice, I could follow on from that.
If you want to use javascript, you could use a button's click event to fill out the other fields before submiting the form. If I understand it correctly you have 3 forms (1 per tab).
You could do something like this for each form.
<form id="form-lt" method="post">
#csrf
<input name="name_lt">
<input type="hidden" name="name_en">
<input type="hidden" name="name_ru">
{{-- Not a true submit button --}}
<button id="button-lt type="button">Submit</button>
</form>
Given a function that takes text input, the original language and the language you want to translate
async function translate(text, from_language, to_language) {
const response = await fetch(...);
const data = await response.json();
// get translated text from data
return translated_text;
}
The js part could look like this
const button_lt = document.getElementById('button-lt');
button_lt.addEventListener('click', async event => {
const form = event.target.form;
const lt_value = form.querySelector('[name=name_lt]').value;
const en_input = form.querySelector('[name=name_en]');
const ru_input = form.querySelector('[name=name_ru]');
en_input.value = await translate(lt_value, 'lt', 'en');
ru_input.value = await translate(lt_value, 'lt', 'ru');
form.submit();
});
Alternatively, if you want to do it server-side, you could try to call whatever translation API you end up using using the Http facade provided by laravel before validating the input data or before saving the model to the database.
Are you using PHP or javascript?
DeepL offers a NodeJS library (for the backend) and a PHP library to easily allow you to translate. For example, to translate in PHP, you can use the following snippet after installing the library:
$authKey = "f63c02c5-f056-..."; // Replace with your key
$translator = new \DeepL\Translator($authKey);
$result = $translator->translateText('Hello, world!', null, 'fr');
echo $result->text; // Bonjour, le monde!
To perform this when your users fill in some text, you will need to write the appropriate Laravel code. Please note that it is not safe to do this in the frontend, as it requires you to expose your $authKey.
I have a page called Personal Info page with assigned ng-models.
e.g.
<input type = "text" name = "foo_name" ng-model = "foo.name" />
<input type = "text" name = "foo_address" ng-model = "foo.address" />
<input type = "text" name = "foo_age" ng-model = "foo.age" />
Then, there's a Continue button that redirects to a new page called Other Details.
The Continue button is validating all required fields if filled in. It's also returning a log if all fields are validated - either:
SUCCESS
{result:
{ error: null }
}
FAIL
{result:
{ error:
{
blah blah blah
}
}
}
In the Other Details page, it's just a GRID of the details entered on the previous page. And then, there's an "Edit" button in this page if they wanted to edit something on their personal info.
I'm using ng-model to retrieve the data being stored in the saveDetailsInfo service.
$scope.retrieveData = function(dataFromService) {
$scope.foo = {
name: dataFromService.entry.name,
address: dataFromService.entry.address,
}
}
Then, it's showing nicely and properly on its respective fields. The problem is if I'm trying to hit the "Continue" button again to save my changes. It's returning an error that these fields are already undefined, although the values have been printed and populated on the input fields.
Why has it become null?
I can't recreate the problem...but a quick fix is to check if the value is null on the continue function and if it's null then read the value from the ng-model again(as it's shown in the dom tree) and then using those data to initialize and continue what you need to do with the data.
Many times this happen because the function is initialized before the dom gets it data and hence null...
Directly below, the user clicks the link, which calls a PHP script and returns a JSON object, through which I parse and create INPUT fields each with their own ID, which was part of the JSON object:
$(function()
{
$('.addNewLink').click(function(e)
{
e.preventDefault();
$('#addNewForm input, #addNewForm select').val('');
$.post('api/size_types.php', function(data)
{
var obj = JSON.parse(data);
$('.size_types').empty();
var htmlToInsert = obj.map(function (item)
{
return '<div class="input-group">
<span class="input-group-addon" >'+item.SIZE_TYPE+'</span>
<input type="text" class="form-control size_types"
id="'+item.SIZE_TYPE+'" value="'+item.DEFAULT_TEU+'" />
</div>';
});
$('.size_types').html(htmlToInsert);
});
$('#addNewModal').modal('show');
});
});
In the code above, I was able to loop through the JSON and create INPUT fields all with their own ID's using item.SIZE_TYPE and have the values set to item.DEFAULT_TEU.
On the HTML side, there is a form, but hopefully I don't have to show that code. Just know there is a submit button with an ID called #addNewSubmit, which I will display the JavaScript directly below:
$('#addNewSubmit').click(function()
{
var addservice = $('#addservice').val(); // user entered field
// here is where I'm stuck
});
What I need to do is create variables using the INPUT fields automatically created by the JSON object. In my current case, 58 INPUT fields have been generated, all with their own ID and DEFAULT_VALUE. The user has the option to change the DEFAULT_VALUE.
After searching the web, I found this code and added it to the click event directly above, right beneath the first variable:
var size_types=new Array();
var j=0;
$(".size_types").each(function(){ // looking at the class, I need the ID
size_types[j]=$(this).val();
j++;
});
Using this, I can return the values of each of the INPUT fields in an ALERT box, but I need the IDs so I can send them all to a PHP script to INSERT into a database.
How can I get each ID and its VALUE and set them all to their own variables? Or, is there another way to do this?
I have three tables in my database: Person (id, name, last_name), System (id, name), PersonInSystem(id, person_id, system_id). The last one is used to link a person with a system.
I use <select> to display every person from my DB like this
echo '<option value="'.$queryResult["id"].'">'.$queryResult["name"].' '.$queryResult["last_name].'</option>';
I use Ajax to get the id and to send a query SELECT * FROM Person WHERE id = ID_FROM_SELECT. Then, I display the data like this (I can't copy the code, so I have to rewrite it from head, I will use pseudo PHP + HTML), and the main purpose of it is to edit a chosen person:
<form>
Name: <input type="text" value="'.$nameFromDB.'" name="name">
Last name: <input type="text" value="'.$lastNameFromDB.'" name="lastname">
System: while () { // if one person is assigned to many systems, I will display them all in separate selects
<select><option value="'.$systemAssignedToPerson.'">'.$systemAssignedToPerson.'</option>
while () {
// display every system except for the one listed above
}
</select><img src="drop.gif" onclick="deleteSystem(document.getElementById(\"system\").value)"><input type="hidden" id="system" value="'.$systemAssignedToPerson.'">
}
<input type-"submit" value="Edit" name="editPerson">
</form>
Now if I want to unassign a person from given system, I would like to click the drop.gif image and trigger deleteSystem(value) function, which will send query DELETE FROM PersonInSystem WHERE system_id = SYSTEM_ID_SENT and person_id = PERSON_ID_SENT, but I can't pass the value and I don't have really idea how to do it (I'm new with Ajax).
I can store person's id in a session variable, but I don't know how to send system id, and also I don't want to sent the data to another page.
Also I would like to refresh the page with changed system assignment (the same person should be displayed).
I think you need native javascript function call to the server
function deleteSystem(value){
var deleteflag=confirm("Are you sure to delete?!!");
if(deleteflag){
//setup your request to the server
window.location='delete.php?SYSTEM_ID_SENT='+value
}
}
In your delete.php file you can get the SYSTEM_ID_SENT in this way
$id=$_GET['SYSTEM_ID_SENT'];
$personid=$_SESSION['your session variable name'];
// run your delete query
$delqry=mysql_query("");
if($delqry){
//redirect to the page you want
header('location:yourpage.php');
}
Change the code as below.
It should work
<img src="drop.gif" onclick="deleteSystem('<?php echo $systemAssignedToPerson;?>')">
Your deleteSystem JavaScript function needs to send the following kind of request to the server:
(Example: Handler file for unassign)
"unassign.php?systemId=459&personId=300"
(Example: Generic handler file)
"handler.php?systemId=459&personId=300&action=unassign"
In unassign.php:
$systemId = $_GET["systemID"];
$personId = $_GET["personID"];
/* Your SQL stuff here -
statement something like
DELETE FROM PersonInSystem WHERE person_id = "$personId" AND system_id = "$systemId" */
Improvements:
* Use a javascript library like Prototype (oldschool, lightweight) or jQuery (more heavy) for handling the Ajax stuff
* Use $_POST and post variables instead of $_GET
* Use a library for properly quoting your SQL
* Care about html special characters and proper input validation/filtering
I'm building a bit of a test-case JS application, something very basic, but have run into some problems.
I'm trying to use a HTML form for a user to enter a number, which is then written to a Javascript Array. The user then has the option to write that same array to a local (client side) cookie. (I understand the security implications of this - it's a test-case and not for commercial use.)
However, I can't make the connection - how can I capture the HTML entry, press 'submit' which will send it to a JS array, where the user can then press a different 'submit' which will write the array to a text file?
If anyone can help I'd appreciate it because it's been nearly 6 hours and it's not funny anymore.
To read the data, use code such as this:
var data = new Array;
function readData() {
var inputs = document.getElementsByTagName('input');
for (i in inputs) {
if (!isNaN(i - 0) && inputs[i].type == 'text') {
data[i - 0] = inputs[i].value;
}
}
}
Trigger it with a button input:
<input type="button" onclick="readData();" value="Read" />
Still, do you want it as a cookie, a text file or what? Here are a few possible statements to use depending on which you want:
alert(data.toString());
window.location.href = 'data:text/plain,' + escape(data.toString());
document.cookie = 'data=' + data.toString();
The second one generates plain text that will likely be displayed in the browser. To save it as a text file, you'll have to either
do it manually after generating it
use some MIME type such as application/octet-stream instead of text/plain (then the user will have to name the file manually).
on the form add
<form bla bla bla onsubmit="return catchThings()">
<input name="test" id="test">
</form>
the with the javascript you can do
function catchThings(){
// get all the forms inputs by id
// do things with arrays or whatever
var example = document.getElementById("test").value;
return false;
}