Javascript: Allow Only Values less than input initial value - javascript

on my form, I have many text input fields with pre-filled decimal values, the user can edit the values before submitting the form.
I was wondering if there is anyway using javascript/jquery, to make each input allow only values less than its initial value.
I find it quite challenging, so I thought about posting it here.
Thank you guys

Use jQuery Validation plugin's max method.
Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and 23 or smaller.</title>
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="field">Required, maximum value 23: </label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
max: $('your_input_selector').val()
}
}
});
</script>
</body>
</html>

This may help you:
var initialValue = $("#myTextbox1").val()
$("#myTextbox1").on("input", function() {
if($("#myTextbox1").val() > initialValue) {
$("#myTextbox1").val(initialValue);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextbox1" type="text" value="5"/>

This solution converts the input into a number, prevents default form action, checks if the input value is a number and if not it alerts the user and resets the default input value, checks to see if the new value is less the the original and if it is not it resets the input to the original value.
HTML
<form id="myForm" action="">
<input type="text" id="myValue" value="5" />
<input type="button" id="myButton" value="validate" />
</form>
JavaScript
var origVal = $('#myValue').val();
$('#myButton').on('click', function(e) {
var getVal = Number($('#myValue').val());
e.preventDefault();
if (isNaN(getVal) === true) {
alert('The input value has to be a number.');
$('#myValue').val(origVal);
}
if (getVal > origVal) {
alert('The input value has to be less than the original value of ' + origVal);
$('#myValue').val(origVal);
}
});

Related

DirtyForms does not work on input hidden field

I added dirtyForms to my forms to detect any changes on one of the input fields https://github.com/snikch/jquery.dirtyforms
HTML
<form>
<input type="text" id="post" name="post">
<input type="hidden" id="body" name="body">
<froala-editor input="body">
</froala-editor>
</form>
Javascript
$('document').ready(function() {
$('form').dirtyForms();
});
However for input hidden seems like it doesn't add the dirty class, it only works for input type="text" . Any ideas on how to solve this problem?
Because it does not make sense when the user is not the one entering the data in the field.
You can do it yourself
SO does not allow the editor so I tested here
$('form').toggleClass('mydirty', e.target.textContent !== "");
tests the editor, it makes more sense than the input field
https://plungjan.name/SO/froala/
$('form').dirtyForms({
helpers: [{
isDirty: function($node, index) {
if ($node.is('form')) {
return $node.hasClass('mydirty');
}
}
}]
});
var editor = new FroalaEditor('#froala')
$(document).on("keyup", function(e) {
$('form').toggleClass('mydirty', e.target.textContent !== "");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/froala-editor#3.2.3/js/froala_editor.min.js"></script>
<form>
<input type="text" id="post" name="post">
<input type="hidden" id="body" name="body">
<div id="froala" input="body">
</div>
</form>

How do i alert the textbox input to a user

If i had a button and an input field. How would i alert whatever is in the input field to the user, when the button is clicked.
Explain your code please.
Make it as simple as possible.
<input type="text" id="input" />
<button onclick="displayEnteredText()">Display</button>
<script>
function displayEnteredText() {
var inputText = document.getElementById("input"); // get the element with id "input" which is the textField
alert(inputText.value); // show the value of the input in alert message
}
</script>
One possible approach:
<!DOCTYPE html>
<html>
<head></head>
<body>
<input id="name" value="">
<input type="button" value="show me the name" onclick="alert(document.getElementById('name').value)">
</body>
</html>
Another possible approach:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var buttonElement = document.getElementById('button');
buttonElement.addEventListener('click', function() {
alert(document.getElementById('name').value);
});
}
</script>
</head>
<body>
<input id="name" value="">
<input id="button" type="button" value="show me the name">
</body>
</html>
With the second approach you can separate responsabilities, one person can create de html, and another person can focus in create javascript code.
Exists several ways to do this, but with two examples i think is enough in the current context
<body>
<input type="text" name="basicText" id="alertInput">
<button class="alertButton">Click me!</button>
</body>
<script type="text/javascript">
$(".alertButton").click(function(){
var value = $("#alertInput").val();
alert(value + " was entered");
});
</script>
In order to show what you typed in your alert, you need to reference the value inside the textbox. Since jquery is tagged in the post, I used it to get what's in the text box.
You can also try this one
HTML
<input type="button" id="btnclick" style="width:100px" value="Click Me" />
<input type="text" id="txtbox">
JS
$("#btnclick").click(function(){
var txtvalue = $("#txtbox").val();
alert("User enter " + txtvalue);
})
FIDDLE

While clicking on submit button null value should get passed and not a default one

Need an amendment to the below code, when I tested this code it was working fine but, what happened is that when user clicks on submit button the default value gets propagate say default value was username then when user doesn't entered anything inside text box the default value passed as a "username" only. But what I want is the value should get is a blank value when user doesn't enter anything (i.e. null value) although text box may show default value (i.e. username). Below is the code for the same:
<FORM action="http://localhost:2013" method="post">
<INPUT type="text" size="25" value="Username" onFocus="if(this.value == 'Username') {this.value = '';}" onBlur="if (this.value == '') {this.value = 'Username';}" />
<INPUT type=submit value=Submit>
</FORM>
So basically I want display name only for "display" purpose when user puts a cursor into text box everything gets wiped out but if he doesn't enter anything null values.
If you are using HTML5
use a placeholder
<input type="text" placeholder="Username">
If you can't use HTML5 this plugin may work for you
http://onwebdev.blogspot.co.uk/2011/11/jquery-emulating-placeholder-attribute.html
Edited Code to match what you needed:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<style type='text/css'>
input { color:#333; }
input:focus { color:#ccc;transition:color .2s linear 0;
-webkit-transition:color .2s linear 0;
-moz-transition:color .2s linear 0 }
input.typing { color:#333; }
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$("#submit").click(function (){
if($("#text").val()=="username")
{ $("#text").val("");}
});
$(function(){
var input = $('input[name="word"]'), defaulttext = input.attr('data-default');
input.val(input.attr('data-default'));
input.on('focus', function(){
if(input.val() != defaulttext)
input.addClass('typing');
else
input.removeClass('typing');
}).on('keydown', function(){
if(defaulttext == input.val()) input.val('');
input.addClass('typing');
}).on('blur', function(){
if(input.val() == '') input.val(defaulttext);
that.removeClass('typing');
});
});
});//]]>
</script>
</head>
<body >
<form method="get" action ="">
<input type="text" id="text" name="word" data-default="username"></font>
</br>
<input type="submit" value="SUBMIT" id="submit">
</form>
</body>
</html>
As this is just to increase UX, if your don't care about old browsers and your are just targeting new browsers use this HTML5 trick:
<INPUT type="text" size="25" placeholder="Username" />
replace above markup with your original input tag.
or use this instead of your form tag:
<FORM action="http://localhost:2013" method="post" onsubmit='if (document.getElementsByName ("username")[0].value == "Username") document.getElementsByName ("username")[0].value = ""'>
also add a name='username' in your username input tag!

Honeypot implementation

Trying to filter out spam from an online form. I have a hidden div with an input. The idea is that if something goes into the field, the form will ID the user as a bot and reject the submission. After trying to implement this method, the bots are still getting through. I'm not very familiar with javascript (or spam-filtration, for that matter) - here's what I'm working with:
html (within the form):
<form action="#" method='post' id='vsurvey' name='defer'>
<div id="hp-div">
If you see this, leave this form field blank
and invest in CSS support.
<input type="text" name="question_20579" value="" />
</div>
<input type="submit" value="Submit Request" />
</form>
css:
#hp-div { display: none }
js:
<script type="text/javascript" charset="ISO-8859-1" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" charset="ISO-8859-1" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
if(!String.IsNullOrEmpty(Request.Form["question_20579"]))
IgnoreComment();
</script>
<![if !IE]>
<script type="text/javascript">
$(document).ready(function(){
$("#vsurvey").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Oops! You missed 1 field. It has been highlighted'
: 'Oops! You missed ' + errors + ' fields. They have been highlighted below';
$("div.alert span").html(message);
$("div.alert").show();
} else {
$("div.alert").hide();
}
},
errorPlacement: function(error, element) {
return true;
}
})
});
</script>
<![endif]>
In my opinion, a honeypot should consist of ALL of the below:
A field hidden by CSS
A field hidden by JavaScript
A field requiring a blank input
A field requiring a specific input
For instance:
<div class="input-field">
Please leave this blank
<input type="text" name="contact" value="" />
</div>
<div class="text-field">
Please do not change this field
<input type="text" name="email" value="your#email.com" />
</div>
Using CSS, hide the first field:
.input-field { display: none; }
Using jQuery, hide the second field:
$('.text-field').hide();
// or
$('.text-field').addClass('hide');
Then a couple of very simple checks in PHP:
if($_POST['contact'] == '' && $_POST['email'] == 'your#email.com') {
// Not a bot
}

Form to jump to page

How can I make a form that allows users to enter a number and then goes to example.com/page/# where # is what the user typed in? I want this for a pagination "jump to" option.
I can only use HTML and JavaScript
<script type="text/javascript">
function goToPage(){
var page=document.getElementById('in').value; // value of input box
page=page*1; // ensures page is numeric only
location.href='http://www.example.com/page/'+page; // redirect to new url
}
</script>
<input type="text" id="in"/>
<input type="button" onclick="goToPage();"/>
<form id="jump" method="get" action="">
<input type="text" id="jump-page"/>
<input type="submit" value="Go"/>
</form>
<script type="text/javascript">
document.getElementById('jump').onsubmit= function() {
location.hash= document.getElementById('jump-page').value;
return false;
};
</script>
For page numbers you should probably prefix them like id="page-2" (to make a valid identifier) and then do location.hash= '#page-'+....

Categories

Resources