how to display input text that user has writen in a label - javascript

I want to display what the user has witten in an input text. I have to formslike below and on the second form I want to display on a label what the user has witten at the input part. But how can I do this...
The first form:
<form name="password" onsubmit="return Validate()" method="post" id="password" action="#" >
<label for="firstname">*First Name:</label>
<input type="text" name="firstname" id="firstname1" class="textinput" required="required" onchange="firstnamecheck1()"><br>
The second form:
<form name="displaylabel" method="post" id="password" action="#" >
<label>First Name:</label> <label id="l1">li.innerHTML('lastname1')</label><br>
</form>
How can I do this because the inner html I use above li.innerHTML('lastname1') do not give result.
I use this function:
<script>
function doStuff()
{myVar = document.getElementById('lastname1');
document.getElementById('l1').value = myvar;
}
</script>
and this is the part of the form:
<div class="hideformobile" onload="doStuff();">
<form name="displaylabel" method="post" id="password" action="#" >
<label>First Name:</label> <label id="l1"></label><br>
</form>
</div>
But it still it gives no result...What can I do? Please help me

To change the HTML content of an element you may set it's innerHTML property.
document.getElementById('my-element').innerHTML = 'test';
To get/set the value of an <input> element, use it's value property.
document.getElementById('my-input').value = 'something';

You have an onchange function called firstnamecheck1. I don't know what that does, but you can either add the following functionality to that function, or add this to the inline listener:
<input ... onchange="firstnamecheck1(); document.getElementById('l1').innerHTML = this.value;">
However, I'd prefer to set the textContent or innerHTML as appropriate using something like:
setText(document.getElementById('l1'), this.value);
Requires a small helper function to set the text:
function setText(el, text) {
if (typeof el.textContent == 'string') {
el.textContent = text;
} else if (typeof el.innerText == 'string') {
el.innerText = text;
}
}

<label>First Name:</label> <label id="l1">li.innerHTML('lastname1')</label><br>
This is not the proper way to use this javascript. You need to run it inside a function. If you put it in a block like
<script>
function doStuff()
{
document.getElementById('l1').innerHTML = 'lastname1';
}
</script>
When you call doStuff(), that code will execute and change the innerHTML property of the list item element. You can call this sort of function on page or body load as well.
<body onload="doStuff();"> (more content) </body>

Related

The value of the placeholder in HTML form input cannot be changed with JavaScript from inside of a function

Problem & Research: I have to automatically change the value of the placeholder of an HTML form input inside a JavaScript function. I did some research. The given code does not work for my case. I found a way around it, but I think there must be a better solution. Also, I wonder why the code example given in w3school doesn't work for my case.
Requirement: Only HTML and Vanilla JavaScript
The Code:
<body>
<h1>Test JS</h1>
<form id="search">
<div id="input_id">
<input type="text" id="id" name="name" required placeholder="Search...">
</div>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt (event) {
event.preventDefault()
var newVal = "123"
document.getElementById("id").placeholder = newVal //This line does not work inside the function, why?
//The following line works but I am looking for a better solution (Vanilla JS only).
document.getElementById("input_id").innerHTML = "<input type='text' id='id' name='name' required placeholder=" + newVal + ">"
}
</script>
</body>
Due to the required attribute, the browser is preventing the form from being submitted when the input is empty. But if you type something into the form to satisfy the validity, the placeholder will no longer be seen because there's text in the input.
Either remove the required attribute, or set the input value to the empty string while setting the new placeholder in order to see the new placeholder.
document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt(event) {
event.preventDefault()
document.getElementById("id").placeholder = '123';
}
<h1>Test JS</h1>
<form id="search">
<div id="input_id">
<input type="text" id="id" name="name" placeholder="Search...">
</div>
<button type="submit">Submit</button>
</form>
document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt(event) {
event.preventDefault()
document.getElementById("id").placeholder = '123';
document.getElementById("id").value = '';
}
<h1>Test JS</h1>
<form id="search">
<div id="input_id">
<input type="text" id="id" name="name" required placeholder="Search...">
</div>
<button type="submit">Submit</button>
</form>

