Unable to Limit the user input in JavaScript [duplicate] - javascript

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;
}
}

Related

value was changed by using "<script>" but it is not shown on the page [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 months ago.
<script>
var idn_text = "123"
document.getElementById("idn_id").value = idn_text
</script>
<p><input type="text" placeholder="Results" name="idn" id="idn_id"></p>
the webpage does not display this value, it only displays it as an empty form. How to fix it?
Your input field has not rendered and the script is looking for an element with it's id. A simple solution is to move your script to end of the html file. like this:
<p><input type="text" placeholder="Results" name="idn" id="idn_id"></p>
<script>
var idn_text = "123"
document.getElementById("idn_id").value = idn_text
</script>
Switch the order of your elements and call the script afterwards.
<p><input type="text" placeholder="Results" name="idn" id="idn_id"></p>
<script>
var idn_text = "123"
document.getElementById("idn_id").value = idn_text
</script>

Simple Javascript code to strip out characters from a field [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
It is interesting that I probably did 100 searches and every result assumes that you already know how to use Javascript and only provides a fraction of the code. I do not need JQuery, I just need a simple javascript code that removes parenthesis and a dollar sign from a form field so that I can copy and paste text that is displayed as ($-45.00) for example, I want it to strip out to read just -45.00 and remove the dollar sign and parenthesis. I actually need the HTML part of the code to use in the field
I tried multiple codes and nothing works
<input name="amnt[]" type="text" value="-" size="9" maxlength="12" />
I found some code on this site like this that seems to do what I want:
run1.onclick = function() {
//removes "(" and ")"
output1.innerHTML = input1.value.replace(/[()]/g, '');
}
but it wants you to click a button for it to work and I want it to appear in the value field automatically.
The codes I found online have no result good or bad. I am not a coder I just need to add this simple change to my website that I use for personal use and I'll probably never edit it again.
If anything can anyone give me a link to a website that actually displays the FULL code to do things like this all my results are stackoverflow partial codes that do not help me. That is like buying a car and they only give you a steering wheel I need more than that.
Try the below code Snippet using Regex to strip:
function getResult() {
var oData = document.getElementById("elem_id").value;
var oMatch = /(?:\(\$([\d-.]+)\))/g.exec(oData);
console.log(oMatch);
document.getElementById("elem_id").value = (oMatch == null ? oData : oMatch[1]);
}
<input type="text" id="elem_id" onblur="getResult();" value="-" size="9" maxlength="12"/>
Simply you can do this:
<html>
<body>
<input id="elem_id" name="amnt[]" type="text" value="-" size="9" maxlength="12" oninput="myFunction()" />
</body>
<script type="text/javascript">
function myFunction() {
var element = document.getElementById("elem_id");
var inputStr = element.value;
inputStr = inputStr.replace("(", "");
inputStr = inputStr.replace(")", "");
inputStr = inputStr.replace("$", "");
element.value = inputStr;
}
</script>
</html>
elem_id is your input field id.
Update :-
Here is the optimized way :-
<html>
<body>
<input id="elem_id" name="amnt[]" type="text" value="-" size="9" maxlength="12" oninput="myFunction()" />
</body>
<script type="text/javascript">
function myFunction(event) {
var element = document.getElementById("elem_id");
var inputStr = element.value;
inputStr = inputStr.replace(/[()$]/g, "");
element.value = inputStr;
}
</script>
</html>
Here's some code to do this:
HTML:
<input id="example-id" name="amnt[]" type="text" value="-" size="9" maxlength="12" />
Javascript:
let valueField = document.getElementById("example-id");
valueField.onchange = function(){
valueField.value = valueField.value.replace(/[()\$]/g, "");
}
JSFiddle demo of this in action.

Need to make the javascript function more refined [duplicate]

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') {}

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

JQuery .append and .remove don't seem to be working consistantly [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
According to the other stackoverflow posts on this, this should work. Yet it doesn't really.
This is the code. Pretty basic just for testing.
HTML:
<form>
<div id="inputs">
<p><input type="text" id="user" /></p>
</div>
<hr />
<input type="button" value="Add Another Row" class="add" id="add" >
</form>
And JQuery:
<script>
$(function() {
var node = "";
var count = 0;
$('#add').on('click', function() {
$node = '<p><input type="text" id="' + count + '">Remove Number' + count + '</p>';
count++;
$('#inputs').append(node);
});
$('.remove').on('click', function() {
$(this).parent().remove();
return false;
});
});
</script>
What's weird is that the Add Field function works on my browser. Yet I put the same code into JSFiddle and it wouldn't work there.
The remove function doesn't work at all, either in my browser or in JSFiddle.
I'm still learning JQuery and Javascript in general, so any assistance in helping me learn would be much appreciated. Thanks!
First problem with your code is usage of a wrong Variable
You have declared var node = "";
But assigning it to $node = '<p><input
And appending it to $('#inputs').append(node);
node is always empty .. But $node contains the HTML
Secondly you need to delegate the event
$('.remove').on('click', function() {
supposed to be
$('#inputs').on('click', '.remove', function() {
Events will be only bound to the elements, that exist on the page at the time when the evnent is attached.
So delegating the event should solve the problem.
Check Fiddle

Categories

Resources