Update form field based on another form field - javascript

I have 2 forms that each do specific calculations. On one of the forms (TCO), one of the input fields populates based on a input field in the other form(MORTGAGE).
The script I have below works fine --
<script>
function checkVar()
{
if( typeof myglobalvar != 'undefined' && myglobalvar != '' && myglobalvar != 0 && jQuery( '.mclass input' ).length )
{
jQuery( '.mclass input' ).val( myglobalvar );
fbuilderjQuery.fbuilder.calculator.defaultCalc( '#'+jQuery( '.mclass input' ).closest( 'form' ).attr('id') );
}
else
{
setTimeout( checkVar, 1000 );
}
}
checkVar();
</script>
In the first form, I have my equation for my calculations wrapped in another function --
(function(){
myvar = fbuilderjQuery.fbuilder.calculator.format( ROUND((fieldname17*(fieldname23/100)/fieldname12)), { 'groupingsymbol' : ',' } );
myglobalvar = myvar;
return myvar;
})()
Everything is working fine however when the value in the first form is changed or updated, the second form does not update.
Is there a way to add some kind of event/change listener for whenever the field updates?
EDIT:
using one of the suggestions in the comments below --
document.getElementById('fieldname22_7').addEventListener("oninput", function(evt) {
var Mor = document.getElementById('fieldname22_7').value;
document.getElementById('fieldname47_20').value = Mor; });
But I receive the follow error --
Uncaught TypeError: Cannot read property 'addEventListener' of null
Am I even close?

I can't fully understand your code, but I think, it could help you.
So. You have two forms like this:
<form>
<input id="input-1">
</form>
<form>
<input id="input-2">
</form>
And if the value of "input-1" changed, you want the "input-2" to be changed too.
In this case you should use the 'oninput' event.
So add an event handler to "input-1"
<input id="input-1" oninput="myEventHandler();">
And the event handler is:
<script>
function myEventHandler() {
var in = document.getElementById('input-1').value;
//Check the input
document.getElementById('input-2').value = in;
}
</script>
I hope it will help you!

Related

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].

Access return value from event Listener callback function from main program?

