Form using Javascript exclusively - javascript

I have an assigment, I don't understand it as i'm beginner.
Create a javascript script which will modify the DOM of a web-page.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?".
Thank you in advance.

I need to use only Javascript for this and I can only find answers
that use HTML
Web applications use HTML to contain, render and display elements in the viewport (browser window).
Where do you intend to render the form and capture user input?
You can build the DOM structure using JavaScript alone, however, there will still be a HTML file, which will contain the HTML elements created using javascript.
Please provide clarity as to your desired goal and what type of application this is being used for.
My gut feeling, for simplicity, is that you will require to use HTML as your template file, and JavaScript for interactivity and manipulation of the HTML file.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?". That's it.
This is a start, just to try to help you to understand the concepts.
I do, however, implore you to go and explore with confidence - you won't break anything, just give it a try!
I recommend you try taking a look at some of these articles, have a look at my (very rudimentary) code below, and feel free to ask any questions you have!
JS:-
W3 Schools JS and HTML reference
HTML:-
W3 Schools: HTML Forms
W3 Schools: Label Tag
W3 Schools: Text Area Tag (This has been left out of the solution on purpose - give it a try!!)
(function divContent() {
//Create a 'div' as a container for our form
var div = document.createElement('div');
// Perhaps you could style it later using this class??
div.className = 'row';
// I have used backticks to contain some more normal looking HTML for you to review, it's not complete though!!
div.innerHTML = `<form action="javascript:" onsubmit="alert('Your message here, or, run a function from your JavaScript file and do more stuff!!')">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="Mickey Mouse">
<br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="mickey#mouse.co.uk">
<br><br>
<input type="submit" value="Submit">
</form> `
// Get the body of the document, and append our div containing the form to display it on page
document.getElementsByTagName('body')[0].appendChild(div);
}());
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="CoderYen | Wrangling with 0s & 1s Since The Eighties">
</head>
<body>
</body>
</html>

Related

Javascript hide HTML text if input box is not filled

I have an HTML form where users are able to input their mobile number. See below:
<form class="formulario" action="signature_test.html" method="get" onsubmit="return signature_Alert()" >
Mobile (mgrs): <input type="text" name="mobile" id="mobile"><br>
<br>
<input type="submit" value="Generate Signature">
</form>
Whatever the user enters, is then populated in another HTML file. It innerHTML the text "Default":
<font color="#008080">Mobile: </font></b><font id="mobileInput">Default </font><br>
However, I would like that if the user leaves the mobile field blank, to have the "Mobile:" and the "Default" not displayed. Is that possible with Javascript?
By the way, this would be the Javascript that innerHTML the "Default" text.
<script>
var values = window.location.search.substring(1).split('&')
var mobile = values[3].split('=')[1]
document.getElementById('mobileInput').innerHTML = mobile;
</script>
Thanks.
Sure, just wrap the content in an element you can target and modify:
<span id="mobileInputContainer">
<font color="#008080">Mobile: </font></b><font id="mobileInput">Default </font><br>
</span>
Then just adjust that element's style similar to how you already adjust another element's content:
if (mobile.length < 1) {
document.getElementById('mobileInputContainer').style.display = 'none';
}
You'd of course want to double-check the actual value you're getting for mobile in your code. Make sure it doesn't have whitespace, etc. Or really tweak whatever your logic is for determining that no value is present to display. But the actual act of hiding the element is simple, just set the style to be hidden.
Additionally, I'd like to echo a comment above. <font> tags really shouldn't be used anymore. You'll find a little bit of an introduction to CSS styling can go a long way here. I recommend some introductory tutorials on the subject.
You also appear to have an errant </b> in your code. Perhaps you're not showing us the entire content. Either way, you'll want to double-check your HTML as well. Always start with valid and well-formed HTML before using any JavaScript or CSS, or behavior may not be what you expect.

Change title of web page according to form elements

