I'm trying to have a value (key) that updates to correspond with a number in a textbox (angle) divided by a value (25). However, for some reason, the changeMe function doesn't seem to be executing. Am I using onchange incorrectly?
<script type="text/javascript">
function changeMe(x)
{
var y=document.getElementById(x).value;
y = (y/25);
y = (Math.round(y));
document.getElementById(key).value=y;
}
</script>
<form method="POST" action="">
Your Angle: <input type="text" name="angle" id="angle"
onchange="changeMe(this.id)" value="0"/>
Key: <span id="key">0</span><br />
</form>
Change the line
document.getElementById(key).value=y;
to
document.getElementById('key').innerHTML=y;
To see if it's being called, just add this as the first line:
alert("Hey, I'm being called!");
Now, I already see a problem here: in the last line of your function, you're doing getElementById(key), but you should enclose key with double quotes. If not, it's being considered a variable instead of a string.
The changeMe(this.id) bothers me, I am using to seeing just (this), but, the best way to know what is going on is to use either the Web Developer extension in IE8 (I press F12 and it comes up) or, preferably, Firebug, on Firefox, and then you can put in a break point at the beginning of the changeMe function and see what is passed in, as there may be an error.
And the other two already mentioned about the problem with your getElementById.
The last line document.getElementById(key) should be document.getElementById("key").
By the way you can simplify this a fair bit by passing the <input> element directly instead of its id:
<script type="text/javascript">
function changeMe(angle)
{
var key = document.getElementById("key");
key.innerHTML = Math.round(angle.value / 25);
}
</script>
<form method="POST" action="">
Your Angle: <input type="text" name="angle" id="angle"
onchange="changeMe(this)" value="0"/>
Key: <span id="key">0</span><br />
</form>
Try using the suggestion by James Black to use onchange="changeMe(this)", your function becomes simplified
function changeMe(x) {
y = Math.round(x.value/25);
document.getElementById('key').innerHTML = y;
}
Notice the document.getElementById('key').innerHTML = y, This will replace the inner html (as the name describes), I think that is what you wanted to use.
Related
I want to restrict an input text through a regular expression. In the first example I use the attribute onkeyup = "lettersOnly(this)" inside the HTML, as follows:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username" onkeyup="lettersOnly(this)">
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
</script>
It works but I learnt that this is a bad practice. I found other solution avoiding that, and setting someVariable.onkeyup inside <script> tags. However, my goal is to find another way to get the same result using addEventListener ('keyup', lettersOnly, false). I researched a lot for this specific situation but no answers. Is it possible? I tried the following:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
<!--No more “onkeyup” attribute.-->
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value.addEventListener('keyup', lettersOnly(input){
input.value = input.value.replace(regex, "");
}, false)
}
</script>
Doesn‘t work. My intention is to avoid the event handler in the html and use instead, the addEventListener. What is wrong in this last coding? Why doesn‘t work? I‘ll really appreciate your patience.
In the code that you said you have tried; the function lettersOnly() will never be called and addEventListener() will never be called.
You can simply change it as follow -
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
document.getElementById("username").addEventListener("keyup", lettersOnly(this), false);
</script>
Finally, I found myself a solution and I want to share it.
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
<!--No more “onkeyup” attribute.-->
</form>
<script>
let user = document.getElementById("username");
var regex = /[^a-z]/gi;
user.addEventListener("keyup", ()=>{
user.value = user.value.replace(regex, "");
})
// The “user” variable has been just to simplify a lot of repeated coding, as it is equivalent to “document.getElementById(“username”).
</script>
I don‘t know if this is the best and optimal way to solve my inquire but it works. No “ONkeyup” at all, but using, instead, addEventListener ("keyup", anonymous arrow function). I‘ll really appreciate if anybody has any other suggestion.
The main problem with your second piece of code was that you weren't actually attaching the eventListener to the input element since the outer lettersOnly function was also not called at any time. It appears you resolved this in your own answer, but I'm going to expand upon my comment and suggest using keydown instead.
In the following snippet, I changed the eventListener to attach to keydown instead of keyup. Then we test if the new key (via event.key) matches our regex with .match. If the key pressed is a non-letter character, the match will be non-null, so we want to utilize event.preventDefault() to interrupt the new key from being added to the input value.
Note: this has the added benefit of not needing to use replace or replaceAll to remove the invalid character.
var regex = /[^a-z]/gi;
function lettersOnly(event) {
if (event.key.match(regex) !== null) {
// Since it is an invalid character, we will prevent default
event.preventDefault();
// Log the key to the console for demonstration
console.log(event.key);
// Not needed since we preventDefault()
//event.target.value = event.target.value.replace(regex, "");
}
}
// `username` is equivalent to `document.getElementById("username")
username.addEventListener("keydown", lettersOnly, false);
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
</form>
This is the scanner I am using...
On Web : https://atandrastoth.co.uk/main/pages/plugins/webcodecamjs/
On Git : https://github.com/andrastoth/WebCodeCamJS
It's working 100%. But I need to add some custom extra's.
When the QR Code is scanned it outputs my result into this paragraph tag.
<p id="scanned-QR"> The scanned code text value is printed out here </p>
However I need it to be an input field so I can use it's value in a url.
How can I set an input field equal to the value submitted to the Paragraph tag?
I have tried these methods and they failed :
Method 1
<input id="scanned-QR"> The scanned code text value is printed out here </input>
Method 2
<p id="scanned-QR" onchange="update"></p>
<input id="code_id_value" type="text" name="" value="">
<br>
<script>
function update(){
var code_id_value = document.getElementById("scanned-QR").innertext;
document.getElementById("code_id_value").value = code_id_value;
}
</script>
The key that you're missing is that the T in .innertext needs to be capitalised (as .innerText).
In addition to this, using inline event handlers is bad practice, and you should consider using .addEventListener() instead of onchange.
This can be seen working in the following:
document.getElementById("scanned-QR").addEventListener("click", update);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerText;
document.getElementById("code_id_value").value = code_id_value;
}
// Demo
update();
<p id="scanned-QR">Text</p>
<input id="code_id_value" type="text" name="" value="">
Hope this helps! :)
So this is the solution I came up with.
Here's my paragraph and input function
<p id="scanned-QR" onchange="update">SCAN.BZ</p>
<input id="code_id_value" type="text" name="" value="">
Here's my function. WITH a interval for every millisecond or faster "I think it's every millisecond".
It runs smoothly and doesn't lag. and the result is practically immediate.
<script type="text/javascript">
setInterval(update,1);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerHTML;
document.getElementById("code_id_value").value = code_id_value;
}
update();
</script>
Thanks for the help "Obsidian Age" Really appreciate it. :)
I am writing a Javascript program that takes a users input text, then (pending a radio button check – lowerCase/UpperCase) converts the input text to either lowercase/upperCase and outputs the value back to the form.
Purely trying to learn on my own Javascript. I am moderately new (but savvy) to JS. Pretty solid on HTML, CSS, Java, but BRAND new with interacting with page elements.
I have dug around for two days to try and solve this. I have even checked out a few books at my local library. (Currently reading the text, Microsoft guide to CSS/HTML, and JS). What other books would you recommend in order to under JS more?
Here is the code below. Although I know one can use CSS in order to convert this and I have done this. I'm purely just wanting to figure out Javascript.
<!DOCTYPE html>
<html>
<head>
<title> Case Changer By: Elliot Granet</title>
<style>
function convert(){
var convertedText = document.test.input.value;
if(document.getElementById("lowerCase").checked = true){
var output = convertedText.toLowerCase();
}else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
convert();
</head>
The rest -
<body>
<h3>Choose your Conversion method below:</h3>
<form action="getElementById">
<fieldset>
<input id="lowerCase" type="radio" name="case" value="lowerCase">Lower Case<br>
<input id ="upperCase" type="radio" name="case" value="upperCase">Upper Case<br><br>
</fieldset>
<fieldset>
<textarea id="inputText" name="input" form="inputText">Enter text here to be Converted...</textarea>
</fieldset><br>
<fieldset>
<textarea id ="outputText" name="output" form="outputText">Converted text will appear here...</textarea>
</fieldset>
<input type="button" value="Convert">
</form>
</body>
</html>
You need to make few changes to make this function work.
style is an invalid tag to put js code. You need to put it inside <script> tag
If you are writing this function inside header yo may come across error since before DOM is ready it will try to get value of textarea with id inputText.
document.getElementById(idName').value but not is right syntax to get the value of element using id
Attaching convert() with the button. So when you will click on button the function will execute.
5.document.getElementById("lowerCase").checked = true this is wrong.It mean that checkbox will get checked as = will assign the value . Instead you need to compare the value. So use == or ===
if you declare var output inside if loop it wont be available inside else. So you need to declare it outside the if-else loop
Hope this snippet will be useful
HTML
<input type="button" value="Convert" onclick="convert()">
JS
window.load =convert; // convert function will be called after window is ready
function convert(){
var output; //variable declaration outside if-else loop
var convertedText = document.getElementById('inputText').value; //document.getElementById
if(document.getElementById("lowerCase").checked == true){ // == comparision
output = convertedText.toLowerCase();
}
else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
EXAMPLE
I'm struggling with some very basic Javascript here (not a big fan or expert in Javascript at all!), and I just cannot wrap my head around why this fails....
I have some very basic HTML markup:
Value 1: <input type="text" id="int1" /> <br />
Value 2: <input type="text" id="int2" /> <br /><br />
<input type="button" name="add" value="Add" onclick="add();" />
and then some Javascript:
<script type="text/javascript">
onerror = unhandled;
function unhandled(msg, url, line) {
alert('There was an unhandled exception');
}
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
From my (Pascal- and C#-based) understanding, the add method should read out the values from the input elements with ID's int1 and int2 and add those values and then show the result.
Seems basic and harmless enough......
But even if I do enter two valid integers (like 10 and 20) into those two textboxes, I keep getting an There was an unhandled exception and I just cannot understand what is going wrong here.
Can someone enlighten me??
$.val() returns a string value. you need to convert both returned strings to numbers and then add the values.
try this
function add() {
alert(parseFloat($('#int1').val()) + parseFloat($('#int2').val()));`
}
You have a few different issues going on here.
Firstly, if you're using jQuery, it would be best to use a click event instead of an inline function call.
Second, the values are returned as strings from the inputs, so you must convert them by using parseInt()
Also, your error handler is useless if you're not alerting the error message, the msg argument in this case.
onerror = unhandled;
function unhandled(msg, url, line) {
alert(msg);
}
$("input[name=add]").click(function() {
var int1 = parseInt($("#int1").val());
var int2 = parseInt($("#int2").val());
alert(int1 + int2);
});
Fiddle: http://jsfiddle.net/9bepJ/
Well firstly, .val() will return a string. The addition operator won't add the numeric values of those strings, it will just concatenate the strings.
But that's not causing your exception. Get rid of the everything but the add function. It should work then.
<script type="text/javascript">
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
This is, of course, assuming you included the jQuery library since that's where the $() function comes from.
Try using binding onclick event instead writing it inline.
I have made fiddle for you. Check it out
UPDATE:
http://jsfiddle.net/rkhadse_realeflow_com/FhL9g/7/
<script>
function add() {
var int1 = parseInt(document.getElementById("int1").value);
var int2 = parseInt(document.getElementById("int2").value);
alert(int1 + int2);
}
</script>
Value 1:
<input type="text" id="int1" />
<br />Value 2:
<input type="text" id="int2" />
<br />
<br />
<button onclick="add()">Add</button>
As it looks like you're using $(..) functions, be sure you're including jQuery on the page, before you use those functions.
Aside from that, I always have scope issues when I put my event handlers in HTML attributes. Try putting them in your code, which has the added benefit of being unobtrusive JavaScript (a new pattern for cleaner, more maintainable code).
Also, add an id to your button:
<input type="button" name="add" value="Add" id="myButton" />
Add event handler in code and remove onclick attribute from your button
document.getElementById('myButton').onclick = add;
I recently received help on this site towards using querySelector on a form input such as select but as soon as I took <select> out it completely changed what had to be done in the function.
HTML:
<form onsubmit="return checkForm()">
Password: <input type="text" name="pwd">
<input type="submit" value="Submit">
</form>
Javascript:
<script language="Javascript" type="text/javascript">
debugger;
function checkForm() {
var form = document.forms[0];
var selectElement = form.querySelector('');
var selectedValue = selectElement.value;
alert(selectedValue);
</script>
Before, I had ('select') for the querySelector, but now I'm unsure what to put there.
I've tried multiple things as well as querySelectorAll but I can't seem to figure it out.
To be clear I'm trying to pull the name="pwd".
How could I do this?
You can try 'input[name="pwd"]':
function checkForm(){
var form = document.forms[0];
var selectElement = form.querySelector('input[name="pwd"]');
var selectedValue = selectElement.value;
}
take a look a this http://jsfiddle.net/2ZL4G/1/
I know this is old, but I recently faced the same issue and I managed to pick the element by accessing only the attribute like this: document.querySelector('[name="your-selector-name-here"]');
Just in case anyone would ever need this :)
1- you need to close the block of the function with '}', which is missing.
2- the argument of querySelector may not be an empty string '' or ' '... Use '*' for all.
3- those arguments will return the needed value:
querySelector('*')
querySelector('input')
querySelector('input[name="pwd"]')
querySelector('[name="pwd"]')
Note: if the name includes [ or ] itself, add two backslashes in front of it, like:
<input name="array[child]" ...
document.querySelector("[name=array\\[child\\]]");
So ... you need to change some things in your code
<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>
<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;
function checkForm() {
alert(pwd.value);
}
</script>
Try this way.
I understand this is an old thread. However, for people who stepped upon this like me, you may utilize the following code.
select the input using elements collection
form.elements['pwd']
or using namedItem method under elements collection
form.elements.namedItem('pwd')
These examples seem a bit inefficient. Try this if you want to act upon the value:
<input id="cta" type="email" placeholder="Enter Email...">
<button onclick="return joinMailingList()">Join</button>
<script>
const joinMailingList = () => {
const email = document.querySelector('#cta').value
console.log(email)
}
</script>
You will encounter issue if you use this keyword with fat arrow (=>). If you need to do that, go old school:
<script>
function joinMailingList() {
const email = document.querySelector('#cta').value
console.log(email)
}
</script>
If you are working with password inputs, you should use type="password" so it will display ****** while the user is typing, and it is also more semantic.
querySelector() matched the id in document. You must write id of password in .html
Then pass it to querySelector() with #symbol & .value property.
Example:
let myVal = document.querySelector('#pwd').value
form.elements.name gives better perfomance than querySelector because querySelector have to look for in entire document every time. In case with form.elements.name computer directly gets inputs from form.