Validation error message for each textbox - javascript

What I have here is validation for comparing textbox values. I have quantity textbox and a hidden textbox, If quantity textbox is lower than the hidden textbox error message will display in span. But the problem is even in other span that has a correct value error message always appears.
Just like the picture below if quantity is less than the hidden textbox error message display but on the other textbox which is has a correct value error message is still display. Help?
$('.n_quantity,.pr_total').each(function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0, len = textBox1.length; i < len; i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_over").html("Over").addClass('validate');
validation_holder = 1;
return false;
}
}
});
<p>
<label for="">PR Quantity</label>
<input name="n_quantity[]" id="n_quantity" class="qty tb1 n_quantity" type="text" value="<?php echo $row['total_quantity'] ?>" />
<span class="val_qty val_over"></span>
</p>
<p style="display:none;">
<input id="pr_total" class="tb2 pr_total" type="text" value="<?php echo $row['total_quantity'];?>" readonly="readonly">
</p>

You could iterate the editable fields, then traverse the dom to the related elements:
$('.n_quantity').each(function () {
var $this = $(this);
var $total = $this.closest('p').next().find('.pr_total');
if (parseInt($this.val(), 10) > parseInt($total.val(), 10)) {
$this.siblings('.val_over').html('Over').addClass('validate');
validation_holder = 1;
}
});

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()" />

Automatic array in PHP

How about, make this example, where we put an initial number and final number.
Example We insert the Initial and Final Number:
Initial Number = 1 Final Number = 4
Result = 1 2 3 4
The result is thrown when we press the SEND button.
What I want is that I throw my result without having to press the SEND button.
That the FOR cycle is performed and I throw the result without pressing the button.
That the result is automatic.
CODE:
<form action="" method="post">
<input type="text" name="inivalue" id="inivalue" placeholder="initial value"/>
<input type="text" name="finvalue" id="finvalue" placeholder="final value"/>
<input type="submit" name="submit" vale="submit" />
</form>
<?php
if(isset($_POST['submit']))
{
$num = (int)$_POST['inivalue'];
$numfin = (int)$_POST['finvalue'];
for($num=$num; $num <= $numfin; $num++)
{
echo $num;
}
}
?>
// Get your input elements using getElementById()
const initialValue = document.getElementById("inivalue");
const finalValue = document.getElementById("finvalue");
const result = document.getElementById("result");
let initialVal = "";
let finalVal = "";
// Every time you change the value in your <input> element
// save that value into the initialVal, finalVal variables.
initialValue.addEventListener("change", function(){
initialVal = this.value;
autoArray(initialVal,finalVal);
});
finalValue.addEventListener("change", function(){
finalVal= this.value;
autoArray(initialVal,finalVal);
});
// Loop using initialVal and finalVal
function autoArray(ini,fin){
numArray = [];
if (ini!= "" && fin != "") {
for(i = ini; i <= fin; i++){
numArray.push(i);
}
}
// Change the value of the result <input> element
result.value = numArray;
}
<input type="text" name="inivalue" id="inivalue" placeholder="initial value"/>
<input type="text" name="finvalue" id="finvalue" placeholder="final value"/>
<input type="text" id="result"/>
One way this can be done is using the onChange event.
set it in your final number field:
<input onchange = "rangefinder()" type="text" name="finvalue" id="finvalue" placeholder="final value"/>
then in your javascript function rangefinder():
function rangefinder(){
//get the value of both the invalue and finalvalue fields
//make sure they're both integers - just return if they're not.
//use a for loop to make a string of numbers from invalue to finalvalue
//insert this string where ever you want it.
}
I'll leave the actual JS up to you.

showing the length of a input

How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.

Create dynamic text boxes then write to text file

So there must be an easier way to create this. I have a form with the following HTML:
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then added some JS to create new text boxes if a user needs to add more names:
Taken from: http://www.sanwebcorner.com/2017/02/dynamically-generate-form-fields-using.html
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
function check() {
var temp = document.getElementsByClassName("formElem");
if (document.getElementById("ckbox").checked) {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = false;
}
} else {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = true;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then need to write those appended values to a .CSV file using PHP and here is where I am having the issue:
<?php
// Receive form Post data and Saving it in variables
header('Location: thanks.html');
$Name = "";
$Name = #$_POST ['Name'];
// Write the name of text file where data will be store
$filename = "file.csv";
// Merge all the variables with text in a single variable.
$f_data= '
Names for people: '.$Name.' ';
$file = fopen($filename, "r+");
fwrite($file,$f_data);
fclose($file);
?>
What happens is that the last appended text box gets written into the csv file.Is there a way to pass these created text boxes so they can write to a the file? Really similar question: Pass dynamic text input to PHP in order to write to text file
But I'm not sure if this can be done with text boxes.
The problem is that every input you add has the name “name”, so PHP can only access the last one (which overwrote the others). To get around this, you can add an index to the input name or make an array of them. This can be achieved like so:
<input type="text" name="name[]"...>
So now, on the PHP script you can iterate over that array to get all the inputs, or implode all the elements into a variable:
<?php
$names = implode(", ", $_POST["name"]); // all the names, comma-separated
?>
Now you can use $names inside $f_data to see all the inputted fields.
(Thanks Fred-ii for the heads up about the quotes)

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.

Categories