I have a form which contains an input field and a submit button. The whole program depends on the submission of the form to continue. Each function can only perform one task as follows:
Get input value
Output the value
allEvents();
//output(name)
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
<form id="formOne">
<input type="text" id="name" required>
<input type="submit" id = "inputText">
</form>
How do I access the value of name after the form has submitted in the main program, so that I can pass it to function output().
Note: Function inputText() can only return the input name.
You stated that you want each function to do different things. This is a good idea, but then take a look at this function:
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
Is this getting the input value only? Nope, it is preventing the default behavior of e as well. But you will want to get the input value later as well. This is not only getting the value, but setting it as well. Now, first things first, let's define a prototype for this purpose.
function InputOutput() {
var inputs = {}; //This will contain key-value pairs.
this.setInputValue = function(name, val) {
inputs[name] = val;
};
this.getInputValue(name) {
return inputs[name];
}
this.getNames() {
var result = [];
for (var key in inputs) result.push(key);
return result;
}
}
Now, lets instantiate this and use it:
//output(name)
function allEvents(){
document.getElementById('formOne').addEventListener('submit',function(e) {
e.preventDefault(); //Are you sure you do not want to execute the submit?
let tag = document.getElementById('inputText');
let name = tag.name;
let value = tag.value;
inputOutput.setInputValue(name, value);
});
}
var inputOutput = new InputOutput();
allEvents();
and later you can get the names by using getNames, like this:
function output(name) {
consolge.log(inputOutput.getInputValue(name));
}
and calling it like this:
output(inputOutput.getNames()[0]);
EDIT
Of course you can avoid the usage of global variables, by wrapping a lot of things into a function which will be the value of onload of your body tag, but that's a different question.
Because getInputValue() returns the name, you can pass it directly to output(name) .
allEvents();
function allEvents(){
document.getElementById('formOne').addEventListener('submit',output(getInputValue))
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
You would have to declare the variable name outside of the function scope.
let name
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function getInputValue(e){
e.preventDefault()
name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
output(name)
However, why not just call your output function from within your getInputValue value?
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function output(n){
console.log(n)
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
output(name)
return name;
}
Jiminy Cricket. Reading through all of this "stuff", I couldn't decide which was more messed-up. The question, or the answers !
Looking at the Question:
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
Why would anyone be adding an Event Listener to formOne ? What does the form have to do with anything ? It's useless.
And continuing with the Question,
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
Why would anyone be getting an Element by ID of inputText ? Seriously. What does that have to do with anything ? That is essentially the "Submit" button. You aren't going to find anyone's name in the interior of a button.
And then there was the Note that he added underneath his question ... Sorry, but there is no Function called inputText().
And now for the first Answer ( the one that has 2 up-votes ); Is that supposed to be JavaScript ? I typed it in, and it doesn't run. It basically has an error on every line.
And for the second answer ( with one up-vote ), I typed that one in too. It doesn't run either.
I hope the original poster is willing to make a modification to his HTML. Because I tried running his code in Internet Explorer and Chrome, and they don't treat his HTML structure the same, because his "Submit" button does not include the value attribute. So each Browser has to take a guess about what value to insert.
So if he will scrap his "pseudo-Submit" button, and replace it with a real Submit button :
<button type="submit" id="inputText">Submit</button>
And also, allow me to add an HTML paragraph tag to print the results in, because I think console.log ought to be banned.
<p id="outputIDname" ></p>
Then here is some code that actually runs. ( And I have also included the console.log statements for the people who need it. )
allEvents( ) ;
// output(name)
function allEvents( ) {
document.querySelector( "#inputText" ).addEventListener( "click", output ) ;
}
function output( e ) {
e.preventDefault() ;
let tempName = getInputValue( ) ;
console.log( "name Inside of Output Function = " + tempName ) ;
document.querySelector( "#outputIDname" ).innerHTML = tempName ;
}
function getInputValue( ) {
let name = document.getElementById( 'name' ).value ;
console.log( "name Inside of Input Function = " + name ) ;
return name ;
}
Here is the modified HTML :
<form id="formOne">
<input type="text" id="name" required>
<button type="submit" id="inputText">Submit</button>
</form>
<p id="outputIDname" ></p>
Here is the output:
// name Inside of Input Function = John
// name Inside of Output Function = John
// And the here is the output that is printed inside of the
// Paragraph Tag that I added to his HTML structure:
// John
And if you want to see just how much the Browsers hated his "Submit" button, just try replacing my "Submit" button with the one that he had. The Java Script will no longer work.
And one final note: Internet Explorer is so dumb, that ( if you replace my "Submit" button with the one that he had ), Internet Explorer doesn't even realize that the Java Script is not working. If you look in console.log, you will see that Internet Explorer just happily prints out 'John' and 'John', as if there is nothing wrong. But the Paragraph Tag ( that I added to the page ) remains empty. Just one of many reasons to ban console.log

Create button which takes to a particular URL according to data in Form Field

I've two input form fields and i want when the user clicks a submit button he should be taken to a URL based on the input in these two fields. For example if the input in the two input fields is A and B respectively the condition should be set such that the User is taken to www.mydomain.com/C in Javascript. I DON'T want the values to be appended to the URL like www.mydomain.com/a/b which I already know how to.
I have seen lot of questions on SO and Google on URL Generation but none was the case as mine. I would really appreciate help from fellow SO users. Thanks in advance.
Do you mean something like this? This would take you to the address when both inputs have the value 'something' and the button is clicked.
<input type="text" id="a">
<input type="text" id="b">
<button onclick="go()">Go</button>
<script>
function go() {
if (document.getElementById('a').value == 'something' && document.getElementById('b').value == 'something') {
window.location = 'http://www.example.com/C';
}
}
</script>
If you are using jquery:
$( "form" ).submit(function() {
// TODO read your variables
// TODO apply conditions and redirect accordingly
if ( ... ) {
window.location = 'http://www.example.com/C'
} else {
window.location = 'http://www.example.com/D'
}
return false; // prevent default submit
});

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

Multiple form fields with same 'name' attribute not posting

I'm dealing with some legacy HTML/JavaScript. Some of which I have control over, some of which is generated from a place over which I have no control.
There is a dynamically generated form with hidden fields. The form itself is generated via a Velocity template (Percussion Rhythmyx CMS) and JavaScript inserts additional hidden form fields. The end result is hidden form fields generated with the same 'name' attribute. The data is being POSTed to Java/JSP server-side code about which I know very little.
I know that form fields sharing the same 'name' attribute is valid. For some reason the POSTed data is not being recognized the back end. When I examine the POST string, the same-name-keys all contain no data.
If I manipulate the code in my dev environment such that only a single input field exists for a given name, the data IS POSTed to the back end correctly. The problem is not consistent, sometimes, it works just fine.
Is there something I can do to guarantee that the data will be POSTed? Can anyone think of a reason why it would not be?
I should really update my answer and post code here, because POST requests without
variable strings indicates the problem is on the client side.
How about this:
<script type="text/JavaScript">
function disableBlankValues()
{
var elements = document.getElementById("form1").elements;
for (var i = 0; i < elements.length; i++)
{
if (elements[i].value == "")
elements[i].disabled = true;
}
}
</script>
<form action="page.php" method="POST" onsubmit="disableBlankValues()" id="form1">
<input type="hidden" name="field1" value="This is field 1."/>
<input type="hidden" name="field1" value=""/>
</form>
EDIT
I now realize the actual problem (multiple variables with the same name should be passed to JSP as an array) and my solution is probably not what the OP is looking for, but I'm leaving it here just in case it happens to help someone else who stumbles upon this post.
you could use something like:
var form = document.getElementById('yourformid');
var elements = form.getElementsByName('repeatedName');
var count = 0;
for(var item in elements){
elements[item].name += count++;
}
this way you will get each hiddenfield with the names:
name0
name1
name2
...
I've worked out a brute-force solution. Note that I'm pretty aware this is a hack. But I'm stuck in the position of having to work around other code that I have no control over.
Basically, I've created an ONSUBMIT handler which examines the form for the repeated hidden fields and makes sure they are all populated with the correct data. This seems to guarantee that the POST string contains data regardless of how the form gets rendered and the Java back end appears to be happy with it as well.
I've tested this in the following situations:
Code generates single instances of the hidden fields (which does happen sometimes)
Code generates multiple instances of the hidden fields
Code generates no instances of the hidden fields (which should never happen, but hey...)
My 'else' condition contains a tiny bit of MooTools magic, but it's otherwise straight-forward stuff.
Maybe someone else will find this useful one day...
Thanks for the help!
<form method="post" name="loginform" id="loginform" action="/login" onsubmit="buildDeviceFP(this);">
<script type="text/javascript">
function insertFieldValues( fields, sValue )
{
if ( 'length' in fields )
{
// We got a collection of form fields
for ( var x = 0; x < fields.length; x++ ) {
fields[x].value = sValue;
}
}
else
{
// We got a single form field
fields.value = sValue;
}
}
function buildDeviceFP( oForm )
{
// Get the element collections for Device Fingerprint & Language input fields from the form.
var devicePrintElmts = oForm.elements.deviceprint;
var languageElmts = oForm.elements.language;
// 'devicePrintElmts' & 'languageElmts' *should* always exist. But just in case they don't...
if ( devicePrintElmts) {
insertFieldValues( devicePrintElmts, getFingerprint() );
} else if ( oForm.deviceprint ) {
oForm.deviceprint.value = getFingerprint();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'deviceprint', 'value':getFingerprint()} )
);
}
if ( languageElmts) {
insertFieldValues( languageElmts, getLanguage() );
} else if ( oForm.language ) {
oForm.language.value = getLanguage();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'language', 'value':getLanguage()} )
);
}
}
</script>

Categories

Resources