JS form validation function is not called inside onsubmit

I am trying to run a form validation on an HTML form with pureJS.
Here is my code:
<form name="myForm" action="" onsubmit="alert('hello world');return validateForm(myForm);">
<label>
<input name="username" placeholder="Name" type="text" required>
</label>
<label>
<input name="email" placeholder="Email" type="email" required>
</label>
<input type="submit" value="Submit 1">
<button type="submit">Submit 2</button>
<button>Submit 3</button>
function validateForm(formName) {
const form = document.forms[formName];
for(let i = 0; i < form.elements.length; i++){
const element = form.elements[i];
// validation fails if element is required and blank
if(element.attributes["required"] && !element.value.length){
element.focus();
return false;
}
// validation fails if email is not valid
if(element.getAttribute('type') === "email" && !validateEmail(element.value)) {
element.focus();
return false;
}
};
return true;
}
function validateEmail(str) {
var regexp = /[a-z0-9!#$%&'*+/=?^_`{|}~.-]+#[a-z0-9-]+(\.[a-z0-9-]+)*/;
return regexp.test(str);
}
new link without typo: http://jsfiddle.net/mech8bon/
http://jsfiddle.net/4bjmh9as/
Expected: to call the alert then the function.
Result: nothing called at all.
Open the developer tools in your browser. Look at the console. Read the error message.
Uncaught TypeError: Cannot read property 'elements' of undefined
You are passing the variable myForm:
validateForm(myForm);
But then you are treating it as a string containing a property name:
const form = document.forms[formName];
String literals need quotes around them:
validateForm('myForm');
The solution thanks to Ric and Quentin in this fiddle:
http://jsfiddle.net/eg89b02j/2/
<form name="myForm" action="" onsubmit="return validateForm(this);" novalidate>
The first fix was adding novalidate attribute to the form tag.
The second fix was making the form more generic by sending the form itself instead of name.

Inserting <object> in current html form

I have a webpage with an input box and a button. If a user inputs some values (12345) an object need to appear below or instead of that form (the input box and the button).
I am handling a value check through and my whole code looks like this:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
</form>
<button onclick="proveriKljuc()" style="margin-top:20px">Potvrdi!</button>
<script>
function proveriKljuc() {
if (document.getElementById("subject").value == 12345) {
document.write(
"<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>"
);
}
}
</script>
Currently this code is showing a object in a new window (only a object on the page).
Also this is offtopic but if you can help, how can I handle if enter is pressed to activate function proveriKljuc()?
Don't use document.write. If you want to replace the current form:
<div id="wrapper">
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
</form>
</div>
<button onclick="proveriKljuc()" style="margin-top:20px">Potvrdi!</button>
<script>
function proveriKljuc()
{
if(document.getElementById("subject").value == 12345)
{
document.getElementById("wrapper").innerHTML = "<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>";
}
}
</script>
If you want your object to appear under the form:
<div id="wrapper">
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
</form>
</div>
<button onclick="proveriKljuc()" style="margin-top:20px">Potvrdi!</button>
<script>
function proveriKljuc()
{
if(document.getElementById("subject").value == 12345)
{
document.getElementById("wrapper").innerHTML += "<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>";
}
}
</script>
You can NEVER use document.write after page load. It will wipe the page. Instead have div or a span and fill the innerHTML of it or appendChild of a div created using document.createElement. return false onsubmit to stop submission or make the button type="button" - alternatively show a hidden div How to show hidden div after hitting submit button in form?
I cannot show a working example because stacksnippets do not support submit
window.onload = function() {
document.getElementById("form").onsubmit = function() {
if (this.elements["subject"].value == 12345) {
document.getElementById("objContainer").innerHTML = "<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>";
}
return false; // ignore submit
}
}
<form id="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
<button type="submit" style="margin-top:20px">Potvrdi!</button>
</form>
<div id="objContainer"></div>

HTML/Javascript form resets automatically

I'm writing javascript that takes in a form and prints it as a "verification" to 'id="printpeople"'. And it works, but after about three seconds, the form refreshes itself, and so does the p tag. The page doesn't seem to refresh itself unless I hit the 'submit' button. Why is this happening?
HTML:
<form name="form" id="form" class="form" onsubmit="createperson()" method="post">
<label for="name">Full Name:</label>
<input type="text" name="name" id="name" /><br>
...
<input type="submit" value="Submit" class="submit" />
</form><br>
<p>People:</p>
<p id="printpeople"></p>
Javascript:
function person(form){
var name = document.forms["form"]["name"].value;//retrieves name field
...
var person = [name,email,gender,address];//creates new person array
return person;
}
function createperson(form){
var personinstance = person(form);
var personstring = "Name "+personinstance[0]+
"\n"+"Email "+personinstance[1]+
...
stringholder(personinstance, "write");
}
window.peoplecriteria = ["Name: ","Email: ","Gender: ","Address: "];
window.peoplearray = []; //stores all the people in here
window.peoplestring = "";//string that's used for pretty printing.
function stringholder(parameter, readwrite){
window.peoplearray.push(parameter);
window.peoplestring += window.peoplecriteria[0]+window.peoplearray[0];
document.getElementById("printpeople").innerHTML = peoplestring;
}
By using:
<form name="form" id="form" class="form" onsubmit="createperson();return false" method="post">
You should prevent the form from submitting itself.
This works by making the submit function return false. By default the onsubmit function returns true. By returning false, you state that you do not want the submission to carry through.
You might be able to stop the form from submitting with the following as your first line in createperson(form):
form.preventDefault();

javascript function in html form

I have seen some other threads like this but they don't seem to help me in my problem. I am new to Javascript and I am struggling to understand which value in the email input has to be called in my javascript function to make it work.
<input type="email" name="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
The function I am using is this:
function check_v_mail('myEmail') {
fld_value = document.getElementById(field).value;
is_m_valid = 0;
if (fld_value.indexOf('#') >= 1) {
m_valid_dom = fld_value.substr(fld_value.indexOf('#')+1);
if (m_valid_dom.indexOf('#') == -1) {
if (m_valid_dom.indexOf('.') >= 1) {
m_valid_dom_e = m_valid_dom.substr(m_valid_dom.indexOf('.')+1);
if (m_valid_dom_e.length >= 1) {
is_m_valid = 1;
}
}
}
}
if (is_m_valid) {
update_css_class(field, 2);
m_valid_r = 1;
} else {
update_css_class(field, 1);
m_valid_r = 0;
}
return m_valid_r;
}
This function is saved as email_script.js and is called in my footer as follows:
<script src="includes/js/email_script.js"></script>
What am I doing wrong?
You need to call the check_v_mail function. Usually, this is done when the user clicks the button to submit the form.
<form name="myForm" onsubmit="return check_v_mail('myEmail')" method="post">
Email: <input type="email" name="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
<input type="submit" value="Submit">
</form>
You can add it in form's onsubmit
In addition to calling the function on form submit or field exit, you also need to add id attribute to your element because your function uses getElementById() to get the element but your input element doesn't have id attribute
<input type="email" name="myEmail" id ="myEmail" value="" class="form-control" required placeholder="Please Enter your email" maxlength="50">
To expand on a comment by Mani:
Right now the signature of your function check_v_mail is incorrect, it is written like a call to a function.
Signature in email_script.js could be:
function check_v_mail(emailFieldId) {
fld_value = document.getElementById(emailFieldId).value;
return m_valid_r;
}
Calling on the form could be:
<form onsubmit="return check_v_mail('myEmail');" method="post"></form>
A slight tweak is to have a validate function or class that handles the validation. This can be expanded to call multiple different validation methods and decreases the likelihood that the onsubmit will become complex with additional validations.
<form onsubmit="return validateForm();" method="post"></form>
function validateForm() {
var emailValid = check_v_mail('myEmail')
var firstNameValid = validateFirstName('firstNameInput');
return emailValid && firstNameValid;
}

Categories

Resources