I am trying to add some text to an input element using a button. I have so far tried modifying .textContent - which does actually appear to modify the textContent, but this does not show up in the image box. Adjusting the .value does not seem to work.
My code:
const buttons = document.querySelectorAll(".row button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
document.querySelector("input").value += buttons[i].value;
})
}
Every solution I have read online just suggests modifying the .value of the input element, which is not working for me, so I am at a loss.
EDIT: Thanks everyone, such a silly thing to overlook.
Modifying the value property should work for you. Your problem lies in this statement:
value += buttons[i].value
Buttons don't have a value unless you specify one. The inner text of a button is accessed using the innerHTML or innerText properties, not the value property:
const button = document.querySelector("button");
const input = document.querySelector("input");
button.addEventListener("click", (e) => {
input.value += button.innerText;
});
<input type="text" />
<button type="button">bleh</button>
With buttons, the value property is used for PHP form submission, not storing textual data.
Are you trying to set the value for the input field based on the button's display text?
If so, you can attempt to replace buttons[i].value with buttons[i].textContent
You can use button.innerHTML to assign the input value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<input type="text" value="" />
<button>1</button>
<button>2</button>
<script>
const buttons = document.querySelectorAll("button");
const input = document.querySelector("input");
buttons.forEach((button) => {
button.addEventListener("click", function () {
input.value += button.innerHTML;
});
});
</script>
</body>
</html>
Related
I am trying to validate inputs. On this particular page, I have 5 inputs. Three will be selected and all three require numbers. Just for this case, I am only going to check that the user has input a number (there will be more things to validate, but I want to get this right first so I don't repeat myself on multiple pages).
const formE = document.getElementById("SubmissionForm");
const sE = document.getElementById("input1");
const tE = document.getElementById("input2");
formE.addEventListener("click", validate);
function validate(e) {
e.preventDefault();
let valid = true;
if (!sE.value) {
const sError = document.querySelector("showError");
sError.forEach((showError));
sError.setAttribute("aria-hidden", false);
sError.setAttribute("aria-invalid", true);
}
return valid;
}
Now, I am aware this doesn't work with this (I got stuck thinking about a forEach and I just haven't taken it further yet.
In the HTML under the input I have this:
<span role="alert" class="showError" aria-hidden="true"> Please enter a number </span>
Bear in mind, this is just for the number validation I will add other validation points too.
So - what is the correct syntax for the JS to find all the showError classes and make their become visible when the user doesn't put in a number?
There are a lot of ways for that. Basically I can suggest this solution relevant to your question:
const button = document.querySelector('#button');
const number_1 = document.querySelector('#number_1');
const number_2 = document.querySelector('#number_2');
const error = document.querySelector('#error');
button.addEventListener('click',()=>{
if(isNaN(parseInt(number_1.value)) || isNaN(parseInt(number_2.value))){
error.removeAttribute('hidden');
}else{
error.setAttribute('hidden','');
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validation Demo</title>
</head>
<body>
<input type="text" id="number_1">
<input type="text" id="number_2">
<button id="button">Check them!</button>
<p id="error" hidden>You can type only numbers!</p>
</body>
</html>
that make up a currency converter, one with the number to be converted, the other receiving the converted number.
My question is: in IE in the input field, an X appears that if clicked allows the deletion of the value. I need to know how I do it (maybe with Javascript) at the click of the X I have to delete the result received in the other input field (see image).
There's no specific event handler available for the clear(X) icon. As a workaround, you can use the mouseup event to catch the change when you clear the input by clicking the clear(X) icon.
Sample code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
input1: <input type="text" id="ipt1" value="111" /><br />
input2: <input type="text" id="ipt2" value="222" />
<script>
$("#ipt1").bind("mouseup", function (e) {
var $input = $(this),
oldValue = $input.val();
if (oldValue == "") return;
// When this event is fired after clicking on the clear button
// the value is not cleared yet. We have to wait for it.
setTimeout(function () {
var newValue = $input.val();
if (newValue == "") {
$("#ipt2").val("");
}
}, 1);
});
</script>
</body>
</html>
Result:
I have seen the example on w3schools that shows how to toggle the visibility on a text/password input.
I would like to have something very similar but it would be one checkbox that can toggle several text inputs that are added in dynamically.
Something like the following:
Note that the code below isn't going to work. It is here to give an example of my situation. I am wondering how to adapt the code seen on the link so I have used the same names as the example on w3schools
HTML
<div class="container_home">
<form id="inputFrm_h" class="inputFrm_home" method="post">
<input type="text" name="env_name[]" /> =
<input type="password" name="env_contents[]" id="myInput"/>
<button class="add_form_field_home">Add</button>
<input type="checkbox" onclick="myFunction()"/>
</form>
</div>
JavaScript
$(document).ready(function(){
var wrapper_home = $(".container_home");
var add_button_home = $(".add_form_field_home");
var y = 1;
$(add_button_home).click(function(e){
e.preventDefault();
console.log('we here');
y++;
$('.inputFrm_home').append('<div><input type="text" name="env_name[]"/> =
<input type="password" name="env_contents[]" class="myInput"/>
Delete<br></div>'); //add input box
});
$(wrapper_home).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); y--;
})
});
I would use an array to store these input elements and when you click the add button it will create and add the new input on the page and in the array. Then when you click the checkbox it will execute a for loop, which will then run through your array and change the type from password to text (making it the letters visible).
http://jsbin.com/risayiquha/edit?html,js,output
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="inputs">
</div>
<button onclick="createInput();">Add Input</button>
<input type="checkbox" onclick="changeValues(this);">
</body>
</html>
JavaScript
var inputList = [];
function createInput() {
var input = document.createElement('input');
input.setAttribute('type', 'password');
document.getElementById('inputs').appendChild(input);
inputList.push(input);
}
// This will essentially just create an input in whatever container you specify and also push the DOM element into an array.
function changeValues(checkbox) {
if (checkbox.checked) {
for (var i = 0; i < inputList.length; i++) {
inputList[i].type = 'text';
}
} else {
for (var i = 0; i < inputList.length; i++) {
inputList[i].type = 'password';
}
}
}
// This just changes the type from text to password for every element
// in the array based on if the checkbox is checked or not.
It looks like you are using jQuery, so you can use that to select elements you want to work with, whether it's one or many.
In your case, $('.inputFrm_home div') will select all div elements that have been appended within the .inputFrm_home element. Which means $('.inputFrm_home div').remove() will remove all matching elements.
Add your Remove All link to the html:
<div class="container_home">
<form id="inputFrm_h" class="inputFrm_home" method="post">
...
</form>
Remove new fields
</div>
Then a click handler for the new link:
$(document).ready(function(){
...
$('.container_home').on('click', '.remove-new-fields', function (e) {
e.preventDefault();
$('.inputFrm_home div').remove();
});
});
Or if you want to use a checkbox to toggle the new fields instead of the link, you can use something like
$('.my-toggle-checkbox').on('change', function (e) {
if($(this).prop('checked')) {
// checkbox is checked
}
else {
// checkbox is not checked
}
})
I am trying to set the length of an accepted input in the input box by using radio buttons. However every time I try to do this I get 'Uncaught TypeError: Cannot read property 'checked' of null'. After searching I have realised this is because JavaScript elements are loading before the whole HTML code can run. Though I cannot not find any code that is able to load the whole page then run the JavaScript that works for me.
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
<script src= 'card.js'></script>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<button type = 'button' id = 'confirm' onclick = 'proceed()'> Click to proceed </button>
</body>
</html>
I have tried windows.onload but it hasn't worked for me. It is highly likely I wasn't using it right.
var cardLength = 0;
if (document.getElementById('visa').checked || document.getElementById('mastercard').checked) {
cardLength = 16;
} else if (document.getElementById('americanexpress').checked) {
cardLength = 15;
}
function proceed() {
var check = document.getElementById('proceed').value;
if (check == cardLength) {
alert('Proceed')
} else {
alert('Card length invalid')
}
}
You are trying to get element by id 'visa', 'mastercard' and 'americanexpress', but there isn't elements with this id's.
Add id's to your input fields like in the code below.
Also try to include js files at the end of <body> tag.
HTML
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa' id='visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard' id='mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress' id='americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<script src= 'card.js'></script>
</body>
</html>
You have multiple issues affecting this.
1) You are correct in that the JS is being loaded before the rest of the HTML. You mentioned that you attempted to use window.onload? Can you please specify how? The following code works:
window.onload = function() {
alert(document.querySelector('[name="card"]:checked').value)
}
Otherwise, I would highly recommend placing your script tag at the bottom of the html, just before the closing </body> tag instead. This has a couple benefits: It loads as you had intended, and it doesn't block the HTML, so to the user, depending on the size of you final script, it loads slightly faster.
2) As lanokvova said, you have no elements with the id of 'visa', 'mastercard', or 'americanexpress'. You can add the ids, or you can use document.querySelector('[name="card"]:checked'), as seen above.
3) You're only running this once on startup. If the user selects a different card, it's not going to update. I would recommend using jQuery for this, as it's significantly cleaner, but it can be done in vanilla JS like so:
document.querySelectorAll('[name="card"]').forEach(function(a) {
a.addEventListener('change', function() {
var selected = this.value;
if(selected === 'visa' || selected === 'mastercard') {
cardLength = 16;
} else if(selected === 'americanexpress') {
cardLength = 15;
}
});
});
A working demo can be found on this Fiddle. You'll just need to update your script to the JS block, and move the tag to the end of the HTML.
Btw, you don't need to close <input> tags, and that <h2> should go inside the body, not the head.
I am trying to have the input text that was entered via a text field form change on button click using JavaScript. I'm having difficulty figuring out why it is not working. Any help would be appreciated.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> </title>
<script type="text/javascript">
function start(){
var button = document.getElementById("button");
button.addEventListener("click", buttonPressed, false);
}
function buttonPressed(){
var text = document.getElementById("textField").value;
text.value = "GMU";
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<form>
<input id="textField" type="text" value="">
<input id="button" type="button" value="Button">
</form>
</body>
</html>
The problem lies here:
var text = document.getElementById("textField").value;
text.value = "GMU";
Take a look at the lines above. You are getting the value of an element and storing it into text but you then try to assign text.value? Consider this situation:
Say that the input currently has a value of "Apples". Doing:
var text = document.getElementById("textField").value;
Will store "Apples" in text. Now you do:
text.value = "GMU";
Since text is a string, and you try to access property value which does not exist for strings, it doesn't work - you've access the value property one too many times.
Now - note that the variable stores the value not reference to the element's value, meaning that in your code above, text only holds the property value, it's not pointing to the actual element's value property. Thus you would need to directly modify the value property like so:
document.getElementById("textField").value = "GMU";
This works because you modify the property of the element itself, you don't copy it into a variable.
You can alternatively store the element into a variable, and do element.value = "val" because an element is an object, and objects have references that point to memory, so when you assign to an object, reference is assigned and it points to the same place in memory.
To change the input text on button click you can use addEventListener just on the button. Then you can change the input field after that.
var button = document.getElementById("button");
var text = document.getElementById("textField");
button.addEventListener('click', function() {
text.value = "GMU";
});
<form>
<input id="textField" type="text" value="">
<input id="button" type="button" value="Button">
</form>