This question already has answers here:
Allow only numbers to be typed in a textbox [duplicate]
(3 answers)
Closed 5 years ago.
As the title say I've written a small code piece to detect if the entered character is a number or a letter and below is the script code.
function checkNum(i) {
//language=JSRegexp
var txt = i.value;
if (isNaN(txt)){
document.getElementById("msg").innerHTML = "Numbers only";
return false
}else{
return true
}
}
<label for="volume">Volume:</label>
<input type="text" name="volume" id="volume" size="4" onkeyup="checkNum(this)" style="margin-left:23px;">
<label for="noPl" style="margin-left: 35px;">No. of Product Lines:</label>
<input type="text" name="noPl" id="noPl" size="4" onkeyup="checkNum(this)">
<div id="msg"></div>
I tried to refine this more but when I change this it stops working for some reason.
What I want this to do is not only prompt the message but also to clear out any entered character from the text box and only allow to enter number.
At the current state it's only prompting the user not to enter letters. I did try many other mentioned methods here but none of them were successful until this.
So if can please enlighten me on what to do also keep in mind I'm still learning JavaScripting not pro yet.
$(function() {
$('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||/65|67|86|88/.test(e.keyCode)&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
<input id="child" type="textarea" />
</div>
You can check
if( typeof txt == 'number' || typeof txt == 'string') {}
Related
This question already has answers here:
Remove text with jQuery
(4 answers)
How do I remove text from a node?
(2 answers)
Closed 11 months ago.
I have a document that I can't edit in PHP looking like this:
<div class="car-search-field-div">
<label class="simple_hide">Türen</label>
<div class="myClear"></div>
doors_count
<input id="car-search-form-field-doors_count" name="search[doors_count]" type="text" value="" placeholder="Anzahl Türen ab">
</div>
Now I am trying to remove the string "doors_count" via jQuery but can't adress it properly. When I try something like:
$('.car-search-field-div').remove('iventory_number', '');
The placeholder of the input field gets removed, but the string "doors_number" still is there. I also thought of using the xpath of the string, but that doesn't work either.
Is there a way to adress / remove a string that has no element wrapped around it? Thank you very much in advance!
you can remove inside all text inside .car-search-field-div
$('.car-search-field-div').contents().filter(function () {
return this.nodeType === 3;
}).remove();
more detail enter link description here
demo
You need DOM access
document.querySelector(".car-search-field-div").childNodes.forEach(node => {
if (node.nodeType === 3 && node.textContent.trim() === "doors_count") node.remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="car-search-field-div">
<label class="simple_hide">Türen</label>
<div class="myClear"></div>
doors_count
<input id="car-search-form-field-doors_count" name="search[doors_count]" type="text" value="" placeholder="Anzahl Türen ab">
</div>
Create an html page with the following form:
<form method="post" name="example" action="">
<p> Enter your name <input type="text"> </p>
<input type="submit" value="Submit Information" />
</form>
<div id="a"></div>
Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->
I run the requirement successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.
My answer is down below;
window.onload = function() {
let form = document.getElementById('form_ref')
form.onsubmit = function() {
let user = form.user.value;
if (parseInt(user) !== user) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
return true;
}
}
<form id="form_ref" method="post" name="example" action="">
<label for="username">User</label><input type="text" name="user" id="username" required>
<div id="a"></div>
<br>
<input type="submit" value="Submit Information" id="submit">
</form>
Your equality check parseInt(user) !== user will always return true because form.user.value is a string but parseInt(...) always returns an integer. If you want to check if the entry is an integer there are a couple ways.
You can change the input's type attribute to number to make sure only digits can be entered and then you just have to make sure it's an integer and not a decimal (type="number" still allows decimal numbers so not just digits). user will still be a string, but it's easier to check. I'd recommend using Number.isInteger(...) to do the checking:
if (!Number.isInteger(parseFloat(user))) {
If you really want to use type="text" you can iterate through user and make sure its characters are all digits:
for(let i = 0; i < user.length; i++) {
if("0123456789".indexOf(user[i]) == -1) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
}
return true;
One advantage of this method is that you can make more characters available if you want to just by adding them to the string that's searched in the iteration. A disadvantage is that it's slower than the other method (the indexOf method has to iterate through the string for every character of user), but for your use case that seems irrelevant-- this function doesn't need to be called many times per second as it's a simple login type of thing, and it's client-side so you don't need to handle many instances at once. If speed is an issue you could probably make a comparison to the integer equivalencies of the characters:
if(user.charCodeAt(i) < "0".charCodeAt(0) || user.charCodeAt(i) > "9".charCodeAt(0)) {
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Junior developer here trying to understand why my code is not working as intended. There are two text fields in my code (Tag 1 and Tag 2), my intention is to concatenate the values of those fields together. I use a function called validateForm to validate that a value is present in both fields; if a value is not present in either field, an alert box displays.
If a value is present in both, I want the validateForm function to call the assembleTags function to concatenate the values the user inputs to one another. Separately, there is also a "reset" button that is intended to reset the generator when clicked. What might I be doing wrong?
<!DOCTYPE html>
<html>
<body>
<p id="demo">
<form id="concatenation" method="post">
Tag 1<br>
<input type="text" name="tag_1" id="tag1" size="75">
<br>
<br>
Tag 2
<br>
<input type="text" name="tag_2" id="tag2" size="75">
<br>
<br>
<input type="submit" name="get_tags" id="gettags" value ="Get Tags" onclick="assembleTags()" style="cursor:pointer">
<input type="button" name="reset_generator" id="resetgenerator" value="Reset Generator" onclick="myServerReset()" style="cursor:pointer">
<br>
<br>
<h3 id="result"></h3>
</form>
</p>
<script>
function validateForm()
var a = document.forms['concatenation']['tag1'].value;
var b = document.forms['concatenation']['tag2'].value;
if (a == "" && b == "") {
alert("Please include Tag 1 and Tag 2");
return false;
}
else if (a == "" && b != "") {
alert("Please include Tag 1")
return false;
}
else if (a != "" && b == "") {
alert("Please include Tag 2")
return false;
else
assembleTags() {
}
function assembleTags() {
document.getElementById('result').innerHTML = document.getElementById('tag1').value + document.getElementById('tag2').value
}
}
function myServerReset() {
document.getElementById('concatenation').reset();
}
</script>
</body>
</html>
I don't know if it is a pasting error but are the opening and closing braces correct?
For example:
Missing opening brace after function validateForm()
Misplaced opening brace after the else
else
assembleTags() {
}
Additional closing brace after function assembleTags()
I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>
This question already has answers here:
How to impose maxlength on textArea in HTML using JavaScript
(16 answers)
Closed 8 years ago.
I tried limiting the user input but it wasn't successful, please guide me where I am making mistake.
JS
<script type="text/javascript">
function countLength() {
var maxLength=10;
var length = document.getElementById("txt").value.length;
if(length>10) {
return false;
}
}
</script>
HTML code
<form name="formA" id="formA" action="#" >
<textarea id="txt" name="txt" onkeyup="countLength()"></textarea>
</form>
Your code basically replicates the maxlength attribute, which seems to work (and I don't think is being deprecated?). Just use that.
<input type='text' name='mytext' maxlength='10'>
return false on onkeyup does nothing (as you've probably noticed). I've seen solutions where someone would just alter the value of the textarea, perform a substring operation, and assign that new value back.
Try this:
function countLength() {
var maxLength=10;
var ta = document.getElementById("txt");
var length = ta.value.length;
if(length>maxLength) {
ta.value = ta.value.substr(0, maxLength);
return false;
}
}