My knowledge on JavaScript is very limited and I need to implement this front end validation please.
So I am using Spring back-end and need to do some front end validation on a form input I have.
There will be 10 of these rows enclosed as Divs with the same input for each row.
eg. the inputs will be in this format
total[0]|qty[0]||qty[0]||qty[0]
total[1]|qty[1]||qty[1]||qty[1]
total[2]|qty[2]||qty[2]||qty[2]
etc...
total[10]|qty[10]||qty[10]||qty[10]
The user will first have the option to enter a total amount first.
The user has the option to enter inputs for qty of each row.
If the total of qty[0] are not equal to the total (total[0]) the user entered, the input box corresponding to that row will turn red(to inform the user they have inputted the wrong total).
eg qty[0] + qty[0] qty[0] != total[0] (BOX GOES RED FOR total[0])
qty[1] + qty[1] qty[1] = total[1] (NO CHANGE TO TOTAL BOX FOR total[1])
No other validation is needed apart from a visual one after the user keys in the last input for qty on that individual row.
Upon Clicking enter on the last input(qty[0] or qty[1] if the user is on the second row, or qty[10] if the user is on the last row) the validation will kick in and check is the box with id ="total[${status.index}]" = the three inputs with id = "qty[${status.index}]"
<!-- total -->
<div class="span1_5">
<form:input path="items[${status.index}].total" size="4"
id = "total[${status.index}]" />
</div>
<!--qtyDis-->
<div class="span1_5">
<form:input path="items[${status.index}].qtyDis"size="4"
onblur="findTotal()"
id ="qty[${status.index}]" />
</div>
<!--qtyAva-->
<div class="span1_5">
<form:input path="items[${status.index}].qtyAva"size="4"
onblur="findTotal()"
id ="qty[${status.index}]" />
</div>
<!--qtyDat-->
<div class="span1_5">
<form:input path="items[${status.index}].qtyDat"size="4"
onblur="findTotal()"
id ="qty[${status.index}]" />
</div>
I am very weak at Javascript and this is all I was able to come up with. I know it will be far of, but any help would be greatly appreciated.
<script type="text/javascript">
var index = 0;
function findTotal(){
var arr = document.getElementsByName('qty')[index];
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total')[index].value = tot;
<!-- if not equal, change the css backround of total[index] to red -->
index++;
}
</script>
Use this fiddle:
JS:
function findTotal($this) {
var cls = $($this).attr("class");
var index = cls.split('qty')[1];
var totalsum = 0;
$('.' + cls).each(function () {
if ($.isNumeric($(this).val())) {
totalsum += parseInt($(this).val());
}
});
if ($.isNumeric($(".total" + index).val())) {
if (totalsum != parseInt($(".total" + index).val())) {
$(".total" + index).addClass('error');
}
else {
$(".total" + index).removeClass('error');
}
}
}
HTML:
<div>
<div class="span1_5"><span>total1:</span><input type="text" class="total1" /></div>
<div class="span1_5"><span>qty1</span><input type="text" class="qty1" onblur="findTotal(this)" /></div>
<div class="span1_5"><span>qty1</span><input type="text" class="qty1" onblur="findTotal(this)" /></div>
<div class="span1_5"><span>qty1</span><input type="text" class="qty1" onblur="findTotal(this)" /></div>
</div>
<br /><br /><br />
<div>
<div class="span2_5"><span>total2:</span><input type="text" class="total2" /></div>
<div class="span2_5"><span>qty2</span><input type="text" class="qty2" onblur="findTotal(this)" /></div>
<div class="span2_5"><span>qty2</span><input type="text" class="qty2" onblur="findTotal(this)" /></div>
<div class="span2_5"><span>qty2</span><input type="text" class="qty2" onblur="findTotal(this)" /></div>
</div>
I would do something like this:
This is just to make you an idea of how could you do, don't copy/paste directly because maybe there is some typo. But the main steps are:
Add classes to each Quantity input so you can select them by row
Recover the total by row
Make a loop for all Quantities by Row and compare with total
In your HTML add classes to identify each element of any row
<div class="span1_5">
<form:input path="items[${status.index}].total" size="4"
class="total${status.index}"
id = "total[${status.index}]" />
</div>
<!--qtyDis-->
<div class="span1_5">
<form:input path="items[${status.index}].qtyDis"size="4"
onblur="findTotal()" class="qty${status.index}"
id ="qty[${status.index}]" />
</div>
<!--qtyAva-->
<div class="span1_5">
<form:input path="items[${status.index}].qtyAva"size="4"
onblur="findTotal()" class="qty${status.index}"
id ="qty[${status.index}]" />
</div>
<!--qtyDat-->
<div class="span1_5">
<form:input path="items[${status.index}].qtyDat"size="4"
onblur="findTotal()" class="qty${status.index}"
id ="qty[${status.index}]" />
</div>
Then in your JS
<script type="text/javascript">
var index = 0;
function findTotal(){
var quantity = document.getElementsByClassName('qty' + index);
var totQty=0;
for(var i=0;i<quantity.length;i++){
if(parseInt(quantity[i].value))
totQty += parseInt(quantity[i].value);
}
<!-- if not equal, change the css backround of total[index] to red -->
if(document.getElementById('total' + index).value != totQty){
$('.qty'+index).addClass("error");
}
index++;
}
</script>
Related
I am creating a lot of numbers inside of a div. Each time someone clicks a number I want to add it to another div. Let me make myself clear with some examples:
When a user clicks on the add class, the value of .addcop should be added to the value of .totalyHide. That means the value should change to 12.
When I click on the .add2 the value should be added on to 12, so the value of .totalyhide becomes 32.80.
and other terms, if I click the first + and click the second +, they should be added together on Yearly Price.
I hope you understand what I am trying to do.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totaly").val("$" + bigTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<div class="box box6">
<div class="titlet">work on it
<hr>
</div>
<div class="explain">to help you better</div>
<div class="money">
<p class="me">$12 Yearly</p><i class="add fas fa-plus-square fa-2x"></i></div>
<input type="text" name="content" class="addcop" style="display: none;" value="12">
</div>
<div class="box box5">
<div class="titlet">Procurement
<hr>
</div>
<div class="explain"></div>
<div class="money">
<p class="me">$20.80 Yearly</p><i class="add2 fas fa-plus-square fa-2x"></i></div>
<input type="text" class="procurement" style="display: none;" value="20.80">
</div>
<div class="box box8">
<div class="total">Your First Deposit will be: <input class="total1" type="button" value="$546"></div>
<input type="text" class="totalHide" style="display: none;" value="546">
<div class="total">Yearly Price: <input onchange="myFunction()" class="totaly" type="button" value="$0"></div>
<input type="text" class="totalyHide" style="display: none;" value="0">
<div class="total">On-off Price: <input class="total" type="button" value="$546"></div>
<input type="text" class="total" style="display: none;" value="546">
</div>
There is a minor issue with the JQuery code that you have written. You can add the following changes to get the desired result.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
The thing to note here is that whenever you are calculating the total,
you'll have to set that total to $(".totalyHide"), so that you can read the updated value upon next click.
I am trying to loop through the form which has label inside random elements and check if the label matches with the given label name and if matches, I am adding a class to that element. But I am not able get it working, how can I do this?
Here's what I have tried.
Form which has labels inside random elements like div
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>
Jquery code:
$("#grtform").each(function(){
var matchLable = "Currency due"
var lable = $(this).find('label').text();
if(matchLable == lable){
$(this).addClass('matchFound');
}
});
You need loop through lables, not against form
$("#grtform lable").each(function(){ // selecting all labels of form
var matchLable = "Currency type"
var lable = $(this).text(); // changed here too
if(matchLable == lable){
$(this).addClass('matchFound');
}
});
In above code, this refers to currently iterating label.
After trimming a bit
$("#grtform lable").each(function(){ // selecting all labels of form
if($(this).text() == "Currency type"){
$(this).addClass('matchFound');
}
});
You can also use following way :-
var allLables = document.querySelectorAll("#grtform lable");
for(var i = 0; i < allLables.length; i++){
var matchLable = "Currency type";
var lable = allLables[i].innerText; // changed here too
if(matchLable == lable){
allLables[i].classList.add("matchFound");
}
}
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>
I have a php loop that call products from database. there is a quantity input field and a ajax add to cart button.
Now ajax add cart function get product id and quantity from the add cart link data attribute. So I want that when I change the quantity field value the add cart link data-quantity will changed automatically. So I can add sent the product quantity to cart.
I tried to do this but unfortunately its change all products quantity on click, because of same class. there is any why to do this that only change the quantity where I clicked?
maybe product id class work here? but how I set a dynamic product id in jquery?
here is my code:
HTML
<div class="row">
<div class="col-md-4">
<img src="img1.jpg" /><br />
<h2>Product 1</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img2.jpg" /><br />
<h2>Product 2</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img3.jpg" /><br />
<h2>Product 3</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
<div class="col-md-4">
<img src="img4.jpg" /><br />
<h2>Product 4</h2>
<button class="button">+</button>
<button class="button">-</button>
<input type="number" class="input" value="1" min="1" />
Add to Cart
</div>
</div>
Jquery
<script>
$(function() {
$(".button").on("click", function() {
var $button = $(this);
var oldValue = $('.input').val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$('a.add-to-cart').attr('data-quantity', newVal);
$('.input').val(newVal);
});
});
</script>
CodePen: https://codepen.io/alshedupur/pen/KmMxJv
Please don't push minus before give me a solution. Maybe you know this, but I don't know. If you share your knowledge it will help me and maybe others too.
You use selector that matches all inputs as they share the class, you can either push an unique id per item or you can use selector to find only items within the same container.
E.g.
$(function() {
$(".button").on("click", function() {
var $button = $(this);
var $parent = $button.parent();
var oldValue = $parent.find('.input').val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$parent.find('a.add-to-cart').attr('data-quantity', newVal);
$parent.find('.input').val(newVal);
});
});
i have a single page which is divided into two sections.So at first first section is seen and we need to fill the inputs value and when we click go to next page button then the first section is now hidden and second section is shown.Then only we can submit the form.
Now what i want is that in the first section, i have four inputs like shown below
<div class="room_details_first col-md-12" id="first_order">
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]"/>
</div>
</div>
Now by using jquery i have append the inputs and the code is shown below
function add_others_order(){
var output="";
output+= '<div class="room_details_first col-md-12" id="first_order">';
output+='<div class="col-md-3"><input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/></div>';
output+='<div class="col-md-3"> <input type="text" placeholder="Hotel Name" name="others_hotel[]"/> </div>';
output+='<div class="col-md-3"><input type="text" placeholder="Hotel price" name="others_hotel_price[]"/></div>';
output+='<div class="col-md-2"> <input type="text" placeholder="Customer Price" name="others_client_price[]"/></div>';
output+='<div class="col-md-1" ><i class="fa fa-remove"></i></div>';
output+='</div>';
$('#first_order').after(output);
}
now what i need is i need to save the inputs value before submitting and list it in second section of the page.i have tried to do it but i am failed many times. And i have also found similar answers which is given below
Display the data entered in a form before submitting the form
Guys i need help.
Here is what you want, you will get all input's value and you can do
what ever you want with it.
function nextStep() {
var allFields = document.getElementsByTagName("input");
//console.log(allFields);
for (var index in allFields) {
console.log('name : '+allFields[index].name);
if (allFields[index].type == "text") { // you can change condition by name instead of type
if (allFields.hasOwnProperty(index)) {
var attr = allFields[index];
console.log(attr.value)
}
}
}
}
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]" />
</div>
<input type="button" onclick="nextStep()" value="Next step">
I think this is what you want, or as close to what you need, I add an Id attribute so you can do add/remove:
var stored_data = [];
stored_data.total = 0;
$('#dummy').on('click', function(){
var obj = {
id: stored_data.length,
food: food.value,
hotel_name: hotel_name.value,
hotel_price: hotel_price.value,
customer_price: customer_price.value
};
stored_data.push(obj);
stored_data.total += parseInt(obj.customer_price);
//$('#first_section').hide();
var output = '<div class="room_details_first col-md-12" id="first_order">';
output += '<div>Order ' + obj.id + '</div>';
output += '<div class="col-md-3">Food: ' + obj.food + '</div>';
output += '<div class="col-md-3">Hotel Name: ' + obj.hotel_name + '</div>';
output += '<div class="col-md-3">Hotel Price' + obj.hotel_price + '</div>';
output += '<div class="col-md-2">Customer Price' + obj.customer_price + '</div>';
output += '<div class="col-md-1" ><i class="fa fa-remove"></i></div> ';
$('#new_section').append(output);
$('#total').text(stored_data.total);
});
https://jsfiddle.net/5uka65tx/2/
Here's a way to do it by using clone() on the whole first order and do some modifications to add the link and change duplicate ID and last item column class.
First use serializeArray() to get the values to store
var values = $('#first_order :input').serializeArray();
console.log(values);
then clone , modify and insert
var link = '<div class="col-md-1" ><i class="fa fa-remove"></i>LINK</div>';
// clone first order and update ID
var $first = $('#first_order').clone().attr('id', 'first-order_2');
// modify column on last one and add the link
$first.children(':last').toggleClass('col-md-2 col-md-3').after(link);
// insert in second position
$('#second').append($first)
DEMO
By taking reference of Jigar7521, i tried to do the following way
var allFields = document.getElementsByClassName("others_order");
var others_total_price='0';
var others_food_items=new Array();
var others_hotel_name=new Array();
var others_hotel_price=new Array();
var others_client_price=new Array();
//var others['food_items'] = new Array();
var ficounter=0;
var hcounter=0;
var hpcounter=0;
var cpcounter=0;
Array.prototype.forEach.call(allFields, function(el) {
if(el.name=='others_client_price[]'){
others_client_price[cpcounter]=el.value;
cpcounter++;
others_total_price=parseFloat(others_total_price)+parseFloat(el.value);
}
if(el.name=='others_food_items[]'){
others_food_items[ficounter]=el.value;
ficounter++;
}
if(el.name=='others_hotel[]'){
others_hotel_name[hcounter]=el.value;
hcounter++;
}
if(el.name=='others_hotel_price[]'){
others_hotel_price[hpcounter]=el.value;
hcounter++;
}
});
$('#others_total_price').val(others_total_price);
var others_output="<h4>Others Order</h4>";
for(var i=0;i<=ficounter;i++){
others_output+='<div ><div class="col-md-12"><div class="col-md-3">'+others_food_items[i]+'</div><div class="col-md-3">'+others_hotel_name[i]+'</div><div class="col-md-3">'+others_hotel_price[i]+'</div><div class="col-md-3"> '+others_client_price[i]+'</div></div></div>';
}
$('#others_id').html(others_output);
it worked but i get errors like undefined
i tried to console.log every array and i got what i did not have expected
hello i am using a form to add experience to users where i have a add more button which adds more (clones) the content and users get one more field to add experience
i am using this code to achieve this
<div id="append_palllsjjs"><div class="full_exp_9092k" id='duplicater'>
<div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Company Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="comp[]" required placeholder="company Name" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Department Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="dept[]" required placeholder="Department Name" class='cname_990s_EXp'/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
From Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2011" data-initial-month="9" class='TEx_About_allihh' name="exsdate[]" required/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
To Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2012" data-initial-month="10" class='TEx_About_allihh' name="exedate[]" required/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Profile <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="profile[]" required placeholder="Profile" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
</div>
<input type="button" name="addmore" value="Add More" class='button small white' onclick='duplicate();'/>
</div>
</div>
</div></div>
js
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicetor" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
here i want the new fields when added should be empty (right now it is showing the same content with pre filled values in textbox )
second issue is i want to insert the data in table for each value of the array i know this can be donr by foreach loop
PHP
$comps=$_POST['comp'];
$profile=$_POST['profile'];
$exedate=$_POST['exedate'];
$exsdate=$_POST['exsdate'];
$dept=$_POST['dept'];
if(empty($comps) || empty($profile) || empty($exedate) || empty($exsdate) || empty($dept) ){
echo 'Please Fill all the fields marked with *';die;
}
foreach($comps as $value){
// insert into tablename (field1,field2,field3,...) values ('comp1','dep1','profile1'....)
// insert as many feilds as the no of elements in the array
}
please suggest me with this php code how to use the foreach loop so that i can insert as many rows as the no of elements in the array with corrosponging values in another array
pleaes note that this question has two questions written please feel free to help for any of the question.
one is wth php and anothr with ajax
Use following code to clear Cloned form :
NOTE : Must add jquery file in document
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
</script>
Here is code with your new requirement :
To Add remove button if user want to remove form block section user
can easily :
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
addButton(clone.id,i);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
function addButton(id,ii){
var divId = '#'+id;
$(divId).append('<input type="button" value="Remove" class="button small white" id="'+ii+'" onclick="rBlock('+ii+')" />');
}
function rBlock(ii){
$('#'+ii).on('click', function(e){
var parentDiv = $(this).parent();
if(parentDiv.attr('id') !== ii){
parentDiv.remove();
}
});
$('#'+ii).trigger( "click" );
}
</script>