Javascript onkeypress conditions - javascript

I'ts my first time exploring java script,Can you help me? thanks in advance
I have a problem in conditioning textboxes.
I have 2 textboxes, the textbox1 and the textbox2, I want the textbox2 to alert me a message on a onkeypress only if textbox2 is greater than textbox1. I succeeded it but the output is not what I expected. so here is what I have done.
//javascript
function validation()
{
x = Number(document.getElementById('text1').value);
y = Number(document.getElementById('text2').value);
if(x < y)
{
alert('Invalid');
return false;
}
}
<!-- HTML -->
<html>
<body>
Text1:<input type="text" id="text1" /><Br />
Text2:<input type="text" id="text2" onkeypress="return validation()" />
</body>
</html>
so the result is this:
Text1:10
Text2:11
when the text2 is 3 digits e.g. 110 the alert message appear, it should appear when I enter 11 because text1 < text2 Am I missing something? or I'm just an idiot.

actually it get called on first character, and works corectly for third one, so use onchange
<input type="text" id="text2" onchange="return validation()" />
eventually you will have to decide the console.log instead of alerting as it blocks you testing way.

you can see this example:
http://jsfiddle.net/yonatanalexis22/yxub03yt/1/
var text2 = document.getElementById('text2');
text2.onchange = function(){
x = Number(document.getElementById('text1').value);
y = Number(this.value);
if(x < y)
{
alert('Invalid');
}
}

First: Your inputs are "text". If you want to compare numbers, change the type of the input to "number".
Second: Adding a Listener is a cleaner way of handling this.
So the HTML could look like this:
Text1:<input type="number" id="text1" /><Br />
Text2:<input type="number" id="text2"/>
And your JavaScript like this:
document.getElementById("text2").addEventListener("change", function() {
if($('#text1').val() < $('#text2').val()) alert();
});
This is just a short version.
Here is the JSFiddle.

Related

How to return the first character of a text input? [duplicate]

