JavaScript/HTML | Making HTML paragraph equal to User Input - javascript

I'm beginner in HTML and I wanted to know, how I can make a paragraph in the HTML-Body equal to a text that the user has written into a textbox in the HTML-Body using a JavaScript function. Are there any ways to do that? And another question: What is happening, when the user clicks on a "Submit" button? Does HTML write all the input of the user into variables?
(EDIT) So, here's my code (HTML):
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body>
<div class="input-text">
<input type="user-answer" id="uA1">
<p id="paragraph"></p>
<input type="button" onClick="inp.input();" value="Write Text">
</div>
</body>
</html>
JavaScript:
var inp = document.getElementById('uA1');
var p = document.getElementById('paragraph');
inp.addEventListener('input', function() {
p.textContent = inp.value;
});
It still doesn't work.

When clicking 'submit' button browser serialise content of the containing that button form to url-encoded string (name1=value1&name2=value2&etc=etc) and perform the http request described in the form tag (action and method attributes). It will not create any variables or save its. All values already saved in properties of form elements (nodes of DOM tree).
To sync your input with paragraph you have to add event listener to that input that will listen if user insert any text there and then use inputs value as text content of the paragraph.
var inp = document.getElementById('myArea');
var p = document.getElementById('myP');
inp.addEventListener('input', function(){
p.textContent = inp.value;
});
See it on jsFiddle.
You can see that in this example I used the property value of the textarea DOM node (selected by it's id). That's the place where the data of the form is stored but until you click 'submit' button.

For the question about what happens when user click on "submit" button, generaly all the information included in your input are stored in php variable. I don't think you want to work with php, but this is as easy as it :
<form method = "post" action = "next.php">
<div>
<input id = "id" name = "id" placeholder = "your id here..." />
<input id = "pass" name = "pass" placeholder = "your pass here..." />
</div>
<div>
<input id = "btn_valid" value = "Valid information" />
</div>
</form>
In this example, I made a short form, with two input to let user type his id and his password. If you specified the "name" tag (like I did in the two input "id" and "pass"), you will be able to get them in your php "next.php" file like this (in another page, in this case in the page "next.php") :
<?php
$id = $_POST['id'];
$pass = $_POST['pass'];
?>
Because you specified to go to "next.php" in the form parameters, you will be able to get these data by calling "$_POST['name-of-the-input']". And it works for all kind of element which can have a "name" tag !
Last information, a php file can contains html, javascript, or php code ! But you need to execute it via a server (like Xampp).

Related

how do I create a javascript function that changes the html when a form submit button is pushed in django

I can easily update the html when it's not part of the form's submit or button. Or even when it's just a pure button element (rather than an input from a form). However, when I try to append a string to the class "chatGoesHere", nothing happens. The consolealso quickly reloads since the form is going to \send.
I'm happy to post my views.py and urls.py, however, I'm pretty sure the issue is inside of my html document below:
<p class="chatGoesHere" id="chatGoesHere"> 1st Item! </p>
<form action="\send\" method="post">
<input type="text" name="userMessage" />
<input type="submit" value="Send to smallest_steps bot" class="sendButt" id="sendButt" />
</form>
<script>
var btn = document.getElementById("sendButt");
btn.addEventListener("click", updateChat);
function createMenuItem(name) {
let li = document.createElement('p');
li.textContent = name;
return li;
}
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST2"))
function updateChat(){
const td = document.getElementById('chatGoesHere');
td.appendChild(createMenuItem("TEST3"))
}
</script>
I'd like it so that every time a user pushes the submit button of the form something gets added to the page without the page reloading.
Thank you
You need to use django with sockets.
Take a look at this walk through.
Helped me to do the same thing a few years ago!
https://channels.readthedocs.io/en/stable/tutorial/part_2.html

How to fetch some content from a url and put it on an input box in html

I have got my website at this link: www.website.zzz , Sometimes my website is loaded from different links (maybe I should say dynamic) for example www.website.zzz/?ref=name1, www.website.zzz/?ref=name2, www.website.zzz/?ref=name3, As i can say the key value on these three examples is 'ref' which takes different names, as name1, name2, name3, and more. When this link is clicked it goes direct to the signup form, on the sign up form i have got two input fields as which takes email and content from a url used. I want this box which takes content to take the name from the url, for example if someone uses this link: www.website.zzz/?ref=name4, this input 4 will get this content 'name4' such that when the user goes on to submit the form this name will be submited also. I have no any hint, that why i did not include any content. I need an example of html code which does this.
<html>
<body>
<form>
<label for="param">Parameter: </label>
<input id="param"/>
</form>
<script>
(function(){
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const ref = urlParams.get('ref')
document.getElementById('param').value = ref;
})();
</script>
</body>
</html>
Read the query string using window.location.search
Set an <input> value using HTMLInputElement.value

Dynamically changing href value on an <a> when clicking on it

This is the HTML page, I am working on:
<div class="container">
<form id="script-approval-form" action="" method="post">
<h3 class="title-submitted">Script Approval</h3>
<h5> Below you will find the script that needs to be approved before being used: </h5>
<fieldset>
<textarea id = "textarea-script-approval" class="textarea-approval"
type="textarea" tabindex="1" required autofocus></textarea>
</fieldset>
<fieldset>
<input class="email-box" placeholder="Your Email Address (if clarification is needed)"
type="email" pattern=".+#COMPANY.com"
oninvalid="this.setCustomValidity('E-mail MUST end with #COMPANY.com')"
value="{{ user_info.email }}" tabindex="2" required>
<button id = "what" class="submit-btn" type="submit"><a id = "submit-lnk" class="submit-link"
href = "#"
>
Submit for Approval</a>
</button>
</fieldset>
</form>
</div>
It's a form with a pre-filled text-area and a submit button. The text-area is automatically filled in with this JS script:
const url = window.location;
const urlObject = new URL(url);
const script = urlObject.searchParams.get('authorize')
var decodedScript = window.atob(script);
document.getElementById("textarea-script-approval").value = decodedScript;
It gets the encoded base64 URL parameter (EXAMPLE: url.com/script_approval?authorize=DScdsaCs) and puts it as normal text in the page textarea. However, if the user clicks the submit button/link, he will be sent to another page. I need to pass the script in text form to the next page as well, so for this reason I have to:
Get current textarea value
Encode it in base64
Change href link to /script-sent?script=${encoded_string}
The next page will be opened with the same URL parameter
I will then use my old JS script to decode and get the string into my other pages textareas/input places
What I tried:
<script>
document.getElementById("submit-lnk").onclick = function() {
var script=document.getElementById("textarea-script-approval").value;
var encodedScript = window.btoa(script);
document.getElementById("submit-lnk").href = `/script-sent?authorize=${encodedScript}`;
return false;
};
</script>
I know for sure that the encodedScript contains the correct value. The problem comes after that when I change the href. Even though its written syntactically correct, the page just reloads or nothing happens. I tested the templated string and it shows fine as well. Can someone please give me any guidance? Thank you!
You can remove the anchor tag from within the button.
<button id = "what" class="submit-btn" type="submit">
<!-- remove this -->
<a id = "submit-lnk" class="submit-link" href = "#">Submit for Approval</a>
</button>
Instead of replacing the href you can simply redirect to the page directly
<script>
document.getElementById("submit-lnk").onclick = function () {
var script = document.getElementById("textarea-script-approval").value;
var encodedScript = window.btoa(script);
// instead of replacing the href you can simply redirect to the page directly
window.location.href = `/script-sent?authorize=${encodedScript}`;
return false;
};
</script>
Looks like the action on the form is blank. Try entering the path to the next page there.
Or use local storage to pass data in browser cache.
You should be able to do what you need to do with jQuery
jQuery('#what').click(function(){
jQuery('#script-approval-form').attr('action','insert link here');
jQuery(this).click();
};

create hyperlink with hyperlink+inputbox

I have a user profile page which url's first part is static and last part is dynamic like this
View profile
I want to create an inputbox where i can type id in input box and given id auto complete hyperlink with input-box value like this.
Type user ID [input-box]
View profile
please tell me how can i do this.
I'd use jQuery for that, i.e:
$( "#in" ).keyup(function() {
var value = $(this).val();
$( "#out" ).text( ' View profile ' );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="in">
<p id="out"></p>
PS: How is JavaScript different from Java?
You can replace the URL with JavaScript using the location.replace function. You can tie that to a button's onclick event.
Type user ID: <input type='text' id='userid'>
<button type='button' onclick="location.replace('http://mywebsite.com/view/'+document.getElementById('userid').value);">View Profile</button>
You will likely want to add some error handling code. What if the User ID field is blank? What if they type "Mushroom" and you expect a number? What if they type ../../../index.html? If it is just for you, then you can assume you will type something valid.
Your code can be like this,
user ID: <input type="text" id="user_id" value="" onkeypup="javascript:change_url(this.value);”>
View profile
The above code calls a javascript function, change_url() on each key up.
You can write the function either in the header between [head] tags or at bottom before [/body] tag.
<script type="text/javascript">
function change_url(input_user_id) {
//-- get the value of old href
var x = document.getElementById("view_profile").href;
//-- append input-field user id
x = x + "" + input_user_id;
//-- set href value back with appened user_id
document.getElementById("view_profile").href = x;
}
</script>

Collecting form data and removing or hiding a form field using JQuery

I'm currently working on a problem that basically involves processing all data in a form, saving it, and replacing the entire form with a text link. My primary goal is to convert a form, with some data using the POST method, and a submit button, into a standard text link that can then take the saved/serialized data and POST it to the server as if it were the original form; and when JS is disabled, the standard form and submit button is presented, i.e. a graceful degradation. I'm currently using jQuery, I know it's possible to process form data by serializing it, but I'm not sure how to go about removing or hiding (whichever one is possible) a form completely so it doesn't interfere with the layout of surrounding HTML element.
In summary:
-Is it possible to remove or hide an entire form field with jQuery?
-When jQuery serializes form data, where is it saved to?
-Can that saved data be referenced by a text link (i.e. Submit") somehow and POSTed as if it were a standard form?
Thank you.
UPDATE: Ok, I implemented Franz's code in a separate JS file I call from my test.html page. The content of the JS file is as follows:
$(document).ready(function() {
//Store form data before removing
var tempStorage = $('.postLink').serialize();
// Remove form:
$('.postLink').remove();
//Assign onClick event to anchor tag
$('.submit').click(function(){
$.ajax({
//aspx page
url:"doSomethingImportant/10",
//Using POST method
type: "POST",
//The data object
data: tempStorage,
//No caching
cache: false,
//Alert on success
success: function(html) {
alert('great');
}
});
});
});
The only difference here is I'm using the class attribute as an identifier for the forms I want removed as opposed to id. Again, this is what I'm tasked with, not by choice. For some reason, however, it doesn't make it to the alert message, i.e. it doesn't work. Below is the snippet of html I'm having the script act on:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<style type="text/css">
h1.intro {color:blue;}
p.important {color:green;}
h2.outro {color:DarkGreen;}
</style>
<script type="text/javascript" src="jQuery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Form2Link.js"></script>
<title>Form Remover demo</title>
</head>
<body>
<h1 class="intro">Hello World!!</h1>
<p>How's it going??</p>
my First Link
<form id = "myForm" name="myForm" action="doSomethingImportant/10" class="postLink" method="post">
<input type="submit" id="submitThis" name="submitThis" value="clickThisLink"></input>
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
</form>
<a class="submit" href="">Submit Link</a>
my Second Link
my Third Link
<br>
<br>
<form action="doSomethingImportant/10" method="post">
<input type="submit" id="submitThis" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>
<form action="doSomethingImportant/11" method="post">
<input type="submit" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>
<h2 class="outro">That's nice, gotta go.</h2>
</body>
</html>
UPDATE 11/10/09:
Ok, I've found an alternate way of going about this problem by hiding the form and adding an anchor tag immediately after the form. I then attach a click operation to the anchor that acts on the submit button in the hidden form. My problem now is that this only works with one form defined in the DOM, I want to come up with a generalization of this function so that it works with several forms. How can I traverse each form and replace it with its own unique link?
Code for my current script:
/**
* Hide forms on page load.
* Call submit button within a form from a link
*/
$(document).ready(function() {
//Hide form:
$('.postLink').hide();
//Append a anchor tag after each form that is replaced
$('.postLink').after("<a class=\"submitLink\" href=\"#\">Submit Link</a>");
//Submit button in hidden form
$('.submitLink').click(function(){
$('#myForm').find('input#submitThis').click();
return false;
});
});
Part 1 is easy:
$('#yourform').hide();
EDIT: (to the best of my understanding - using ScottE's step-by-step idea)
Part 2:
Save the form in a local variable:
var tempStorage = $('#yourform').serialize();
Part 3:
Assign a function to the onClick event of your link that sends the data via an AJAX request:
$('#yourbutton').click( function() {
$.ajax({
// Your PHP processing script goes here
url: "yourfile.php",
// You wanted to use POST, right?
type: "POST",
// The data object (I hope, it's accessible here)
data: tempStorage,
// We don't need caching
cache: false,
// A function that gets executed on success
// Note that you have the response of the script in the html variable
success: function(html) {
alert('great');
}
});
});
If I understand what you're looking for, you could do the following:
handle the submit event of the form.
store the form data in a local variable in js - look to http://docs.jquery.com/Ajax/serialize
hide the form
show the link that will submit the form (again), and handle it's click event, initiating an ajax call where you pass in the local variable created in step 2.
This seems like an odd request...
Ok all, I went the route of hiding all my forms and appending anchor tags following each form based with class="postLink", I added a conditional statement that adds a unique ID if a form doesn't already have one, the script then adds an anchor tag with the unique ID and the value of the submit button to the end of the hidden form. A separate click function the processes the submit button in the hidden form that is tied to an anchor tag by the unique ID. Code follows:
/**
* Hide all forms with class="postLink" on page load.
* Call submit button within a form from an anchor tag
*/
$(document).ready(function() {
//Hide form(All forms with class="postLink" will be hidden):
$('.postLink').hide();
var num = 0;
//Loop over each form with a postLink class
$("form").each(function(){
//Add value of submit button as name of text link
if($(this).hasClass("postLink")){
//Get value attribute from submit button
var name = $(this).find('input#submitThis').val();
//Add a uniqueID if the form has no id
if($(this.id).length == 1){
this.id='uniqueID'+num;
num++;
}
var id = $(this).attr('id');
//Append a anchor tag after each form that is replaced
$(this).after("<a id="+id+" class=\"submitLink\" href=\"#\">"+name+"\</a>");
}
});
//Submit button in hidden form by clicking associated anchor tag
$('.submitLink').click(function(){
var anchorID = $(this).attr('id');
//Find the form id that matches the anchor id
$("form").each(function(){
if(this.id == anchorID){
$(this).find('input#submitThis').click();
}
});
return false;
});
});

Categories