Check if input field value has changed on button click - javascript

I need to check if a value has changed on an input field before submitting a form. This is the code I have so far:
JS
$(document).ready(function(){
$('#submitButton').click(function() {
if( $('input[name="inputToBeChecked"]').val() != 'Original input field value' {
alert("Input field has changed!");
} else {
alert("Input field has not changed!");
}
});
});
HTML
<form>
<input type="text" name="inputToBeChecked" id="inputToBeChecked" value="Original input field value">
<a id="submitButton" type="button" class="btn" href="javascript:void(0);">Submit form</a>
</form>

Just set a flag once the input has been changed
var flag = 0;
$('input[name="inputToBeChecked"]').change(function(){
flag = 1;
});
$('#submitButton').click(function() {
if(flag == 1){
//yeah!
}
});
There can be also another case, if it gets changed and then returns to initial state. Then you could just save the initial value instead.
var initialVal;
$(document).ready(function(){
initialVal = $('input[name="inputToBeChecked"]').val();
});
$('#submitButton').click(function() {
if($('input[name="inputToBeChecked"]').val() != initialVal){
// initial value changed
} else {
// initial value either unchanged or changed and later reversed to initial state
}
});

Related

check input field value on enter press against js object value

My input field <input type="text" id="barcode" placeholder="Barcode"
onkeypress="search(this)">
and I want to check it's value by pressing enter against a value in my js object.
function search(ele) {
if(event.key === 'Enter') {
// element.anr is the value i want to check my input against
if (ele.value === element.anr) {
// action that should be performed if value is equal
document.getElementById("next").click();
}
}
};
What am I doing wrong here? Nothing happens when I put the correct value and hit enter (sidenote the document.getElementById("next").click(); is showing me the next key and its values of my js object)
just tested element.anr as 123 and tried, its working fine
function search(ele) {
if(event.key === 'Enter') {
var anr="123"
// element.anr is the value i want to check my input against
if (ele.value == anr) {
// action that should be performed if value is equal
console.log(ele.value+" - "+anr);
document.getElementById("next").click();
}
}
}
function printHi()
{
console.log("HAIIIII")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="barcode" placeholder="Barcode"
onkeypress="search(this)">
<button id="next" onclick="printHi();">test</button>
You can use an eventListeners,
const node = document.getElementsById("barcode");
node.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
// Do more work
}
});

Validating a form to not submit on empty input boxes

// html
<label>Write Data:</label>
</br>
<input type=text id=data name="data"style="width: 14em;">
</br>
</br>
<button id="write" type="submit" formaction="/output4" formmethod="post" style="width: 5em;">Write</button>
<button id="More" type="submit">Add more Parameters</button>
// js
$('#write').click(function(){
$('#data').each(function() {
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
return false;
}
});
});
I have a program where if a user clicks on a button, more write data boxes are appended. I do not want the form to submit unless all the write data boxes are filled out. The snippet above shows the alert box if an input if incomplete but then when you press ok, the form still submits?
You can use the .submit() event handler. Then use either return false or e.preventDefault() to stop the submit. Also note that id's are unique so $('#data') will only be a single element, so the .each() isn't needed:
$('#formIDHere').submit(function(e){
if ($('#data').val() == "" || $('#data').val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // or `return false`
}
});
For many inputs have your input items be a class with the value class="data". Just note you need to to use e.preventDefault() using the e from the submit event. In this case return false is for the .each() and not the submit. I use it here to stop the .each from going so we don't have many unneeded alerts and checks:
$('#myForm').submit(function(e){
$('.data').each(function(){
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // This is the preventDefault of submit
return false; // This stops the .each from continuing
}
});
});
Demo
$('#write').click(() => {
// if any one of the inputs is blank canSubmit will end up as false
// if all are not blank, it will end up as true
var canSubmit = [...document.querySelectorAll('input')]
.reduce((acc, input) => acc = input.value === '' ? false : acc , true)
});
<script type="text/javascript">
$(function () {
$("#data").bind("change keyup", function () {
if ($("#data").val() != "")
$(this).closest("form").find(":submit").removeAttr("disabled");
else
$(this).closest("form").find(":submit").attr("disabled", "disabled");
})
});
</script>
This would allow you to disable your submit button until there was data within the input field.

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

Disable form button unless all text input fields are filled in

I have a form that has multiple text inputs, I don't want to add id to each one as they are generated from server side code - number of fields may differ etc. I just want to be able to disable the submit button until there is text entered into each text input.
I have gotten this far, but only disables button until text entered in to one text input field - I want it to stay disabled until text entered in to all text inputs.
<script>
$(function () {
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
$('#button').prop('disabled', this.value == "" ? true : false);
})
});
</script>
I have also tried $('input:text').each().keyup(function (){ - but does not make button clickable?
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
var disable = false;
$('input:text').each(function(){
if($(this).val()==""){
disable = true;
}
});
$('#button').prop('disabled', disable);
});
Demo
The callback function for keyup now checks only that specific input field's value (this.value). Instead, this needs to loop through all input fields that need to be filled, and only when all have text do you change the the .prop value.
$('input:text').keyup(function () {
$('#button').prop('disabled', allFieldsAreFilled());
});
function allFieldsAreFilled() {
var allFilled = true;
// check all input text fields
$("#yourForm input:text"]).each(function () {
// if one of them is emptyish allFilled is no longer true
if ($(this).val() == "") {
allFilled = false;
}
});
return allFilled;
}
Try this:
$(function() {
var bool = true, flag = false;
$('#button').prop('disabled', bool); // use prop to disable the button
$(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs
$('input:text').each(function() { // loop through each text inputs
bool = $.trim(this.value) === "" ? true : false; // update the var bool with boolean values
if(bool)
return flag;
});
$('#button').prop('disabled', bool); // and apply the boolean here to enable
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='button' id='button' value='button' />

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Categories

Resources