Jquery validation - field focus - javascript

I have a form with list of input fields to be filled in.The values entered will be validated against the min and max criteria.If the entered value doesn't fall into the criteria , users need to be triggered to enter the reason followed by entering the after weight.
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" value="" maxlength="255" size="25">
</c:forEach>
So once the initalWeight is entered , onchange event will be triggered to check whether the value is with in the min and max value.If it doesn't fall in to the criteria ,users will be alerted to enter reason and the screen focus should be on the reason field.
function checkOnChange(name, id, min, max)
{
var check = true;
var originalValue = '';
var minimum = eval(min);
var maximum = eval(max);
var nameVal = eval(name.value);
if (nameVal > maxVal)
{
alert(id + ' Enter the reason before proceeding');
return false;
}
if (itemVal < minVal)
{
alert(id + ' Enter the reason before proceeding');
return false;
}
}
JSFiddle link : http://jsfiddle.net/jegadeesb/ehehjxbp/
Is there a better way to achieve this .Kindly share your suggestions.
Thanks for your valuable suggestions and time

Add the reason field an ID and the set focus on it using the focus method
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="number" class="required" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value="${Item.personId}"/>','<c:out value="${Item.minWeight}"/>','<c:out value="${Item.maxWeight}"/>')">
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" id="reason" value="" maxlength="255" size="25">
</c:forEach>
function checkOnChange(name, id, min, max)
{
var check = true;
var originalValue = '';
var minimum = eval(min);
var maximum = eval(max);
var nameVal = eval(name.value);
if (nameVal > maxVal)
{
alert(id + ' Enter the reason before proceeding');
document.getElementById("reason").focus();
return false;
}
if (itemVal < minVal)
{
alert(id + ' Enter the reason before proceeding');
document.getElementById("reason").focus();
return false;
}
}

Related

(Javascript) oninput with numbercheck

I'm trying to make a simple inventory systems. But I'm having problem with my oninput event.
I want to make TOTAL GOODS to be "Please input number in GOODS IN " whenever every non number value inserted into GOODS IN. But it seems I can't make it so.
/*MAKE EVERY TABLE CLICKABLE AND SHOW ROW DATA IN INPUT TEXT*/
var tbGoods = document.getElementById('tbGoods');
for (var i = 0; i < tbGoods.rows.length; i++) {
tbGoods.rows[i].onclick = function() {
document.getElementById("idTxt").value = this.cells[1].innerHTML;
document.getElementById("gdTxt").value = this.cells[2].innerHTML;
document.getElementById("qtyTXT").value = this.cells[3].innerHTML;
var qty = parseInt(document.getElementById('qtyTXT').value);
var x = parseInt(document.getElementById('gdin').value);
var result = qty - x;
document.getElementById('totalgd').value = result;
};
}
/*MAKE EVERY NUMBER I PUT IN GOODS IN, TO BE CALCULATED WITHOUT SUBMIT BUTTON (ONINPUT)*/
function testmin() {
var qty = parseInt(document.getElementById('qtyTXT').value);
var x = parseInt(document.getElementById('gdin').value);
var result = qty - x;
if (document.getElementById('gdin').value === '') {
document.getElementById('totalgd').value = '0';
} else if (document.getElementById('qtyTXT').value === '') {
document.getElementById('totalgd').value = '0';
} else if (Number.isNaN(document.getElementById('gdin').value)) {
document.getElementById('totalgd').value = 'Please Input Number in Goods In';
} else {
document.getElementById('totalgd').value = result;
}
}
<form method="post">
<label>ID</label>
<input type="text" name="id" id="idTxt" disabled>
<label>GOODS</label>
<input type="text" name="goods" id="gdTxt" disabled>
<label>AVAILABLE QTY</label>
<input type="text" name="qty" id="qtyTXT" disabled>
<label>GOODS IN</label>
<input type="text" name="gdin" id="gdin" oninput="testmin()">
<br>
<br>
<label>Total Goods</label>
<input type="text" name="totalgd" id="totalgd" value="0" disabled>
<br>
<input type="submit" name="submit" value="submit">
</form>
You don't need to code that manually. You can simply set the input type as "number" and your browser will not allow any non-numeric characters to be entered into the field.
Demo (run the snippet and try typing in the box):
<input type="number" id="gdin" name="gdin"/>
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number
Just add type = "number" in the input label for TOTAL GOODS. It should prevent user from entering any alphabet. Except "e"
<input type="number" name="totalgd" id="totalgd" value="0" disabled>
As pointed out, if you want to show an alert or something when an input of alphabet is there in TOTAL GOODS, you can just add
<input type="text" name="totalgd" id="totalgd" value="0" oninput = "checkFunction()" disabled>
and in the function you can check the input for :
function checkFunction() {
let totalGoodsIn = document.getElementById("totalgd").value;
let regExp = /[a-zA-Z]/g;
if(regExp.test(totalGoodsIn))
{
//logic if alphabet is present in TOTAL GOODS
}
else
{
//logic if alphabet is not present in TOTAL GOODS
}
}
if you want GOODS IN to be numeric just change the type of the label accordingly
function validateNumberField() {
var value = $("#numberField").val();
var pattern = /^\d+$/;
var isValid = pattern.test(value);
if(!isValid){
document.getElementById('totalgd').value = 'Please Input Number in Goods In';
}
}
<p>Please enter number :</p>
<input type="number" id="numberField" name="numberField"
oninput="validateNumberField()" />

