Why my javascript code is not working as expected - javascript

I am trying to validate a text field using JavaScript. I have an available field and a quantity field. I want to give a message below the quantity field when the quantity entered is greater than available.
What I have tried is:
<form method="post" action="/saveBid" id="reviewForm">
<input type="hidden" name="_token" value="{{csrf_token()}}" />
<input type="hidden" name="truck_name" value="{{truck_name}}" />
<input type="hidden" name="user_name" value="{{auth_user().first_name}}" />
<input type="hidden" name="seller_id" value="{{seller_id}}" />
<div class="form-group row">
<label class="col-sm-4 col-form-label">Select Milege Gap: </label>
<div class="col-sm-8">
<select class="form-select" name="mileage" id="mileage" onchange="getOption()">
<option>Select </option>
{% for p in product_data %}
<option value="{{p.price}},{{p.number_of_products}},{{p.name}},{{p.id}},{{p.number_of_products_sold}}">{{p.name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group row">
<label for="available" class="col-sm-4 col-form-label">Available Quantity: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="available" readonly name="available_qty" />
</div>
</div>
<div class="form-group row">
<label for="truck" class="col-sm-4 col-form-label">Price: </label>
<div class="col-sm-8">
<input type="text" class="form-control" readonly id="truck" name="truck" />
</div>
</div>
<div class="form-group row">
<label for="qty" class="col-sm-4 col-form-label"> Quantity: </label>
<div class="col-sm-8">
<input type="text" id="qty" name="qty" class="form-control" oninput="checkInput(this);" required />
<p id="qty-msg">
</p>
</div>
</div>
<div class="form-group row">
<label for="t_price" class="col-sm-4 col-form-label"> Total Price: </label>
<div class="col-sm-8">
<input type="text" readonly id="t_price" name="t_price" class="form-control" />
</div>
</div>
<div class="form-group row">
<label for="inputBid" class="col-sm-4 col-form-label">Enter Bid Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputBid" name="bid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"/>
</div>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" id="btn" name="send" value="Send" disabled="disabled">
</div>
</form>
Javascript code:
<script>
function getOption()
{
var select = document.getElementById('mileage');
var option = select.options[select.selectedIndex];
var opArr = option.value.split(",");
var price=document.getElementById("truck");
price.value=opArr[0];
var available=opArr[1]-opArr[4];
document.getElementById("available").value=available;
if(available<=0)
{
alert('Out of Stock');
document.getElementById("qty").disabled=true;
document.getElementById("inputBid").disabled=true;
}
}
function checkInput(item)
{
var t_price=document.getElementById("t_price");
var available=document.getElementById("available");
var price=document.getElementById("truck");
var msg=document.getElementById("qty-msg");
if(item.value>available.value)
{
alert("Quantity" +item.value +"Availabe: "+available.value);
item.value='';
msg.innerHTML="* Value must be less than Availabe quantity "+available.value;
msg.style.color="red";
}
t_price.value=price.value*item.value;
}
</script>
What I run this code, If the available quantity is 15, and the quantity entered is 1, it is working fine. But when the quantity entered is other than 1, like 2, 3, or anything, it gives the message. I wish to give a message only when the quantity is greater than 15 like 16, 17, etc.
but when I try to enter 12, it is ok. when I try to enter 3, 4, etc. It gives the validation message. Same in the case, if the available quantity is 20, then quantity entered 2 will work. but 3 or anything 2 will not work. Why this is happening. Why my javascript is not working properly.
My output
When I try to enter 3, this happens in my output
When I try to enter 2 in the quantity field, it is ok
When I try to enter 12, it is working
When I try to enter 4, it is not working
I want to show this error message only when the quantity entered is greater than the available qauntity.

As said in the comments, try to convert your input value (string) in numbers before comparing. So it'll be something like this :
if(parseInt(item.value)>parseInt(available.value))
{
...
}

Related

How to validate input field with numbers only using javascript?

I am new to Javascript, I need to validate the input field. I wish to enter only numbers, not allowing alphabets or special characters. I need to show the error message below the input field. Validation rules for the input field are:
Should be numbers only
Numbers should be greater than 1 and less than available quantity.
I have form with three input fields, available quantity, quantity and bid price.
Validation on value entered on quantity field should be greater than 1 and less than the available quantity is working fine. But I need to enter only numbers using javascript.
What I have tried is
<form method="post" action="/truckianBidSave/{{id}}" id="reviewForm">
<input type="hidden" name="_token" value="{{csrf_token()}}" />
<input type="hidden" name="user_name" value="{{auth_user().first_name}}" />
<!-- <div class="form-group row">
<label class="col-sm-4 col-form-label">Select Milege Gap: </label>
<div class="col-sm-8">
<select class="form-select" name="mileage" id="mileage" onchange="getOption()">
<option>Select </option>
{% for p in product_data %}
<option value="{{p.number_of_products}},{{p.number_of_products_sold}},{{p.mileage_gap}}">{{p.mileage_gap}}</option>
{% endfor %}
</select>
</div>
</div>-->
<div class="form-group row">
{% set total=0 %}
{% set sold=0 %}
{% for p in product_data %}
{% set total =total+p.number_of_products %}
{% set sold=sold+p.number_of_products_sold %}
{% endfor %}
{% set available=total-sold %}
<label for="available" class="col-sm-4 col-form-label">Available Quantity: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="available" readonly name="available_qty" value={{available}} />
</div>
</div>
<div class="form-group row">
<label for="qty" class="col-sm-4 col-form-label"> Quantity: </label>
<div class="col-sm-8">
<input type="text" id="qty" name="qty" class="form-control" oninput="checkInput(this);" required />
<p id="qty-msg">
</p>
</div>
</div>
<div class="form-group row">
<label for="inputBid" class="col-sm-4 col-form-label">Enter Bid Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="inputBid" name="bid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"/>
</div>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" id="btn" name="send" value="Send" disabled="disabled">
</div>
</form>
Javascript code:
function checkInput(item)
{var available=document.getElementById("available");
var msg=document.getElementById("qty-msg");
if(parseInt(item.value)>parseInt(available.value) )
{
item.value='';
msg.innerHTML="* Value must be less than Availabe quantity "+available.value ;
msg.style.color="red";
}
else if(parseInt(item.value)<1)
{
item.value='';
msg.innerHTML="* Value must be greater than 1" ;
msg.style.color="red";
}
else if('/^[A-Za-z]+$/'.test(item.value))
{ alert('hi');
item.value='';
msg.innerHTML="* Only numbers allowed" ;
msg.style.color="red";
}
How to not allow alphabets and special characters in input filed using javascript.
Use this instead of your pattern
!(/^[0-9]{1,}$/.test(item.value))
It'll return true if the value contains a string, otherwise, it'll return false.
You may use <input type="number"> for the 'qty' input. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number for details.
A javascript filter like
document.getElementById('qty').addEventListener('keydown',
function(event){
if(!event.key.match(/^[0-9]$/)){
event.preventDefault();
}
}
);
is never perfectly safe, i.e., it will not work on some old browsers or mobile browsers.

How to set empty or null value doesn't worked in Jquery change

I want the value in the input text to be null after the hide process
This is my view :
<div class="form-group row">
<label for="status" class="col-sm-4 col-form-label col-form-label-sm">Status Karyawan</label>
<div class="col-sm-8">
<select id="status" name="status" class="form-control form-control-sm" required>
<option value="" selected>Pilih Status Karyawan</option>
<option value="Kontrak">Kontrak</option>
<option value="Tetap">Tetap</option>
</select>
</div>
</div>
<div class="form-group row" id="tgl_pengangkatan" style="display:none">
<label for="tgl_pengangkatan" class="col-sm-4 col-form-label col-form-label-sm">Tgl. Pengangkatan</label>
<div class="col-sm-8 input-group">
<input name="tgl_pengangkatan" type="text" class="form-control datepicker form-control-sm" id="tgl_pengangkatan" placeholder="yyyy-mm-dd" value="">
</div>
</div>
<div class="form-group row" id="tgl_berakhir_kontrak" style="display:none">
<label for="tgl_berakhir_kontrak" class="col-sm-4 col-form-label col-form-label-sm">Tgl. Akhir Kontrak</label>
<div class="col-sm-8 input-group">
<input name="tgl_berakhir_kontrak" type="text" class="form-control datepicker form-control-sm" id="tgl_berakhir_kontrak" placeholder="yyyy-mm-dd" value="">
</div>
</div>
And than, this is my script:
<script>
$(function () {
$("#status").change(function() {
var val = $(this).val();
if(val === "Kontrak") {
$("#tgl_berakhir_kontrak").show();
$("#tgl_pengangkatan").hide();
$("#tgl_pengangkatan").val('');
}
else if (val === "Tetap") {
$("#tgl_pengangkatan").show();
$("#tgl_berakhir_kontrak").hide();
$("#tgl_berakhir_kontrak").val('');
}
});
});
I want to make it like that to minimize errors in the input process, thanks.
The element you are trying to change should be called with its name, not the id. Try changing it as:
$('[name="tgl_berakhir_kontrak"]').val('');
By the way, it's not a good practice to give identical name and id to separate elements on the same page.

jQuery form validation fails only on a specific input

I have a fairly straightforward validation function that only checks if input is empty or not. I'm using it across a half dozen different forms and it seems to be working everywhere except one specific input id="driver_first_name" . Can't figure out why it fails there.
If I leave all fields empty I get errors on all of them, and is generally correct across any combination I have tried except driver_first_name In the case that I fill out everything except driver_first_name the form submits anyways.
Any insight on what might be going on here?
Thank you!
My Validation function is this:
function validateForm(form, fields) { //add exit anbimation and reset the container state
$(".form-input-error").remove();
var result=false;
$.each( fields.rules, function( key, value ) {
if(!$("#"+key+"").val()){
$("#"+key+"").addClass("form-error");
$( "<div class='form-input-error'>"+value.message+"</div>" ).insertBefore("#"+key+"");
result = false;
//console.log(this.val());
}
else{
$("#"+key+"").removeClass("form-error");
result = true;
}
});
return result;
}
I am calling my validation on my submit triggers, generally like this for fields that should not be empty:
$(".app-canvas").on('click', ".submitNewDriver", function () {//list all drivers trigger
var checkInputs = {
rules: {
driver_first_name: {
message: "First Name is Required"
},
driver_last_name: {
message: "Last Name is Required"
},
driver_address_street: {
message: "street is Required"
}
}
};
if(validateForm($("#addDriverForm"),checkInputs) == true){
console.log("form submit");
addNewDriver();
}
else{
console.log("form errors");
}
});
My full form HTML is
<div class="form-wrapper">
<form id="addDriverForm" class="post-form" action="modules/add_driver.php" method="post">
<div class="form-row">
<label for="driver_first_name">First Name:</label>
<input id="driver_first_name" placeholder="John" type="text" name="driver_first_name">
</div>
<div class="form-row">
<label for="driver_last_name">Last Name:</label>
<input id="driver_last_name" placeholder="Smith" type="text" name="driver_last_name">
</div>
<div class="form-row">
<label for="driver_address_street">Street</label>
<input id="driver_address_street" placeholder="123 Main St." type="text" name="driver_address_street">
</div>
<div class="form-row">
<label for="driver_address_city">City</label>
<input id="driver_address_city" placeholder="Chicago" type="text" name="driver_address_city">
</div>
<div class="form-row">
<label for="driver_address_state">State</label>
<input id="driver_address_state" placeholder="IL" type="text" name="driver_address_state">
</div>
<div class="form-row">
<label for="driver_address_zip">Zip</label>
<input id="driver_address_zip" placeholder="60164" type="number" name="driver_address_zip">
</div>
<div class="form-row">
<label for="driver_telephone">Zip</label>
<input id="driver_telephone" placeholder="60164" type="tel" name="driver_telephone">
</div>
<div class="form-row">
<label for="driver_email">E-Mail</label>
<input id="driver_email" placeholder="60164" type="email" name="driver_email">
</div>
<div class="form-row"><label for="driver_payment_type">Settlement Type</label>
<select id="driver_payment_type" name="driver_payment_type">
<option value="flat">Flat Rate</option>
<option value="percent">Percent</option>
<option value="mile">Per Mile</option>
</select></div>
<div class="form-row">
<label for="driver_license_number">Lisence #</label>
<input id="driver_license_number" placeholder="ex:D400-7836-2633" type="number" name="driver_license_number">
</div>
<div class="form-row">
<label for="driver_license_expiration">Lisence Expiration Date</label>
<input id="driver_license_expiration" type="date" name="driver_license_expiration">
</div>
<div class="form-row">
<label for="driver_licence_image">Lisence Copy</label>
<input id="driver_licence_image" type="file" name="driver_licence_image">
</div>
<div class="form-row">
<label for="driver_medical_certificate_expiration">Medical Certificate Expiration</label>
<input id="driver_medical_certificate_expiration" type="date" name="driver_medical_certificate_expiration">
</div>
<div class="form-row">
<label for="driver_medical_certificate_image">Medical CXertificate Copy</label>
<input id="driver_medical_certificate_image" type="file" name="driver_medical_certificate_image">
</div>
<div class="form-row">
<label class="driverCheckbox" for="driver_access_mobile_app">Allow Mobile Access</label>
<input id="driver_access_mobile_app" checked value="1" type="checkbox" name="driver_access_mobile_app">
</div>
<div class="form-row"></div>
<div class="driver-access-copnditional">
<div class="form-row">
<label for="driver_username">Username</label>
<input id="driver_username" placeholder="JohSmi" type="text" name="driver_username">
</div>
<div class="form-row">
<label for="driver_password">Password</label>
<input id="driver_password" placeholder="***" type="password" name="driver_password">
</div>
</div>
<div class="clear"></div>
<div class="submitNewUnit button green"><i class="material-icons">save</i>Submit</div>
</form>
</div>
Your validation logic is a little messed up. This is what's happening:
#driver_first_name is validated as invalid... result is set false
#driver_last_name is validated as valid... result is set true
#driver_address_street is validated as valid... result is set true
After all that the code thinks the form is valid. You're only preventing the form from being submitted if the last field as validated as not-valid.
Change your logic to assume the form is valid from the beginning. Then set it to false if any of the fields are invalid.
I also don't see anything in your code that actually prevents the form submition, so I also added e.preventDefault()
function validateForm(form, fields) { //add exit anbimation and reset the container state
$(".form-input-error").remove();
var result = true;
$.each(fields.rules, function(key, value) {
if (!$("#" + key + "").val()) {
$("#" + key + "").addClass("form-error");
$("<div class='form-input-error'>" + value.message + "</div>").insertBefore("#" + key + "");
result = false;
//console.log(this.val());
} else {
$("#" + key + "").removeClass("form-error");
}
});
return result;
}
$(".app-canvas").on('click', ".submitNewDriver", function(e) { //list all drivers trigger
var checkInputs = {
rules: {
driver_first_name: {
message: "First Name is Required"
},
driver_last_name: {
message: "Last Name is Required"
},
driver_address_street: {
message: "street is Required"
}
}
};
if (validateForm($("#addDriverForm"), checkInputs) == true) {
console.log("form submit");
} else {
e.preventDefault();
console.log("form errors");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="app-canvas form-wrapper">
<form id="addDriverForm" class="post-form" action="" method="post">
<div class="form-row">
<label for="driver_first_name">First Name:</label>
<input id="driver_first_name" placeholder="John" type="text" name="driver_first_name">
</div>
<div class="form-row">
<label for="driver_last_name">Last Name:</label>
<input id="driver_last_name" placeholder="Smith" type="text" name="driver_last_name">
</div>
<div class="form-row">
<label for="driver_address_street">Street</label>
<input id="driver_address_street" placeholder="123 Main St." type="text" name="driver_address_street">
</div>
<div class="form-row">
<label for="driver_address_city">City</label>
<input id="driver_address_city" placeholder="Chicago" type="text" name="driver_address_city">
</div>
<div class="form-row">
<label for="driver_address_state">State</label>
<input id="driver_address_state" placeholder="IL" type="text" name="driver_address_state">
</div>
<div class="form-row">
<label for="driver_address_zip">Zip</label>
<input id="driver_address_zip" placeholder="60164" type="number" name="driver_address_zip">
</div>
<div class="form-row">
<label for="driver_telephone">Zip</label>
<input id="driver_telephone" placeholder="60164" type="tel" name="driver_telephone">
</div>
<div class="form-row">
<label for="driver_email">E-Mail</label>
<input id="driver_email" placeholder="60164" type="email" name="driver_email">
</div>
<div class="form-row"><label for="driver_payment_type">Settlement Type</label>
<select id="driver_payment_type" name="driver_payment_type">
<option value="flat">Flat Rate</option>
<option value="percent">Percent</option>
<option value="mile">Per Mile</option>
</select></div>
<div class="form-row">
<label for="driver_license_number">Lisence #</label>
<input id="driver_license_number" placeholder="ex:D400-7836-2633" type="number" name="driver_license_number">
</div>
<div class="form-row">
<label for="driver_license_expiration">Lisence Expiration Date</label>
<input id="driver_license_expiration" type="date" name="driver_license_expiration">
</div>
<div class="form-row">
<label for="driver_licence_image">Lisence Copy</label>
<input id="driver_licence_image" type="file" name="driver_licence_image">
</div>
<div class="form-row">
<label for="driver_medical_certificate_expiration">Medical Certificate Expiration</label>
<input id="driver_medical_certificate_expiration" type="date" name="driver_medical_certificate_expiration">
</div>
<div class="form-row">
<label for="driver_medical_certificate_image">Medical CXertificate Copy</label>
<input id="driver_medical_certificate_image" type="file" name="driver_medical_certificate_image">
</div>
<div class="form-row">
<label class="driverCheckbox" for="driver_access_mobile_app">Allow Mobile Access</label>
<input id="driver_access_mobile_app" checked value="1" type="checkbox" name="driver_access_mobile_app">
</div>
<div class="form-row"></div>
<div class="driver-access-copnditional">
<div class="form-row">
<label for="driver_username">Username</label>
<input id="driver_username" placeholder="JohSmi" type="text" name="driver_username">
</div>
<div class="form-row">
<label for="driver_password">Password</label>
<input id="driver_password" placeholder="***" type="password" name="driver_password">
</div>
</div>
<div class="clear"></div>
<input type="submit" class="submitNewDriver button green" value="Submit" />
</form>
</div>

Dynamically add and remove form fields to be validated by Parsley.js

Here is my fiddle: My Fiddle (updated)
In my form (ID: #form), inputs fields are shown or hidden based on the selected option of a select input.
Each Input and its labels a wrapped in a div, which is hidden or shown based on the selected option. The attribute data-children of the select contains the information (in JSON Format) which inputs are to be shown when a certain option is selected.
I use the data-parsley-excluded attribute to remove the fields not visible from the parsley validation (Parsley Documentation).
Before I execute the parsley method $('#form').destroy();, at the end $('#form').parsley();
My HTML:
<div class="container">
<div class="row">
<div class="col-sm-offset-2 col-sm-8">
<form id="form" method="post" accept-charset="UTF-8" class="form-horizontal" data-parsley-validate="">
<div class="form-group">
<label class="control-label" for="question_01" style="">Question 1</label>
<select class="form-control" name="question_01" id="question_01" required data-children="{"option_01":["input_01","input_02","input_03","input_04","input_05","input_06"],"option_02":["input_01","input_06","input_07","input_08","input_09","input_10"],"option_03":["input_02","input_04","input_05","input_07","input_09","input_10","input_11"]}">
<option value="" selected>Bitte auswählen</option>
<option value="option_01">Option 01</option>
<option value="option_02">Option 02</option>
<option value="option_03">Option 03</option>
</select>
</div>
<div id="div_input_01" class="form-group input-div hidden">
<label for="input_01" style="">Input 01</label>
<input type="text" class="form-control" name="input_01" id="input_01" required>
</div>
<div id="div_input_02" class="form-group input-div hidden">
<label for="input_02" style="">Input 02</label>
<input type="text" class="form-control" name="input_02" id="input_02" required>
</div>
<div id="div_input_03" class="form-group input-div hidden">
<label for="input_03" style="">Input 03</label>
<input type="text" class="form-control" name="input_03" id="input_03" required>
</div>
<div id="div_input_04" class="form-group input-div hidden">
<label for="input_04" style="">Input 04</label>
<input type="text" class="form-control" name="input_04" id="input_04" required>
</div>
<div id="div_input_05" class="form-group input-div hidden">
<label for="input_05" style="">Input 05</label>
<input type="text" class="form-control" name="input_05" id="input_05" required>
</div>
<div id="div_input_06" class="form-group input-div hidden">
<label for="input_06" style="">Input 06</label>
<input type="text" class="form-control" name="input_06" id="input_06" required>
</div>
<div id="div_input_07" class="form-group input-div hidden">
<label for="input_07" style="">Input 07</label>
<input type="text" class="form-control" name="input_07" id="input_07" required>
</div>
<div id="div_input_08" class="form-group input-div hidden">
<label for="input_08" style="">Input 08</label>
<input type="text" class="form-control" name="input_08" id="input_08" required>
</div>
<div id="div_input_09" class="form-group input-div hidden">
<label for="input_09" style="">Input 09</label>
<input type="text" class="form-control" name="input_09" id="input_09" required>
</div>
<div id="div_input_10" class="form-group input-div hidden">
<label for="input_10" style="">Input 10</label>
<input type="text" class="form-control" name="input_10" id="input_10" required>
</div>
<div id="div_input_11" class="form-group input-div hidden">
<label for="input_11" style="">Input 11</label>
<input type="text" class="form-control" name="input_11" id="input_11" required>
</div>
<button type="button" class="btn btn-info btn-block btn-submit-settings">Submit</button>
</form>
</div>
</div>
</div>
My Javascript:
$(document).ready(function() {
$('.btn-submit-settings').on('click', function(e) {
window.Parsley.on('field:error', function()
{
console.log('Validation failed for: ', this.$element);
});
$('#form').submit();
});
$('#form select').change(function() {
var $this = $(this);
if ($this.data('children')) {
$('#form').parsley().destroy();
// Hide all child elements
$.each($this.data('children'), function(value_id, input_id_array) {
$.each(input_id_array, function(key, input_id) {
if ($('#div_' + input_id).length ) {
$('#' + input_id).val(null);
if (!$('#div_' + input_id).hasClass('hidden')) {
$('#div_' + input_id).addClass('hidden');
}
}
});
});
// show the child elements of the selected option
if ($this.data('children')[$this.val()]) {
$.each($this.data('children')[$this.val()], function(key, input_id) {
if ($('#div_' + input_id).length )
{
if ($('#div_' + input_id).hasClass('hidden'))
{
$('#div_' + input_id).removeClass('hidden');
}
}
});
}
// For all inputs inside hidden div set attribute "data-parsley-excluded" = true
$('#form div.input-div.hidden').find(':input').each(function() {
var attr_data_parsley_excluded = $(this).attr('data-parsley-excluded');
if (typeof attr_data_parsley_excluded === typeof undefined || attr_data_parsley_excluded === false) {
$(this).attr('data-parsley-excluded', 'true');
}
});
// For all inputs inside not hidden div remove attribute "data-parsley-excluded"
$('#form div.input-div:not(.hidden)').find(':input').each(function() {
console.log(this.id);
$(this).removeAttr('data-parsley-excluded');
});
$('#form').find(':input').each(function() {
// Log shows that attribute is set right, seems to be ignored by parsley
console.log('ID: ' + this.id + ' TYPE: ' + $(this).prop('nodeName') + ': excluded=' + $(this).attr('data-parsley-excluded'));
});
$('#form').parsley();
$('#form').parsley().refresh();
}
});
});
I can't get it to work, even though the attributes seem to be set the right way.
The fields once hidden, stay out of the validation.
I guess you should add the attribute data-parsley-required="false" to exclude hidden fields from validation.
I mean, try to change
<input type="text" class="form-control" name="input_01" id="input_01" required>
to this
<input type="text" class="form-control" name="input_01" id="input_01" data-parsley-required="false">
and just change the attribute value if you want to validate it or not
This is more of a personal opinion than a factual answer, but I think you are attempting to solve the problem incorrectly. If I were doing this, I would create 2 parsley groups "shouldValidate" and "shouldNotValidate", and add your fields accordingly based on whether they are displayed or not. Then when you call validate, pass the group name "shouldValidate", and only that set of elements will be validated.
You probably need to call refresh on your parsley form after you modify excluded.

Multiple input fields to JSON

I've a form which has input fields as shown in figure below. Each time I click the add button, the row containing the input fields is appended.
The html code goes like this :
<div class="row">
<div class="row ifields">
<div class="col-sm-3 form-group">
</div>
<div class="col-sm-2 form-group">
<input type="text" class="form-control" name="pname" placeholder="Product Name" />
</div>
<div class="col-sm-2 form-group">
<input type="number" min="1" class="form-control text-center" name="pquantity" placeholder="Product Quantity" />
</div>
<div class="col-sm-2 form-group">
<select class="form-control text-center" name="qtype">
<option value="g">g</option>
<option value="Kg">Kg</option>
<option value="ml">ml</option>
<option value="L">Lt.</option>
<option value="pc">Pc</option>
</select>
</div>
<div class="col-sm-2 form-group">
<input type="text" class="form-control text-center" name="pcost" placeholder="Product Cost" />
</div>
<div class="col-sm-1"><button class="btn btn-default add-btn">Add</button></div>
</div>
</div>
<div class="row iclone"></div>
</div>
And the Jquery code :
$(document).ready(function(){
$('.add-btn').click(function(){
var cl = $('.ifields').first('.row').clone(true);
$('.iclone').append(cl);
});
});
I want to go through each row and create a JSON file. For ex:
[{
"product" : "A",
"quantity" : "100",
"quantitytype" : "g",
"cost" : "100"
},
...
....
]
How to do create this JSON output ? Please guide.
You can use map() to create the required array of objects. Try this:
var data = $('.row.ifields').map(function() {
return {
product: $(this).find('[name="pname"]').val(),
quantity: $(this).find('[name="pquantity"]').val(),
quantityttype: $(this).find('[name="qtype"]').val(),
cost: $(this).find('[name="pcost"]').val()
};
}).get();
You can then use the data array as required - presumably in a $.ajax() call.
Working example

Categories

Resources