HTML form getElementById() is NULL - javascript

Disclaimer: After some research online, I did attempt something to make sure the DOM was loaded before I queried, so please check that below, maybe I didn't get it right and that's where the problem comes from.
I know similar questions have already been asked maaaaanyyyy times but my code still doesn't work as I hoped after reading similar responses and trying to adapt my code accordingly, so please help if you can!
I am currently struggling with a form in my website. I wanted to create a form so that the admin could display a message on some of the site's pages. When I wanted to get the text that I put in the form, the returned value was NULL. I then noticed that the form I had just created was in fact nested inside another form, which doesn't work. I tried bypassing the problem by deleting the sub-form and using a formaction field but I keep having a NULL return value.
(I am using Spip for my website).
Here is the base HTML code of the admin part of the website, which contains the first form
<form method="post" action="#ENV{action}" id="form1">
<div>
#ACTION_FORMULAIRE{#ENV{action}}
[(#REM) ------------------------ Alert Message ------------------------ ]
<INCLURE{fond=formulaires/configure_alert_message}>
<script>
var msg_al = document.getElementById('alert_ortho').value;
console.log(msg_al);</script> <!-- THIS DISPLAYS THE TEXT THAT I WANT-->
<p class="buttons">
[(#ENV{choix}|=={valider_seul}|non)
<input type="submit" class="submit over" title="global_update" value="global_update" />
<input type="reset" class="submit" title="global_delete" value="global_delete" />
]
<input type="submit" class="submit" title="global_update" value="global_update" />
</p>
</div>
</form>
Then, here is configure_alert_message.html. I want the message to be sent to my page edit_article/html.
<div>
<label for="name">Alert Message :</label>
<textarea type="text" id="alert_ortho" name="alert_message">Blablabla.</textarea>
</div>
<div class="button">
<button type="submit" formaction="/edit_article.html" form="form1">Save alert message</button>
</div>
<p></p>
Lastly, here is the part of my edit_article.html file which calls for the previous code (this code is also inside a form field, I don't know if that could be a problem). I added the jQuery ready() in it in order to make sure that my query happens after DOM is loaded:
<div style="padding:10px; margin:10px; border: 3px solid #A0A0A0; text-align: center;background: #FFFF00;">
<span style="color:#FF0000;"> <strong>
<script>
$(document).ready(function() {
// do stuff when DOM is ready
var msg_al = document.getElementById('alert_ortho').value;
console.log(msg_al); <!-- THIS RETURNS "Cannot read property 'value' of null"-->
}); </script>
</strong> </span> </div>
<p class='buttons'><input type='submit' name="save" class='submit' value='save_button' /></p>
Why do I, when I try to get my message through document.getElementById('alert_ortho'), keep getting null on my page? I thought by using formaction and ready() before my query I wouldn't have this problem any more. Did I do it wrong for the DOM?
Thank you!

document.getElementById() searches the DOM of the current document for an element with a given ID.
It won't find an element in a different HTML document.
When you submit a form the data in it will be passed in the request body (for a POST form) or the query string of the URL. You need to read it from there.
Note that client-side JS has no access to the request body so this will require server-side code.

Related

Using the WYSIWYG MDBootstrap widget

I am trying to use the MDBootstrap WYSIWYG plug-in to enhance my forms, but am coming up short.
It does not seem to appear to be a class that can be applied to a textarea; doing so only displays the form element without the enhanced functions and toolbar. Instead, the docs say to create an instance as follows
<div class="wysiwyg" data-mdb-wysiwyg="wysiwyg" id="foo" name="foo">
However, when submitting a form that includes the above div, the value contained is not "posted" or "getted".
I have seen a post (https://mdbootstrap.com/snippets/standard/m-duszak/3256156#js-tab-view) that suggests what to do, using Javascript, but I don't understand it. The HTML they give (with the addition of the first textarea that I have added) is:
<form>
Title:
<textarea name="title" cols="60" rows="2"><?php echo $Story->title; ?></textarea>
<div class="first-area">
<div class="wysiwyg" data-mdb-wysiwyg="wysiwyg">
</div>
</div>
<button type="submit" class="btn btn-primary">
Submit
</button>
</form>
The JS is:
const formEl = document.querySelector('form');
const firstArea = document.querySelector('.first-area .wysiwyg-content');
formEl.addEventListener('submit', (e) => {
e.preventDefault();
alert(`Text area content: ${firstArea.innerText}, but you can also get HTML: ${firstArea.innerHTML}`)
})
What I need to do is get what is there into a $_POST or $_GET or via some method that I can then use to process for a MYSQL insert or update. Any help would be appreciated.

html onclick keeps redirecting to a function of javascript

Im calling a function from onclick of a button. When i press the button it executes my function deletes everything from the screen and displays the button inside my function. Everything works ok but why does it delete everything from screen. How to make it for it to only run the function but keep previous html elements prior to clicking the function?
<div id="form-container">
<form id="dim_form" action="">
<div class="bg">
<label class="form-label-a" for="dimm">Dimension</label>
<input id="dimm" type="text" />
</div>
<div class="bg">
<label class="form-label-b" for="dimm_upper">Upper tolerance</label>
<input id="dimm_upper" type="text" required />
</div>
<div class="bg">
<label class="form-label-c" for="dimm_lower">Lower tolerence</label>
<input id="dimm_lower" type="text" required />
</div>
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
</form>
</div>
data_table()
document.write("<input class='download' type='button' id='button-a' value='download xls' />");
I tried with "button" instead of submit. return false, basically everything i found on google and nothing works for me.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
When this method is not used for testing, it is often used to write some text to an output stream opened by the document.open() method. See "More Examples" below
see the full documentation here: https://www.w3schools.com/jsref/met_doc_write.asp
if you want to add some nodes without cleaning the whole HTML try append
https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append
document.write will erase everything you had earlier. Instead use append.
function data_table() {
const input = document.createElement('input');
input.type = "submit";
input.id = "button-a";
input.value = "download xls";
document.querySelector('.bg').appendChild(input);
}
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
Document is referred to the entire html page when you are trying to do document.write it will write on the entire page....
There can be couple of work arounds but i will suggest this one
Give class to the element you want to add element to.
Get element by the class you assign to the element in first step
var x = document.getElementsByClassName("example");
if you want to keep whats already there
x.appendChild("whatever you want to add goes here");
if you want to add only new element and discard everything previously present
x.innerHtml="whatever you want to add goes here";

How to reference an html document with a form to another html document to create a table out of that?

I need a little bit of help. I'm stuck at making the form information I have on my first html document show up on the tables in the second html document.
Any help would really feel good right now.
I'm not sure exactly what your question means, but if you are asking about including an html inside another html, check this link: include html in another html
Edit:
If you have no option to use server-side programming, you could use the query string.
In the form, add a method="GET" attribute:
<form action="display.html" method="GET">
<input type="text" name="name" />
<input type="text" name="phone" />
<input type="submit" value="Submit" />
</form>
When they submit this form, the user will be directed to an address which includes the name, phone value as a parameter. like:
http://www.example.com/display.html?name=XYZ&phone=98745654
You should then be able to parse the query string - which will contain the parameters value - from JavaScript, using the window.location.search value:
// from display.html
<p id= 'hi' ></p>
<script>
document.getElementById("hi").innerHTML = window.location.search;
</script>
this should help you to start what you are trying to do.

How do I use the <form> tag to send data to a javascript function?

I was testing and trying to make an little form that when the user entered their name, it would take that name and display it on to the screen.
<html>
<head>
<center><h1>Test-Page</h1></center>
</head>
<body>
<div class="someRandomStuff">
<h2 id="testingID">What is your first name?</h2>
<form name="input" action="login.js" method="post">
Name: <input type="text" name="userID"/>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
Here is the js file
function displaySystem(name) {
document.getElementById("testingID").innerHTML("Ah, hello there" + name)
}
I know that I could probably do this in one HTML file, however I want to try and make the js and HTML separate. ANY help is appreciated.
You don't send data to a JavaScript function, but a JavaScript function can retrieve form data.
For example, and input of type text can be retrieved using its value property:
var input = document.getElementById("userID");
var value = input.value;
I know that I could probably do this in one HTML file, however I want
to try and make the js and HTML separate.
Nice step. In fact, there's no practical difference in terms of retrieving form data or manipulating the document from an inline script or a script that's included using a <script src=... element. The main difference is a script embedded in the HTML document won't be cached, while a one included as a separate file will be cached (obviously, there're other reasons if we talk about good separation of concerns!).
use onkeypress event on textbox and pass this to display that value and use that parameter in function to display it
<div class="someRandomStuff">
<h2 id="testingID">What is your first name?</h2>
<form name="input" action="login.js" method="post">
Name: <input type="text" name="userID" onkeypress="displaySystem(this)"/>
<input type="submit" value="Submit"/>
</form>
</div>
//javascript function
function displaySystem(name) {
document.getElementById("testingID").innerHTML("Ah, hello there" + name.value)
}

How to store value entered in an input textfield in a database

I am using springsourcetoolsuite, grails project and I am coming across this problem of storing the value entered in the textfield into a table in the database created in mysql and connected to grails. Now I have a domain class called property having variables address, city,
zipcode, country etc. which are also fields of the table property in mysql database.
When I ask user to fill in using this piece of code-(gsp views)
<body>
<g:textField name="address" maxlength="40" value="${propertyInstance?.address}" />
</body>
it works and the value is stored in database.
However I am required to append an input field on each button click, so i have put this input field in a function called add(). Here is the code-
<head>
<script type="text/javascript">
function add() {
var newP = document.createElement("p");
var input1,
area = document.getElementsByTagName("form")[0];
input1 = document.createElement("input");
input1.type = "g:textField";
input1.placeholder = "street";
input1.value = "${propertyInstance?.address}";
newP.appendChild(input1);
area.appendChild(newP);
}
</script>
</head>
<body>
<g:form name='prop' method="post" action="save">
<input type="button" value="+Add" onclick= "add();" ><br>
<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</g:form>
</body>
Now when i do this and run it, it takes null value and prints an error saying 'address cannot be null'. Now i cannot see what is wrong, but if anyone is familiar with groovy/javscript.. please help me figure out whats wrong.
Thanks a lot.
I'm guessing you did not use the scaffolding feature to generate your views in first place. If you didn't, it's a good way to start understanding the basics of grails. In your case specifically, you need to put your fields that you want to pass to the controller (like address) inside the form tag. Like:
<body>
<g:form name='prop' method="post" action="save">
<g:textField name="address" maxlength="40" value="${propertyInstance?.address}" />
<input type="button" value="+Add" onclick= "add();" ><br>
<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</g:form>
</body>
Another thing is you can't create a tag input and put its type as "g:textfield". The html input fields only have limited types. The one you want to use in this case is really "text". In any case, the grails' tags are rendered before the javascript (in the server-side) while javascript code is rendered client-side. So the first time the page is rendered they will work. But to insert something dynamically in your page, you need ajax because the grails' tags are already rendered. The value ${propertyInstance?.address} needs to be processed at the server, returned and established in your field. Therefore you need to make an async request. Anyway JQuery is your guy.
Also, for what you're doing, JQuery helps to manipulate HTML DOM, that will make your work so much easier.

Categories