how to stop the code for the user to enter the following value in input

I do some calculator and want user take turns input first and second value. I need stop program when user enter first value and continue when user enter second value in the same input field. User continues by pressing the "=" button in html code or "Enter".
$('#plus').on('click', function(){
var firstNum = $("#txt").val()
$("input").val('')
if (isResult === true || $("input").keypress() === 13){
var secondNum = $("#txt").val()
result = Number(firstNum)+Number(secondNum)
console.log(result)
}
<input type='text' id='txt' value='' onpaste="return false" placeholder="Enter number" />
JavaScript programs don't stop to wait for the user, they react to events that are triggered asynchronously by the user.
You can save the state of the program in a global variable between calls to the event handler.
var firstNum;
$('#plus').on('click', function() {
if (firstNum === undefined) {
firstNum = Number($("#txt").val());
} else {
var secondNum = Number($("#txt").val());
var result = firstNum + secondNum;
console.log(result);
}
$("#txt").val('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='txt' value='' onpaste="return false" placeholder="Enter number" />
<button type="button" id="plus">+</button>
You can keep the second input element(and equal button) hidden when the page loads and then show the input(and equal button) when the operator is clicked by the user to make it more interactive.
You can get more information about toggling between hiding and showing an element on this astonishing website: https://www.w3schools.com/howto/howto_js_toggle_hide_show.asp
var firstNum;
var secondNum;
var first_in = document.getElementById("txt1");
var sec_in = document.getElementById("txt2");
var equal = document.getElementById("equals");
sec_in.style.display = "none";
equal.style.display = "none";
$('#plus').on('click', function() {
if (firstNum === undefined) {
firstNum = Number($("#txt1").val());
sec_in.style.display = "block";
equal.style.display = "block";
}
});
$('#equals').on('click', function() {
if (secondNum === undefined) {
secondNum = Number($("#txt2").val());
var result = firstNum + secondNum;
console.log(result);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='txt1' value='' onpaste="return false" placeholder="Enter first number" />
<button type="button" id="plus">+</button>
<input type='text' id='txt2' value='' onpaste="return false" placeholder="Enter second number" />
<button type="button" id="equals">=</button>

Populate the grand total value base on value of each input fields

I would like to calculate and populate the grand total automatically before submiting the form. The grand total will base on my 5 input fields.
<input type="number" name="inspection_fee">
<input type="number" name="storage_fee">
<input type="number" name="local_fee">
<input type="number" name="cert_fee">
<input type="number" name="others_fee">
<input type="number" name="total_fee">
I know how to do it the php way like it would put variables after I submit it then calculate it totally like this.
<?php
$inspection_fee = $paymentSettings->inspection_fee;
$storage_fee = $paymentSettings->storage_fee;
$cert_fee = $paymentSettings->cert_fee;
$local_fee = $paymentSettings->local_fee;
$others_fee = $paymentSettings->others_fee;
$total_fee = $inspection_fee + $storage_fee + $cert_fee + $local_fee + $others_fee;
?>
But how would I populate the total before submiting it using javascript? Like if I change the inspection fee the total fee will auto adjust depends on the total value.
Looking for help.
Thanks in advance.
Set the total input field to read-only
Create a function to add up all the inputs and set the value in total_fee (good opportunity to use Array.prototype.reduce)
Bind your function to the inputs input event
const inputs = ['inspection_fee', 'storage_fee', 'local_fee', 'cert_fee', 'others_fee']
const total = document.querySelector('input[name="total_fee"]')
const sumTotal = () => {
total.value = inputs.reduce((sum, input) =>
sum += parseInt(document.querySelector(`input[name="${input}"]`).value || 0, 10), 0)
}
inputs.forEach(input => {
document.querySelector(`input[name="${input}"]`).addEventListener('input', sumTotal, false)
})
<input type="number" name="inspection_fee">
<input type="number" name="storage_fee">
<input type="number" name="local_fee">
<input type="number" name="cert_fee">
<input type="number" name="others_fee">
<input type="number" name="total_fee" readonly>
Attach onblur event to all input fields to call a JavaScript function. I have changed the "name" attribute to "id" attribute to be used in the JS function.
<input type="number" id="inspection_fee" onblur="calculateTotalFee();">
<input type="number" id="storage_fee" onblur="calculateTotalFee();">
<input type="number" id="local_fee" onblur="calculateTotalFee();">
<input type="number" id="cert_fee" onblur="calculateTotalFee();">
<input type="number" id="others_fee" onblur="calculateTotalFee();">
<br/>
<input type="number" id="total_fee">
<script type="text/javascript">
function calculateTotalFee(){
var totalFee = 0;
var inspectionFee = document.getElementById("inspection_fee").value.trim() === "" ? 0 :
document.getElementById("inspection_fee").value.trim();
var storageFee = document.getElementById("storage_fee").value.trim() === "" ? 0 :
document.getElementById("storage_fee").value.trim();
var localFee = document.getElementById("local_fee").value.trim() === "" ? 0 :
document.getElementById("local_fee").value.trim();
var certFee = document.getElementById("cert_fee").value.trim() === "" ? 0 :
document.getElementById("cert_fee").value.trim();
var othersFee = document.getElementById("others_fee").value.trim() === "" ? 0 :
document.getElementById("others_fee").value.trim();
totalFee = parseInt(inspectionFee) + parseInt(storageFee) +
parseInt(storageFee) + parseInt(localFee) + parseInt(certFee) + parseInt(othersFee);
document.getElementById("total_fee").value = totalFee;
}
</script>

Disabling a array of textbox when any one textbox have a value

how can i disable all textbox if any one of textbox have a value?? I have array of cost_type and its cost, if any of the cost enterd.. all the other textboxes for cost_type should be disable.if no cost entered.. all text field should be editable. I already try this code but its not working.
function stoppedTyping(iVal){
var costs=document.getElementsByName("cost")[iVal].value;
if(costs > 0) {
document.getElementById("cost_" + iVal).disabled=true;
} else {
document.getElementById("cost_" + iVal).disabled=false;
}
}
<td colspan="4">
<input type="text" size="10" maxlength="8" name="cost" id="cost_<c:out value="${y}"/>" value="<c:out value="${costDto.cost}"/>"
onBlur=" stoppedTyping(<c:out value="${y}"/>)"; "/>
</td>
Try checking the length of the value:
var costs = document.getElementsByName("cost")[iVal].value;
if(costs.length > 0) {
}
or a little more compact:
var costs = document.getElementsByName("cost")[iVal].value;
document.getElementById("cost_" + iVal).disabled = costs.length > 0;
Add this to your script.
$('.enableToggle').on('keyup paste', function(){
var curVal = $(this).val().replace(/\s+/g,'').length > 0;
$(this).siblings('.enableToggle').prop('disabled', curVal);
});
and add class="enableToggle" to all your input fields.

jquery Datepicker date range validation

I have a field like Born date. I have used jquery datepicker to show the calender so that user can select the date.Now I have a problem.
In the the Born date field there is a option to choose between which opens two date picker fields like
Born Date -- Between--------- ---From------- And --To----------
Now the problem is if the user selects a date in 'To field' which is less than 'From field' and press the submit button it gets submitted. I need to prevent it from submitting and display appropriate message so the user enters right date .
Please Help.
Here is the code that i am using
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</input>
<span id="span_borndate" style="display:none">
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</span>
This is the Java script i am using
function checkdate(fieldname) {
var comparator = '#comp_' + fieldName;
var compVal = $(comparator).val();
Value = $('#' + fieldName).val();
var fromDate = jQuery.datepicker.parseDate('mm-dd-yy', Value, null);
Values = $('#' + fieldName + '-to').val();
var toDate = jQuery.datepicker.parseDate('mm-dd-yy', Values, null);
$('#span_' + fieldName).find('.error').remove();
if (compVal == "Between") {
if (toDate < fromDate) {
$('#span_' + fieldName).append("<label class='rangeError' generated='false'>Start date should come before end date</label>");
return false;
}
}
return true;
}
And this is the function which is called again while submitting
function validateforms() {
var valid = true;
$('//classnamefor table rows which includes the date td').each(function (index) {
fieldName = $(this).attr("name");
if ($('#' + fieldName).hasClass('dateISO')) {
valid = checkDate(fieldName);
}
}
return valid;
}
Try this
http://jqueryui.com/demos/datepicker/#date-range
and make the textboxes readonly='true'
<input type="text" id="from" name="from_date" value="" readonly="true"/>
<input type="text" id="to" name="to_date" value="" readonly="true"/>

Categories