I want to create a form which has a text entry box where a user can enter their name and then I want a button as well. But what I want this button to have a function called ReadName() where what will happen is when the user clicks on the button it will come up with a message saying "Hello user name will appear here
I have tried my self and but I don't think I am not getting what I want. Any help will be appreciated.
<form>
<label for="name">Name:</label>
<input type="text" name="name" id="name"/>
<input type="text" name="name" onfocus="ReadName()"/>
</form>
function ReadName() {
var name = document.getElementById('name').value;
alert('Hello '+ name);
}
Related
I have a function that's called with a submit button and another that is based on key entry enter. When I run my code I keep getting an error saying myFunction() is not defined why is this?
js code: The validate function is suppose to add in user input elements based on how many volunteers need and invitation for the website. the myFunction() code is supposed to save fields of the form to variable (more code variables are in here but you guys don't need to see that)
html: it is a basic form the user is supposed to enter how many guests and the JavaScript is supposed to create a field for each recipient name. I am then supposed to save the names to and array which I will be working on later but I can get past the myFunction is not defined error.
var wage = document.getElementById("howMany");
window.onload = wage.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
var num = document.getElementById("howMany").value;
for (i = 1; i < num; i++) {
//loop set to repeat to the amount of guests inputed by user
container.appendChild(document.createTextNode("Recipient " + (i + 1) + ":"));
//creates a text for the user to read which recipient each input is for
var x = document.createElement("input");
//creates the input element
x.setAttribute("id", "empInput" + i);
x.setAttribute("type", "text");
//sets the type and attribute
container.appendChild(x);
//places the input element in the container
//values.push(x);
}
}
window.onload = function myFunction() {
//loads the function on page load to change variables for user
var urlParams = new URLSearchParams(location.search);
//sets var for the URL information the users inputed information on submit
//var num = urlParams.get("howMany");
//sets the var for the amount of guests attending
var container = document.getElementById("container");
//sets a variable to reference the container in the form to place the input elements
var values = new Array();
}
<section id="pageForm">
<form name=myForm action="#">
<div>
<label for="howMany">How Many Guests:
<br />(max. 10) <br />
</label>
<input type="number" id="howMany" value="" placeholder="0" />
</div>
<div>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" placeholder="Enter your Recipient Name" />
</div>
<div id="container">
</div>
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" placeholder="Enter your Organization Name" />
<label for="eventDate">Event Date:
</label>
<input type="text" name="eventDate" placeholder="Enter your Event Date" />
<label for="websiteURL">URL:
</label>
<input type="text" name="websiteURL" placeholder="Enter your Website URL" />
<label for="hostName">Host name:
</label>
<input type="text" name="hostName" placeholder="Host Name" />
<input type="submit" value="Submit" onclick="myFunction()">
</form>
</section>
That's definitely not intuitive, but the name "myFunction" as you had it is basically ignored. Try this instead.
function myFunction() {
//loads the function on page load to change variables for user
//etc. as before
}
window.onload = myFunction;
I am creating a contact form that creates something like a cart view depending on the inputs.
I managed to get all the checkboxes to output when they are checked; I am having trouble getting the same to work with text and number inputs. So input type text, number and textarea.
<input id="form_name" type="text" name="name" class="form-control"
placeholder="Please enter your firstname *" required="required"
data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99"
class="form-control" required="required"
data-error="Pflichtfeld" data-validate="true">
<div id="descript11" style="display:none;">Vorname:
<b id="vorname"></b>
</div>
<div id="descript12" style="display:none;">Alter:
<b id="alter"></b>
</div>
So I tried the method with $(document).change() but that did not work. I want to grab the contents of the input or textarea and output it to the div with the corresponding id. So "age" should output to "alter" and so on. I'm not sure how to achieve this and w3schools or other sites don't offer an answer.
You can do this by adding an input event listener to your input text boxes. In the example below, I loop through all your input text boxes (as I gave them a class of text-input) using a forEach loop. You can then grab the text from the textbox using this.value and place it into its associated div. To help with this I created a mapping object which is used to map the id of the input to the id of where the text should be placed into.
See example below:
const input_map = {
form_name: "vorname",
age: "alter"
}
document.querySelectorAll(".text-input").forEach(elem => {
elem.addEventListener('input', function() {
const textbox_value = this.value; // get text from input bpx
const target = input_map[this.id]; // get location (ie: the id) of where the text should be placed
document.getElementById(target).innerText = textbox_value; // place the text in that location
});
});
<input id="form_name" type="text" name="name" class="form-control text-input" placeholder="Please enter your firstname *" required="required" data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99" class="form-control text-input" required="required" data-error="Pflichtfeld" data-validate="true">
<div id="descript11">Vorname:<b id="vorname"></b></div>
<div id="descript12">Alter: <b id="alter"></b></div>
Note: In the example above I removed the style="display: none;" from your divs so that you can see the output
You can do it like this:
$('input').on('input',function(){
let text = $(this).val();
let id = $(this).attr('id');
$('div.'+id).text(text)
});
This snippet checks changes on inputs and sets their value to the div with class that matches each input's id .
I'm making a website for a project and I've added a subscribe to our newsletter section and I've set up a pop when you click the subscribe button. Before I added that js, the form wouldn't proceed until both fields were filled out and it showed a popup telling you to fill it.
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily
Newsletter
</label>
<input type="submit" value="Subscribe" onclick="myFunction1()">
Now with the js, it shows the pop up I made thanking the person for subscribing when I click the subscribe button regardless if the fields are filled or not.
function myFunction1() {
alert("Thanks for subscribing!")
}
You should include all the inputs in a form tag, as so:
<form id='myForm'>
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily
Newsletter
</label>
<input type="submit" value="Subscribe" onclick="myFunction1()">
</form>
This approach is better because then all the inputs are together in one entity, without it the 'submit' input won't really work. It won't know what is being submitted. Within the form tag it knows it's submitting the form together with all inputs contained within.
The form tag has its own set of events that you can add listeners to.
Including a 'submit' event.
To add the event listener to run your function whenever a submit happens on the form, you can do as so:
document.getElementById('myForm').addEventListener('submit', myFunction1)
Alternatively, you can also set the listener on the html:
<form onsubmit='myFunction1()'>
But keep in mind that with the 'addEventListener' method you can add multiple listeners to the same event. While the onsubmit property only accepts one function.
More info on events and on the addEventListener method:
https://developer.mozilla.org/en-US/docs/Web/Events
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
inside the function check for the field values. Confirm whether the fields are empty. If not then show the alert
function myFunction1() {
var f1 = ; // get value of field1;
var f2 = ; // get value of field2;
if (f1 != '' && f2 != ''){
alert("Thanks for subscribing!");
}
}
give all inputs of class, eg: 'myInput', and loop over them to check their value before alerting.
function myFunction1() {
var inputs = Array.fom(document.getElementsByClassName('myInput'));
var allChecked = false;
inputs.map(function(input){
if (input.value == '') { allChecked = false }
});
if (allChecked) { alert("Thanks for subscribing!") }
};
I have a form with a simple text field for a person's full name.
After a user enters their name and moves/tabs to the next field, I want to be able to capture the full name, extract only the first name, and attach to a separate hidden form field.
If the user goes back and corrects their full name, the extraction should repeat to get the correct first name. The full name text field would still be passed along during form submittal.
I'm thinking plain JS would be the best approach (I'm not using JQuery).
<form>
<input type="text" name="fullname" value="">
<input type="hidden" name="firstname" value="">
</form>
you can try this
this is your html
<form>
<input type="text" name="fullname" value="" id="fullname">
<input type="hidden" name="firstname" value="" id="firstname">
</form>
this is your javascript
<script>
let fullName = document.getElementById("fullname");
let firstName = document.getElementById("firstname");
fullName.addEventListener("blur", function() {
let names = fullName.value.split(" ");
if (names.length > 0) {
firstName.value = names[0];
}
});
</script>
https://jsfiddle.net/3k8kur9u/
I'm trying to copy the First Name and Last Name field into another 'Username' field dynamically. The Username field should also be lowercase and have a hyphen in the middle. So for example,
if First Name = John
and Last Name = Smith
then Username (dynamically-created) = john-smith
Any ideas?
You can do this with plain JavaScript. I'm assuming there is a button of some sort to add the fields together. Also assuming that your Input is <input> text boxes.
document.getElementById("button").addEventListener("click", function() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var userName = document.getElementById("userName");
userName.value = firstName.toLowerCase() + "-" + lastName.toLowerCase();
});
<input id="firstName" type="text" placeholder="First Name" />
<input id="lastName" type="text" placeholder="Last Name" />
<input id="userName" type="text" placeholder="Username" disabled />
<button id="button">Create Username</button>
To make it dynamically update, use onkeydown or onkeyup. Follow kemotoe's answer.
Another option is using onkeyupevent to make it dynamic. This also takes care of any uppercase letters.
function generateFullName() {
document.getElementById("username").innerText =
document.getElementById("fName").value.toLowerCase() +
"-" +
document.getElementById("lName").value.toLowerCase();
}
First Name <input type="text" id="fName" onkeyup="generateFullName()" />
Last Name <input type="text" id="lName" onkeyup="generateFullName()" /> <br/>
Username: <span id="username" />
You can do it with jquery, too. This is a working example.
Working Fiddle
HTML
<input id = "first"> <br> <br>
<input id = "last"> <br> <br>
<input id = "username">
<button id ="generate">Generate</button>
JS
$("#generate").on("click", () => {
let first = $("#first").val()
let last = $("#last").val()
$("#username").val(first+ "-"+last)
})
$('#firstName').change(updateUsername());
$('#lastName').change(updateUsername());
function updateUsername(){
$('#userName').val($('#firstName').val().toLowerCase() +"-"+$('#lastName').val().toLowerCase() );
}
Bind with change event to update the user name field
You can use the onkeypress event.
It would look like this
document.querySelector('.form').addEventListener(("keypress"), () => {
//Code to edit the username field goes here
//Try pressing a key inside the form
alert('Hi');
});
<form class='form'>
<input type="text">
<input type="text" >
<input type="text" class='username'>
</form>