I'm looking to change the title of an html page according to certain form elements, as well as some text found on that page. I found a good site describing how using Javascript can do almost what I need, located here: http://www.devx.com/tips/Tip/13469.
The problem with the script found there is that the option to change the title is restricted to the textarea, or if I try to include another element, I get an error message. I authored web page/form templates, nothing complicated, where the intended users, who, shall we say, are not very computer literate(one of them has never used computers), fill out certain textareas and drop-down options and then save the pages in an ARCHIVE folder. To make it easier for them, I would like to give them the luxury of saving the pages without having to type the relevant date and # (each form is basically one of a series of 59), essentially standardizing the titles of the saved pages which should make it easier to categorize them using another script in the future. Can the code below(the one found in the above web site) be extended to include more than one html item, such as the select drop-down options found below, and maybe something found inside elements such as a or div?
<HTML>
<HEAD><TITLE>Change Title Dynamically:</TITLE></HEAD>
<BODY>
<FORM action="" method=POST name="SampleForm">
<B>Enter Title for the window:</B>
<TEXTAREA NAME=WindowTitle ROWS=1 COLS=50></TEXTAREA>
<INPUT TYPE=BUTTON VALUE="Change Title" ONCLICK="javascript:UpdateTitle()">
</FORM>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
function UpdateTitle()
{
document.title = document.SampleForm.WindowTitle.value;
}
</SCRIPT>
</BODY>
</HTML>
<SELECT>
<option>-----</option>
<OPTION>JAN</OPTION>
<OPTION>FEB</OPTION>
<OPTION>MAR</OPTION>
<OPTION>APR</OPTION>
<OPTION>MAY</OPTION>
<OPTION>JUN</OPTION>
<OPTION>JUL</OPTION>
<OPTION>AUG</OPTION>
<OPTION>SEP</OPTION>
<OPTION>OCT</OPTION>
<OPTION>NOV</OPTION>
<OPTION>DEC</OPTION>
</SELECT>
I would recommend jQuery to get the values of the fields you want to display in the title and set it. More info on jQuery can be found at http://jquery.com/
You can use a jQuery selectors to get the values of the fields and concatenate it accordingly. Something like this:
document.title = $('textarea').val() + ' - ' + $('select').val();

Apply javascript with the script tag

I have a page where users can creates their own script to modify texts on the server (don't worry the access is restricted to a few users). So the users only have three fields they can fill, one with the name of the rule, another with the expression to replace and a last one with what to replace it with:
<label id="name">Name: </label> <input type="text" name="ruleName" size="50" id="ruleName"></input> </br>
<label id="input">Replace: </label> <input type="text" size="50" name="inputStep1" id="inputStep1"></input> </br>
<label id="output">By:</label> <input type="text" size="50" id="outputStep1"></input></br>
After that the rules are stored in a file on the server via a php post (I'll spare you the unecessary details of this command...). and then the rules are listed in a form with checkboxes, and I want that when the checkboxes are clicked the rule is applied.
The only thing I could come up with was to import the script file via a script tag but only by importing it it doesn't run the inside script.
How do I do that?
Thanks
If i understund you correct, you would have to create a script file with contentlike this
generate Script on the server:
// i would approch this totally differt, because i would not let user generate script on the server, but to answer the question ...
function executeRule(){ // name of the function is probably the Rulename and must be unique
document.getElementyId("withRules").innHTML = document.getElementyId("withRules").innHTML.replace('[userenteredvalue1]','[userenteredvalue2]');
}
//this code should just be executed when the radiobutton is selected
and than i would add the script per html - script - tag
<script src="/generated_user_script.js"></script> <!-- a line per generated script -->
and than on select(the onchange/onclick Event, when the checked attribute is set) i would call the function, quick an dirty. :)
if you have many rules you need uniqe names, so that they dont override themselfes and so on.
this said an other approche were javascript code is not create would be better.
If it is only the replace function, may be you could store the input and output values or so.

Javascript HTML Registration

I am creating a html document for class and there is an example in my notes that is very similar to what I have to do it has First Name, Last Name, and Phone Number, my question is what does this line of code mean? There is a .addphone in style but the code on the bottom only applies to phone why not first name or last name?
<!-- <div class="addphone" onclick="addPhone();">Add Phone</div> -->
<input id="adduser" type="submit" value="Add User" style="margin-top: 25px;">
</div>
The first line of code is an example of a clickable element. In this case has been commented out, meaning it will not be rendered in the browser.
For example:
<!-- Anything written here won't affect the page -->
Is it possible this line, plus the line in your stylesheet, are examples on how to write your other fields for your assignement?
Why not first name or last name?
I guess it's because your 'user' can have more than one phone, but not more than one first name or last name. This isn't really a programming question then though, is it?!
It's never good to put an onclick() event handler on a div element. It also looks like the div has been given a class for styling to make it look like a button or link. Well, if you need a button, or link, then use a button, or link. That way, keyboard support is automatically included.

Javascript form innerHTML

i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/

Categories

Resources