I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
And this is my JavaScript code:
<script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>
How do I get the value from the text field into JavaScript?
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
Method 1
document.getElementById('textbox_id').value to get the value of
desired box
For example
document.getElementById("searchTxt").value;
 
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0],
for the second one use [1], and so on...
Method 2
Use
document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection
For example
document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.
Method 3
Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection
For example
document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.
Method 4
document.getElementsByName('name')[whole_number].value which also >returns a live NodeList
For example
document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.
Method 5
Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element
For example
document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name
Method 6
document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.
For example
document.querySelectorAll('#searchTxt')[0].value; selected by id
document.querySelectorAll('.searchField')[0].value; selected by class
document.querySelectorAll('input')[0].value; selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name
Support
Browser
Method1
Method2
Method3
Method4
Method5/6
IE6
Y(Buggy)
N
Y
Y(Buggy)
N
IE7
Y(Buggy)
N
Y
Y(Buggy)
N
IE8
Y
N
Y
Y(Buggy)
Y
IE9
Y
Y
Y
Y(Buggy)
Y
IE10
Y
Y
Y
Y
Y
FF3.0
Y
Y
Y
Y
N IE=Internet Explorer
FF3.5/FF3.6
Y
Y
Y
Y
Y FF=Mozilla Firefox
FF4b1
Y
Y
Y
Y
Y GC=Google Chrome
GC4/GC5
Y
Y
Y
Y
Y Y=YES,N=NO
Safari4/Safari5
Y
Y
Y
Y
Y
Opera10.10/
Opera10.53/
Y
Y
Y
Y(Buggy)
Y
Opera10.60
Opera 12
Y
Y
Y
Y
Y
Useful links
To see the support of these methods with all the bugs including more details click here
Difference Between Static collections and Live collections click Here
Difference Between NodeList and HTMLCollection click Here
//creates a listener for when you press a key
window.onkeyup = keyup;
//creates a global Javascript variable
var inputTextValue;
function keyup(e) {
//setting your input text to the global Javascript Variable for every key press
inputTextValue = e.target.value;
//listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
if (e.keyCode == 13) {
window.location = "http://www.myurl.com/search/" + inputTextValue;
}
}
See this functioning in codepen.
I would create a variable to store the input like this:
var input = document.getElementById("input_id").value;
And then I would just use the variable to add the input value to the string.
= "Your string" + input;
You should be able to type:
var input = document.getElementById("searchTxt");
function searchURL() {
window.location = "http://www.myurl.com/search/" + input.value;
}
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
I'm sure there are better ways to do this, but this one seems to work across all browsers, and it requires minimal understanding of JavaScript to make, improve, and edit.
Also you can, call by tags names, like this: form_name.input_name.value;
So you will have the specific value of determined input in a specific form.
Short
You can read value by searchTxt.value
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
<script type="text/javascript">
function searchURL(){
console.log(searchTxt.value);
// window.location = "http://www.myurl.com/search/" + searchTxt.value;
}
</script>
<!-- SHORT ugly test code -->
<button class="search" onclick="searchURL()">Search</button>
<input type="text" onkeyup="trackChange(this.value)" id="myInput">
<script>
function trackChange(value) {
window.open("http://www.google.com/search?output=search&q=" + value)
}
</script>
Tested in Chrome and Firefox:
Get value by element id:
<input type="text" maxlength="512" id="searchTxt" class="searchField"/>
<input type="button" value="Get Value" onclick="alert(searchTxt.value)">
Set value in form element:
<form name="calc" id="calculator">
<input type="text" name="input">
<input type="button" value="Set Value" onclick="calc.input.value='Set Value'">
</form>
https://jsfiddle.net/tuq79821/
Also have a look at a JavaScript calculator implementation.
From #bugwheels94: when using this method, be aware of this issue.
If your input is in a form and you want to get the value after submit you can do like:
<form onsubmit="submitLoginForm(event)">
<input type="text" name="name">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<script type="text/javascript">
function submitLoginForm(event){
event.preventDefault();
console.log(event.target['name'].value);
console.log(event.target['password'].value);
}
</script>
Benefit of this way: Example your page have 2 form for input sender and receiver information.
If you don't use form for get value then
You can set two different id (or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
If you set the same value for two inputs, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver. Later, if you change the order of 2 form in HTML, you need to check this code again
If you use form, then you can use name, address, ...
You can use onkeyup when you have more than one input field. Suppose you have four or input. Then
document.getElementById('something').value is annoying. We need to write four lines to fetch the value of an input field.
So, you can create a function that store value in object on keyup or keydown event.
Example:
<div class="container">
<div>
<label for="">Name</label>
<input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Age</label>
<input type="number" name="age" id="age" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Email</label>
<input type="text" name="email" id="email" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Mobile</label>
<input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
</div>
<div>
<button onclick=submitData()>Submit</button>
</div>
</div>
JavaScript:
<script>
const data = { };
function handleInput(e){
data[e.name] = e.value;
}
function submitData(){
console.log(data.fname); // Get the first name from the object
console.log(data); // return object
}
</script>
function handleValueChange() {
var y = document.getElementById('textbox_id').value;
var x = document.getElementById('result');
x.innerHTML = y;
}
function changeTextarea() {
var a = document.getElementById('text-area').value;
var b = document.getElementById('text-area-result');
b.innerHTML = a;
}
input {
padding: 5px;
}
p {
white-space: pre;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
<input id="new" >
<button onselect="myFunction()">it</button>
<script>
function myFunction() {
document.getElementById("new").value = "a";
}
</script>
One can use the form.elements to get all elements in a form. If an element has id it can be found with .namedItem("id"). Example:
var myForm = document.getElementById("form1");
var text = myForm.elements.namedItem("searchTxt").value;
var url = "http://www.myurl.com/search/" + text;
Source: w3schools
function searchURL() {
window.location = 'http://www.myurl.com/search/' + searchTxt.value
}
So basically searchTxt.value will return the value of the input field with id='searchTxt'.
Short Answer
You can get the value of text input field using JavaScript with this code: input_text_value = console.log(document.getElementById("searchTxt").value)
More info
textObject has a property of value you can set and get this property.
To set you can assign a new value:
document.getElementById("searchTxt").value = "new value"
Simple JavaScript:
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
}

how to make sure user type correct type in form

I found this example on w3schools website -
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Can Validate Input</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
when I input 9 - it says 'Input OK'
when I input 11 -it says 'Input not valid'
but I have following questions -
how can I force users to type the correct type I want, but if they don't, then don't allow them to submit or re-input.
you are compareing string with number!
you should parse x to an integer like:
x = parseInt(document.getElementById("numb").value);
like this <input type="number" id="numb"/>
There are several ways to listen to changes on the input for instance. One way, just changing the code in the example above is to switch to listen to changes on the number field as trigger to validate:
<input id="numb" onChange="myFunction()">
<button type="button" >Submit</button>
Then you can add more logic into the myFunction() to make sure the button can't be pressed until numbers are valid and so on, see a working example that stops the user from pressing the button until input is valid:
https://jsfiddle.net/5fg4payk/2/
Assuming you're wanting range restriction you can achieve this with the HTML5 constraint validation API in combination with type="number", min="1" and max="10".
<input type="number" min="1" max="10" step="1" id="numb" oninput="(validity.valid)||(value='');">
To prevent re-input, you need to disable the field.
document.getElementById("numb").disabled = true;
So your code becomes :
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
document.getElementById("numb").disabled = true;
} else {
text = "Input OK";
}

