changing a value using javascript - javascript

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 = ""/>

Related

How do i get a send button to only submit and write to its own inputField?

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)

Change input to Upper Case with CapsLock on

I would just like to know is it possible to change the input automatically to capitalized on a certain input field where the user entered a value with Caps Lock on.
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps On = TEST NAME
Expected: Test Name
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps Off = test name
Default: Test Name
I know some Names looks like Reader Van der Bank where not all the name parts are capitalized, but still would like to know if its possible. Thanks
Alternative : Think i might be using a php function to transform everything to lowercase and then capitalized.
Here is a javascript function to do that, if there is no CSS solution for it.
var id = document.getElementById("test");
function change() {
var arr = id.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
id.value = arr.join(" ");
}
id.addEventListener("change", change);
id.addEventListener("keyup", change);
<input placeholder="Brand Name" id="test" type="text" />
For multiple elements with class test
var elements = document.getElementsByClassName("test");
function change() {
var arr = this.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
this.value = arr.join(" ");
}
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("change", change);
elements[i].addEventListener("keyup", change);
}
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
Do you want to enter all the text capitalized in the input? then u can use text-transform:uppercase in css and if u want to change it while typing you can use toUpperCase() on keyup of that input.
style="text-transform: capitalize"
(Question was edited. New Answer.)
Give your input an id, for this example let's say it's called "theInputId".
Then add an onkeypress event to it also and call the function script I've listed below.
<input placeholder="Brand Name" style="text-transform: capitalized"
type="text" id="theInputId" onkeypress="capsLock(event)">
<script>
//Script to check if Caps Lock is on.
function capLock(e){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){
document.getElementById('theInputId').style.textTransform = 'lowercase'
document.getElementById('theInputId').style.textTransform = 'capitalize'
}
}
</script>

Extract Unique Element ID using Javascript

Okay, so I have a form which adds an item to a list of items and does calculations with it, but every new item thats added is done on the users side before being submitted to the server for verification and updating of database. Now, I've looked at other answers and couldnt really get an answer. If the user adds a new item and enter a quantity and rate it should calculate the amount automatically, how would one extract the unique ID identifier to change the value of the amount? The code below and in this case the unique identifier is 19786868. The length of this identifier is always different and their is no unique pattern, the length and value is generated by a random command.
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
How would I extract this unique identifier with the OnChange command in JavaScript to calculate the amount value?
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
var id = el.id.replace(/\D+/g,"");
console.log( id ); // "19786868"
});
so basically use a this.id.replace(/\D+/g,"") where all non Digit \D gets replaced by ""
Here's an example using the input event:
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
el.addEventListener("input", function() {
var id = this.id.replace(/\D+/g,"");
alert( id );
}, false)
});
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_123_foobar" />
Take note that: asd_123_foo_9 will return 1239 as result so make sure to always have asd_123_foo as ID value
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" onchange="extractId(event);"/>
And in javascript :
function extractId(event) {
var elem = event.target;
var myArr = elem.id.split('_');
var yourUnique_id = myArr[3];
}
To be able to respond to newly added input controls, you need to capture the change event at some parent element, otherwise you will not trap the change on newly added elements.
Here is some code that handles the change event on the document. As this event bubbles up, it will eventually get there, so we can respond to it:
For extracting the number from the input's id, we can use a regular expression:
document.onchange = function(e) {
var match = e.target.id.match(/^(list_item_attributes_.*?_)(rate|quantity)$/);
if (!match) return; // not rate or quantity
// read rate and quantity for same ID number:
var rate = +document.querySelector('#' + match[1] + 'rate').value;
var quantity = +document.querySelector('#' + match[1] + 'quantity').value;
// write product as amount:
document.querySelector('#' + match[1] + 'amount').value = rate*quantity;
}
Quantity: <input class="form-control" type="text" id="list_item_attributes_19786868_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_19786868_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_19786868_amount" /><br>
<p>
Quantity: <input class="form-control" type="text" id="list_item_attributes_14981684_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_14981684_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_14981684_amount" /><br>
As you have asked to respond to the change event, I have kept it that way, but you might be interested to use the input event instead, which will trigger as soon as any character changes in an input.
The above sample does not protect the amount fields from input. You should probably do something about that, because users could just overwrite the calculated result.
document.querySelector(".my-form").addEventListener("change", function(e) {
var changed = e.target;
var matchedId = changed.id.match(/^(list_item_attributes_[^_]*)_/);
if (!matchedId) {
// this isn't one of the relevant fields
return;
}
var uniquePrefix = matchedId[1];
var quantity = document.querySelector("#" + uniquePrefix + "_quantity");
var rate = document.querySelector("#" + uniquePrefix + "_rate");
var amount = document.querySelector("#" + uniquePrefix + "_amount");
var newVal = quantity.value * rate.value;
if (isNaN(quantity.value) || isNaN(rate.value) || isNaN(newVal)) {
amount.value = "";
} else {
amount.value = newVal;
}
});
<form class="my-form">
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</form>
If the user adds a new item and enter a quantity and rate it should
calculate the amount automatically, how would one extract the unique
ID identifier to change the value of the amount?
You can use input event; for loop; attribute contains selector [attributeName*=containsString], .nextElementSibling, .previousElementSibling, to sum values of id containing "quantity" and id containing "rate" and set result at id containing "amount"
function calculate() {
this.parentElement.querySelector("[id*=amount]")
.value = +this.value
+ +(/quantity/.test(this.id)
? this.nextElementSibling
: this.previousElementSibling
).value
}
var elems = document.querySelectorAll("[id*=quantity], [id*=rate]");
for (var i = 0; i < elems.length; i++) {
calculate.call(elems[i]); elems[i].oninput = calculate;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" value="1" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" value="2" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</div>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786867_quantity" value="3" />
<input class="form-control" type="text" id="list_item_attributes_19786867_rate" value="4" />
<input class="form-control" type="text" id="list_item_attributes_19786867_amount" />
</div>

Creating a dynamic form with input buttons

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.

Combining javascript functions

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/

Categories