hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/
Related
I'm a beginner and I'm now stuck trying to figure out two things for the below code:
How do I code so that each of the send buttons only connects to its own input field?
How do I code so that each new text input overwrites the previous?
My code:
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="lastName">Last name</p>
<p id="firstName">First name</p>
<script>
var b1=document.getElementById("myButton1")
b1.addEventListener("click", handleClick);
var b2=document.getElementById("myButton2")
b2.addEventListener("click", handleClick);
function handleClick(){
var i=document.getElementById("inputField1");
var iValue=i.value;
var d=document.getElementById("lastName");
var oldText=d.innerText;
var newText=oldText+"\n"+iValue;
d.innerText=newText;
var k=document.getElementById("inputField2");
var kValue=k.value;
var f=document.getElementById("firstName");
var oldText=f.innerText;
var newText=oldText+"\n"+kValue;
f.innerText=newText;
}
Here is a solution that sends a 1 or a 2 to the handleClick function as a parameter depending on which button you click. It then gets the value of the input that matches the number, checks to make see if it is empty, and outputs the name to the correct paragraph if it isn't and an error message if it is. Let me know if you have any problems with it.
var b1 = document.getElementById("myButton1");
b1.addEventListener("click", () => handleClick("1"));
var b2 = document.getElementById("myButton2");
b2.addEventListener("click", () => handleClick("2"));
function handleClick(iNum){
var i = document.getElementById("inputField" + iNum);
var iValue = i.value;
var d = document.getElementById("name" + iNum);
if (iValue != "") {
var pText = (iNum == "1" ? "Last" : "First");
var newText = pText + " name: " + iValue;
d.textContent = newText;
} else {
d.textContent = "Please enter a name!";
}
}
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="name1"></p>
<p id="name2"></p>
Not really sure what's going on here, but usually you have to access the input field via the event: event.target.value (just put event as a parameter)
I am trying to change/set a value using javascript.
From what I have currently created this works for a piece of text in tags going by the id: title.
It works like this:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}
<h1 id="title">test</h1>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
Now what I want to set is a value inside here:
Voornaam + Achternaam:<input type="text" name="firstname" value="" />
Which is basically supposed to be a firstname.
I want the value to be set, using the method I was already using for my tag.
However when I give it an id like so:
Voornaam + Achternaam:<input type="text" id="firstname" value="" />
And also change my function change to that id instead of title, it doesn't change or set the value inside the firstname field.
could anybody help me out?
While I don't understand why you want one input to update another , if you want to change the value of an input field you must use .value instead of .innerHTML
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('firstname');
title.value = myNewTitle;
}
<h1 id="title">test</h1>
Voornaam + Achternaam:<input type="text" id="firstname" value="" />
<br/><br/>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
You set the value attribute on an element with the value key:
var firstnameInput = document.getElementById('firstname');
firstnameInput.value = 'Firstname value';
You need to do this:
Use firstname.value = myNewTitle; instead of innerHTML.
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var firstname = document.getElementById('firstname');
firstname.value = myNewTitle;
}
<h1 id="title">test</h1>
<input type="text" id="myTextField" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
Voornaam + Achternaam:<input type="text" id="firstname" value = ""/>
Now when I run this code, the form's function do not run. Why, Im not sure. Is it because of the doall() function I placed in my js. I did it specifically to tell the button tag thats the function to ultimately run. Is placing functions within 1 whole function considered bad? Where did I go wrong with my javascript and html pairings? I am ultimately trying to have one part of the form validate with alerts, have the total spit a given value automatically after a radio is chosen, and as you click the submit button after everything is filled, it creates that var sign.
<form name="form1" action="" onsubmit="return doall{};">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" size="12" placeholder="First Name">
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" size="12" placeholder="Last Name">
<label for="address">Address:</label>
<input type="text" name="address" id="address" size="40" placeholder="Address">
<label for="city">City:</label>
<input type="text" name="city" id="city" size="40" placeholder="City">
<label for="state">State:</label>
<input type="text" name="state" id="state" size="40" placeholder="State">
<label for="country">Country:</label>
<input type="text" name="country" id="country" size="40" placeholder="Country">
<label for="zipcode">Zip Code:</label>
<input type="text" name="zipcode" id="zipcode" placeholder="Zip Code">
<p><label for="email">Email:</label>
<input type="text" name="email" id="email" size="30" placeholder="Email Address"></p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" size="20" placeholder="Password">
<p><label for="repass">Retype Password:</label>
<input type="password" name="repass" id= "repass" size="20" placeholder="Re-type Password"></p>
<p><b>Choose the Program you would like to purhase:</b></p>
<table align ="center">
<tr>
<td><input type="radio" name="offers" value= "Basic" id="chkbox" onchange="ontotal()"></td>
<td>Basic</td>
<td>$<span>19.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Premium" id="chkbox" onchange="ontotal()" ></td>
<td>Premium</td>
<td>$<span >35.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Super" id="chkbox" onchange="ontotal()"></td>
<td>Super</td>
<td>$<span >59.99</span></td>
</tr>
</table>
<p>
Total:
<input type="text" id="prototal" size="8" value="0" >
</p>
</form>
<button type="button" onclick="doall();">Submit</button>
<p id="submit"></p>
` function formval() {
var first = document.getElementById("fname")
var second = document.getElementById("lname")
var third = document.getElementById("address")
var fourth = document.getElementById("city")
var fifth = document.getElementById("state")
var sixth = document.getElementById("country")
var seventh = document.getElementById("zipcode")
var fire = document.getElementById("email")
var sense = document.getElementById("password")
var retype = document.getElementById("repass")
if (first == ""){
alert("Please enter first name");
return false;
}
if (second == ""){
alert("Please enter last name");
return false;
}
if (third == ""){
alert("Please enter address");
return false;
}
if(fourth == ""){
alert("Please enter city");
return false;
}
if (fifth == ""){
alert("Please enter state");
return false;
}
if (sixth == ""){
alert("Please enter county");
return false;
}
if (seventh == ""){
alert("Please enter zip code");
return false;
}
if (fire == ""){
alert("Please enter email address");
return false;
}
if (sense == ""){
alert("Please enter a password");
return false;
}
if (retype == ""){
alert("Please enter your typed password");
return false;
}
var sign = "Thank you for submission. Your purchase order instructions will be emailed shortly!";
document.getElementById("sub").innerHTML = sign;
}
var programprices = new Array();
programprices["Basic"]=19.99;
programprices["Premium"]=35.99;
programprices["Super"]=59.99;
function ontotal(){
var producttotal=0;
var calform = document.forms["form1"]
var offers = calform.elements["offers"]
for(var i = 0; i < offers.length; i++)
{
if (offers[i].checked)
{
producttotal = programprices[offers[i].value];
break;
}
}
return producttotal;
}
function caltotal(){
var price = ontotal;
var presentme = document.getElementById('prototal')
presentme.innerHTML = price
}
function doall(){
formval();
ontotal();
caltotal();
}
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal); `
https://jsfiddle.net/Lnehnkaz/
First correct the above mentioned errors.
There is nothing wrong with calling some functions from another function. If you want multiple submit handlers, put the submit button within the form, change it to type="submit" and use the addEventListener method.
This works, when you give the form the attribute id="form1":
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal);
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.
When a textbox is created, default, gray text (#888) is given a displayed. When it is given focus, the value should disappear and start showing the typed value. I've written the code for this problem and it is as follows:
<html>
<script type="text/javascript">
function Focus(i) {
if (i.value == i.defaultValue) {
i.value = "";
i.style.color = "#000";
}
}
function Blur(i) {
if (i.value == "") {
i.value = i.defaultValue;
i.style.color = "#888";
}
}
</script>
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="Focus(this)" onblur="Blur(this)" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;"
value="lastname" onfocus="Focus(this)" onblur="Blur(this)" />
</body>
</html>
But, here whenever the textbox is focused, the value is disappearing. What should I do in order to correct this? Even though the text box is under focus, the value should not disappear and the value should disappear only when I start typing in it. I'm a new user so I can't post screenshots.
what you want is called placeholder.
use it like this:
<input type="text" name="enterfirstname" placeholder="First Name" />
<input type="text" name="enterlastname" placeholder="Last Name" />
Try with
<html>
<head>
<script type="text/javascript">
function Focus(i) {
if (i.value == i.defaultValue) {
i.value = "";
i.style.color = "#000";
}
}
function Blur(i) {
if (i.value == "") {
i.value = i.defaultValue;
i.style.color = "#888";
}
}
</script>
</head>
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="Focus(this)" onblur="Blur(this)" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;"
value="lastname" onfocus="Focus(this)" onblur="Blur(this)" />
</body>
</html>
Note:script tags not inside body/head elements create invalid HTML
Try using "onkeydown" as following...
function Focus(cntrl,value)
{
if (cntrl.value == value)
{
cntrl.value = '';
cntrl.style.color = '#000';
}
}
function Blur(cntrl,value)
{
if (cntrl.value == '')
{
cntrl.style.color = 'gray';
cntrl.value = value;
}
}
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;" value="First Name" onkeydown="Focus(this,'First Name')" onblur="Blur(this,'First Name')" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;" value="lastname" onkeydown="Focus(this,'lastname')" onblur="Blur(this,'lastname')" />
</body>