I want to restrict users from entering number ending with 5

Here is text field.I want users to only enter value like 210,220,230,... and restrict from entering something like 215,225,...
I am looking for suggetions.I don't have much knowledge of javascript.
If you just want to prevent strings that end in '5':
document.getElementById("input").onblur = checkEND;
function checkEND() {
let firstValue = event.currentTarget.value;
if(firstValue.endsWith('5')){
warnUser()
}
}
This won't validate that the string is a valid number though.
function testInput() {
var key = window.event.keyCode;
var x = document.getElementById('textarea').value
var y = document.getElementById('textarea2').value
var z = parseInt(x, 10);
if (z+10 == y) {
document.getElementById('result').innerHTML = "valid";
} else {
document.getElementById('result').innerHTML = "invalid";
}
}
<textarea maxlength="3" id="textarea">5</textarea>
<textarea maxlength="3" id="textarea2">15</textarea>
<button onclick="testInput()">Test Input</button>
<div id="result"></div>
The first input is your first number, the second is your second number.
See Comments If Your Wondering Why This Doesn't Answer His OG Question
You can experiment with the setCustomValidity() of input elements (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) from an onblur, onchange or oninput handler. If you are not satisfied with the value, set an error message, and an empty string otherwise. As long as the error message is set to non-empty, it is displayed and the form refuses to submit:
function check5() {
cgiftcardq.setCustomValidity(cgiftcardq.value.endsWith('5')?"Nope, it can not end with 5":"");
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" onblur="check5()">
<input type="submit" value="Send">
</form>
(StackOverflow snippets interfere with form submission - probably as part of security -, so successful submission just makes the form disappear)
As setCustomValidity() does not work everywhere (according to the compatibility table, it will not work on non-Andorid mobiles), classic "budget" solution may be mentioned too: you can simply disable the send button as long as you are not satisfied with the input:
function check5() {
if(cgiftcardq.value.endsWith('5')){
send.disabled=true;
message.innerHTML="Nope, it can not end with 5";
} else {
send.disabled=false;
message.innerHTML="OK";
}
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" oninput="check5()">
<input id="send" type="submit" value="Send" disabled>
</form>
<div id="message"></div>

check if input is between two int or float then display or not display content

In javascript I need to check whiwh value user enter in an html input like this:
<input type="text" id="volume" class="form-control" name="voilume"></input>
<div id"button"></div>
Ineed to know if the input is between 0,5 and 8 (so I have int and float as you can understand).
So the value has to be >= 0,5 and <= 8
If value input if between 0,5 and 8 I have to display a button, else nothing to do. But I need to prevent if user change the value many times.
So if he enters 3 display a button in div id=button", if it changes for another value like 2 for example keep displaying the button, but if he changes value input for 100 I need to remove the button in div id="button".
for now I tried something like this in order to test if it works:
var input= $('#volume').val();
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
But it does not work.
You can exploit the CSS Constraint Validation here a little bit. It seems to me like a X/Y Problem. Actually, we could set our min, max and step values for this <input> element and then let the browser do the validation:
<input type="number" min="0.5" max="8" step="0.1" required id="volume" class="form-control" name="voilume">
Alongside this, we can make usage of the pseudo css selectors :valid and :invalid like so:
input:valid~div#button {
display: block;
}
input:invalid~div#button {
display: none;
}
This would have the effect, that if we enter a valid value in our input control, the button will be displayed. If not, the button disappears. Magic!
Example: https://jsfiddle.net/4q1fjqwp/
.val() of an input field is a string, you have to convert it to a number in order to be able to compare it to numbers by >=, <=. You also had a typo: id"button"
function go() {
var input=parseFloat($('#volume').val(), 10);
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="volume" class="form-control" name="voilume"/>
<div id="button"></div>
<button onclick="go()">run</button>
The problem may happen when input contain comma ,
so "0,5" >= 0.5 will return false and parseFloat("0,5") will return 0.
You need replace , with .
Something like below will work.
<input type="text" id="myTextField" onblur="change()"/>
<input type="submit" id="byBtn" value="" />
JavaScript
function change() {
var myTextbox = document.getElementById('myTextField').value;
var button = document.getElementById('byBtn');
if (parseFloat(myTextbox) >= 0.5 && parseFloat(myTextbox) <= 8) {
button.value = "OK";
} else {
button.value = "";
}
}
you need to parse string value to integer. for that use parseInt().
it will parse string to integer.
replace this:
var input= $('#volume').val();
by
var inputval= parseInt($('#volume').val());

Javascript Addition Error Message

I am new to javascript and was wondering what the the following error message means:
Hello __ NaN
What does NaN mean?
My script is as follows:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("What Is Your Name?");
return false;
}
}
function addNos(){
var a, b, res;
a= parseFloat(document.myForm.salary.value);
b= parseFloat(document.myForm.requiredamount.value);
res = a+b;
window.alert("Hello" + a + b );
}
</script>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<label>Your Name</label> <br /><br /><input name="name" type="text" />
<br /><br />
<label>Your Salary</label><br /><br />
<select name="salary">
<option value="10000">10000</option>
<option value="20000">20000</option>
<option value="30000">30000</option>
</select>
<br /><br />
<label>Required Amount</label><br /><br />
<input name="requiredamount" type="radio" value="5000" /> 5000
<input name="requiredamount" type="radio" value="10000" /> 10000
<input name="requiredamount" type="radio" value="15000" /> 15000
<input name="requiredamount" type="radio" value="20000" /> 20000
<br /><br />
<input name="" type="submit" value="Get Quote" onclick="addNos()" />
</form>
i am trying to add the requiredamount with the salary and also get the name to appear in the dialog box.
anyone know the anwseR?
function addNos(){
var a, b, res;
a= parseFloat(document.myForm.salary.value);
b= parseFloat(document.myForm.requiredamount.value);
res = a+b;
window.alert("Hello" + a + b );
}
You are relying on user input to be properly entered as a number. You should validate that the input is a number using a RegEx before parsing.
http://jsfiddle.net/rMgeB/
It means "Not a Number" (NaN). This will happen if either the "salary" field or the "requiredamount" field has some non-numeric value in it. For instance if you had the values "100" and "Blah" repsectively, the parseFloat() used to calculate a would return the number 100 and the parseFloat() for b would return NaN since "Blah" has no numeric representation. Subsequently when you try to add 100 and NaN in your alert box, you'll get the behavior you're seeing.
You can double check these values by using the isNaN() function:
a = parseFloat(...);
if (isNaN(a))
{
alert("Sorry, you must enter a real number");
return;
}
Hope that clears things up.
EDIT:
What's most likely the case is that your input has a $ in it. parseFloat("$100") == NaN whereas parseFloat("100") == 100 so you'll need to strip any leading dollar signs in your code first.
Try this:
http://jsfiddle.net/LEX84/
I did not add a test if a radio button is selected. NaN will be the result if no radio button is selected.
Obtaining the radio button is from here: javascript selected radio
function validateForm()
{
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("What Is Your Name?");
return false;
}
}
function getCheckedRadioId(name) {
var elements = document.getElementsByName(name);
for (var i=0, len=elements.length; i<len; ++i)
if (elements[i].checked) return elements[i].value;
}
function addNos(){
var a, b, res;
a= parseFloat(document.myForm.salary[document.myForm.salary.selectedIndex].value);
alert(a);
b= parseFloat(getCheckedRadioId("requiredamount"));
res = a+b;
window.alert("Hello " + a + " " + b );
}
NaN means Not a Number. It can happen when dividing by zero, or adding an undefined value.
Wiki:
http://en.wikipedia.org/wiki/NaN
Ok i've not got the time to test your code, but it looks like your JavaScript is trying to access the form elements before the user has entered a value? (meaning they're undefined).
need to download jQuery to do this:
You could surround your JavaScript code in $(document).ready(function(){ //your code {);
How to detect causes of NaN
Has the html element loaded (sometimes the html loads after the javascript)
Is the value undefined?
Are you dividing by zero?
JavaScript has http://www.w3schools.com/jsref/jsref_isnan.asp

Categories

Resources