form drop-down selection based input trigger in jquery - javascript

my form has drop-down form invoice type which has two value when user select services i want to hide from_date and to_date field from form, when user select milestone i want to hide upload_file input from form.
<form id="raise-invoice-form-validation" accept-charset="UTF-8" method="post">
<div class="row">
<div class="field columns large-3">
<label class="required" for="raise_invoice_invoice_type">Invoice type</label>
<select name="raise_invoice[raised_invoice_type]" id="raise_invoice_raised_invoice_type"><option value="">Select One</option>
<option value="0">services</option>
<option value="1">milestones</option></select>
</div>
<div class="field columns large-3">
<label class="required" for="raise_invoice_from_date">From date</label>
<input class="datepicker hasDatepicker" type="date" name="raise_invoice[from_date]" id="raise_invoice_from_date"><button type="button" class="ui-datepicker-trigger"><img src="/images/calendar.gif" alt="..." title="..."></button>
</div>
<div class="field columns large-3">
<label class="required" for="raise_invoice_to_date">To date</label>
<input class="datepicker hasDatepicker" type="date" name="raise_invoice[to_date]" id="raise_invoice_to_date"><button type="button" class="ui-datepicker-trigger"><img src="/images/calendar.gif" alt="..." title="..."></button>
</div>
<input value="20" type="hidden" name="raise_invoice[payment_milestone_id]" id="raise_invoice_payment_milestone_id">
<div class="field columns large-2">
<label for="raise_invoice_upload_file">Upload file</label>
<input type="file" name="raise_invoice[raised_invoice_file]" id="raise_invoice_raised_invoice_file">
</div>
</div>
<div class="row">
<div class="field columns large-3">
<label for="raise_invoice_raised_invoice_for">Raised invoice for</label>
<select name="raise_invoice[raised_invoice_for]" id="raise_invoice_raised_invoice_for"><option value="">Select One</option>
<option value="0">Performa Invoice</option>
<option value="1">Tax Invoice</option></select>
<div class="actions text-center">
<input type="submit" value="Raise invoice" class="button primary button-margin-top" data-disable-with="Raise invoice">
</div>
</form>

You can use simply change function to check which option was selected and hide the relevant divs accordingly.
//hide on load
$('.from_date, .to_date').hide()
$('.upload_field').hide()
//watch the change
$(document).on('change', '#raise_invoice_raised_invoice_type', function() {
if ($(this).val() == '0') {
$('.from_date, .to_date').hide()
$('.upload_field').show()
} else if ($(this).val() == '1') {
$('.upload_field').hide()
$('.from_date, .to_date').show()
} else {
$('.upload_field').hide()
$('.from_date, .to_date').hide()
}
})
Live Demo:
//hide on load
$('.from_date, .to_date').hide()
$('.upload_field').hide()
//watch the change
$(document).on('change', '#raise_invoice_raised_invoice_type', function() {
if ($(this).val() == '0') {
$('.from_date, .to_date').hide()
$('.upload_field').show()
} else if ($(this).val() == '1') {
$('.upload_field').hide()
$('.from_date, .to_date').show()
} else {
$('.upload_field').hide()
$('.from_date, .to_date').hide()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="raise-invoice-form-validation" accept-charset="UTF-8" method="post">
<div class="row">
<div class="field columns large-3">
<label class="required" for="raise_invoice_invoice_type">Invoice type</label>
<select name="raise_invoice[raised_invoice_type]" id="raise_invoice_raised_invoice_type">
<option value="" selected>Select One</option>
<option value="0">services</option>
<option value="1">milestones</option>
</select>
</div>
<div class="field columns large-3 from_date">
<label class="required" for="raise_invoice_from_date">From date</label>
<input class="datepicker hasDatepicker" type="date" name="raise_invoice[from_date]" id="raise_invoice_from_date"><button type="button" class="ui-datepicker-trigger"><img src="/images/calendar.gif" alt="..." title="..."></button>
</div>
<div class="field columns large-3 to_date">
<label class="required" for="raise_invoice_to_date">To date</label>
<input class="datepicker hasDatepicker" type="date" name="raise_invoice[to_date]" id="raise_invoice_to_date"><button type="button" class="ui-datepicker-trigger"><img src="/images/calendar.gif" alt="..." title="..."></button>
</div>
<input value="20" type="hidden" name="raise_invoice[payment_milestone_id]" id="raise_invoice_payment_milestone_id">
<div class="field columns large-2 upload_field">
<label for="raise_invoice_upload_file">Upload file</label>
<input type="file" name="raise_invoice[raised_invoice_file]" id="raise_invoice_raised_invoice_file">
</div>
</div>
<div class="row">
<div class="field columns large-3">
<label for="raise_invoice_raised_invoice_for">Raised invoice for</label>
<select name="raise_invoice[raised_invoice_for]" id="raise_invoice_raised_invoice_for">
<option value="">Select One</option>
<option value="0">Performa Invoice</option>
<option value="1">Tax Invoice</option>
</select>
<div class="actions text-center">
<input type="submit" value="Raise invoice" class="button primary button-margin-top" data-disable-with="Raise invoice">
</div>
</form>

You can use toggle(boolean) and use selected value comparison to create the boolean
$('#raise_invoice_raised_invoice_type').change(function() {
const val = $(this).val();
$('.from_date, .to_date').toggle(val === '0')
$('.upload_field').toggle(val === '1');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="raise-invoice-form-validation" accept-charset="UTF-8" method="post">
<div class="row">
<div class="field columns large-3">
<label class="required" for="raise_invoice_invoice_type">Invoice type</label>
<select name="raise_invoice[raised_invoice_type]" id="raise_invoice_raised_invoice_type">
<option disabled selected>Select One</option>
<option value="0">services</option>
<option value="1">milestones</option>
</select>
</div>
<div class="field columns large-3 from_date">
<label class="required" for="raise_invoice_from_date">From date</label>
<input class="datepicker hasDatepicker" type="date" name="raise_invoice[from_date]" id="raise_invoice_from_date"><button type="button" class="ui-datepicker-trigger"><img src="/images/calendar.gif" alt="..." title="..."></button>
</div>
<div class="field columns large-3 to_date">
<label class="required" for="raise_invoice_to_date">To date</label>
<input class="datepicker hasDatepicker" type="date" name="raise_invoice[to_date]" id="raise_invoice_to_date"><button type="button" class="ui-datepicker-trigger"><img src="/images/calendar.gif" alt="..." title="..."></button>
</div>
<input value="20" type="hidden" name="raise_invoice[payment_milestone_id]" id="raise_invoice_payment_milestone_id">
<div class="field columns large-2 upload_field">
<label for="raise_invoice_upload_file">Upload file</label>
<input type="file" name="raise_invoice[raised_invoice_file]" id="raise_invoice_raised_invoice_file">
</div>
</div>
<div class="row">
<div class="field columns large-3">
<label for="raise_invoice_raised_invoice_for">Raised invoice for</label>
<select name="raise_invoice[raised_invoice_for]" id="raise_invoice_raised_invoice_for">
<option value="">Select One</option>
<option value="0">Performa Invoice</option>
<option value="1">Tax Invoice</option>
</select>
<div class="actions text-center">
<input type="submit" value="Raise invoice" class="button primary button-margin-top" data-disable-with="Raise invoice">
</div>
</form>

Related

Add Third Select Drop Down and Auto Populate Based on Selection

I have made a request form for my group to make it easier for them to request for help desk. At the moment I have two dropdowns - I have the main request dropdown when the user selects from the first dropdown selection it goes to the second dropdown selection for the user to select. I want to add the third dropdown so when the user selects from the second dropdown it opens more selection in the third dropdown based on what category the user has selected for the Second dropdown.
How can i add third select option and then show the input for the selection
$(function() {
// on page load wrap all select-2 options in span so they cannot be selected without specifying select-1
$('#select-2 option:not([selected])').wrap('<span/>');
});
// when select-1 is changed, hide all options that do not have the class corresponding to the value of select-1
$('#select-1').change(function() {
$('#select-2 span > option').unwrap();
console.log($('#select-1'));
$('#select-2 option:not(.' + $('#select-1').val() + ', [selected])').wrap('<span/>');
//console.log($('#select-2').val());
});
$('#select-2').trigger('change');
$(document).ready(function() {
$("#otherFieldGroupNewacc").hide();
$("#otherFieldGroupMod").hide();
$("#otherFieldGroupRes").hide();
$("#otherFieldGroupRem").hide()
});
//----------------------------------Second Dropdown----------------------------------------------//
$(function() {
$("#select-2").change(function() {
if ($(this).val() == "AS400 New Account") { //AS400 New Account //
$("#otherFieldGroupNewacc").show();
$('#otherFieldGroupNewacc').attr('required', '');
} else {
$("#otherFieldGroupNewacc").hide();
$('#otherFieldGroupNewacc').removeAttr('required');
}
if ($(this).val() == "Modify Account") { //AS400 Modify Account //
$("#otherFieldGroupMod").show();
} else {
$("#otherFieldGroupMod").hide();
}
if ($(this).val() == "Reset Password") { //AS400 Reinstate Account //
$("#otherFieldGroupRes").show();
} else {
$("#otherFieldGroupRes").hide();
}
if ($(this).val() == "Remove Password") { //AS400 Remove Account //
$("#otherFieldGroupRem").show();
} else {
$("#otherFieldGroupRem").hide();
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Request Type</label>
<select id="select-1" name="select-1" class="form-control w-100" required>
<option selected value="">--Select an option--</option>
<option value="AS400">AS400</option>
<!-- "option-1" -->
<option value="EETV">EETV</option>
<!-- "option-2" -->
<option value="Outlook">Outlook</option>
<!-- "option-3" -->
<option value="Windows">Windows</option>
<!-- "option-4" -->
</select>
<br/>
<label>Choose a Sub-Category</label>
<select id="select-2" name="select-2" class="form-control w-100" required>
<option selected value="">--Select an option--</option>
<option value="AS400 New Account" class="AS400">New Account</option>
<!-- "option-1a" -->
<option value="Modify Account" class="EETV">Modify Account</option>
<!-- "option-1b" -->
<option value="Reset Password" class="Outlook">Reset Password</option>
<!-- "option-1c" -->
<option value="Remove Password" class="Windows">Remove Account</option>
<!-- "option-1d" -->
</select>
</div>
<hr>
<!--AS400 New Account-->
<div class="form-group" id="otherFieldGroupNewacc">
<h2>AS400 New Account</h2>
<hr>
<div class="row">
<div class="col-6">
<label for="userRequestor">Full Name</label>
<input type="text" class="form-control w-100" id="userRequestor" name="userRequestor" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userTM">Beneficiary (Full Name)</label>
<input type="text" class="form-control w-100" id="userTM" name="userTM" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userEmployee">Employee ID</label>
<input type="text" class="form-control w-100" id="userEmployee" name="userEmployee" placeholder="Type Here...">
</div>
<br>
<div class="col-6">
<label for="selectJob">New Job Category</label>
<select id="selectJob" name="selectJob" class="form-control w-100" placeholder="*Click in box for Job Category List*">
<option disabled selected value="">Select an option</option>
<option value="NO CHANGE">NO CHANGE</option>
<option value="ADMCLK = Admin Clerk">ADMCLK = Admin Clerk</option>
<option value="ADMCLK+ = Admin Clerk w/ Manual Book">ADMCLK+ = Admin Clerk w/ Manual Book</option>
<option value="ADMMGR = Admin MGR w/ Manual Book">ADMMGR = Admin MGR w/ Manual Book</option>
</select>
</div>
<br>
<div class="col-6">
<label for="userNewAS400">New AS400 ID</label>
<input type="text" class="form-control w-100" id="userNewAS400" name="userNewAS400" placeholder="Type Here...">
</div>
</div>
</div>
<!--Modify AS400 Account-->
<div class="form-group" id="otherFieldGroupMod">
<h2>AS400 Modify Account</h2>
<hr>
<div class="row">
<div class="col-6">
<label for="userRequestorMod">Requester (Full Name)</label>
<input type="text" class="form-control w-100" id="userRequestorMod" name="userRequestorMod" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userTMMod">Beneficiary (Full Name)</label>
<input type="text" class="form-control w-100" id="userTMMod" name="userTMMod" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userEmployeeMod">Employee ID</label>
<input type="text" class="form-control w-100" id="userEmployeeMod" name="userEmployeeMod" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userAS400Mod">AS400 ID</label>
<input type="text" class="form-control w-100" id="userAS400Mod" name="userAS400Mod" placeholder="Type Here...">
</div>
<br>
<div class="col-6">
<label for="selectJobsMod">New Job Category</label>
<select id="selectJobsMod" name="selectJobsMod" class="form-control w-100" placeholder="*Click in box for Job Category List*">
<option disabled selected value="">Select an option</option>
<option value="NO CHANGE">NO CHANGE</option>
<option value="ADMCLK = Admin Clerk">ADMCLK = Admin Clerk</option>
<option value="ADMCLK+ = Admin Clerk w/ Manual Book">ADMCLK+ = Admin Clerk w/ Manual Book</option>
<option value="ADMMGR = Admin MGR w/ Manual Book">ADMMGR = Admin MGR w/ Manual Book</option>
<option value="DCM = DC Manager">DCM = DC Manager</option>
<option value="FM IN = Inbound Funtion Manager">FM IN = Inbound Funtion Manager</option>
</select>
</div>
<br>
<div class="col-6">
<label for="userNewAS400Mod">New AS400 ID <strong>***Leave Blank If No Change***</strong></label>
<input type="text" class="form-control w-100" id="userNewAS400Mod" name="userNewAS400Mod" placeholder="Type Here...">
</div>
</div>
</div>
<!--Reinstate AS400 Account-->
<div class="form-group" id="otherFieldGroupRes">
<h2>AS400 Reinstate Password</h2>
<hr>
<div class="row">
<div class="col-6">
<label for="userRequestorRe">Requester (Full Name)</label>
<input type="text" class="form-control w-100" id="userRequestorRe" name="userRequestorRe" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userTMRe">Beneficiary (Full Name)</label>
<input type="text" class="form-control w-100" id="userTMRe" name="userTMRe" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userEmployeeRe">Employee ID</label>
<input type="text" class="form-control w-100" id="userEmployeeRe" name="userEmployeeRe" placeholder="Type Here...">
</div>
<br><br>
<div class="col-6">
<label for="userAS400Re">AS400 ID</label>
<input type="text" class="form-control w-100" id="userAS400Re" name="userAS400Re" placeholder="Type Here...">
</div>
</div>
</div>
<!--Remove AS400 Account-->
<div class="form-group" id="otherFieldGroupRem">
<h2>AS400 Remove Account</h2>
<hr>
<div class="row">
<div class="col-6">
<label for="userRequestorRes">Requester (Full Name)</label>
<input type="text" class="form-control w-100" id="userRequestorRes" name="userRequestorRes" placeholder="Type Here...">
</div>
<br>
<div class="col-6">
<label for="userTMRes">Terminated TM (Full Name)</label>
<input type="text" class="form-control w-100" id="userTMRes" name="userTMRes" placeholder="Type Here...">
</div>
<br>
<div class="col-6">
<label for="userEmployeeRes">Employee ID</label>
<input type="text" class="form-control w-100" id="userEmployeeRes" name="userEmployeeRes" placeholder="Type Here...">
</div>
<br>
<div class="col-6">
<label for="userAS400Res">AS400 ID</label>
<input type="text" class="form-control w-100" id="userAS400Res" name="userAS400Res" placeholder="Type Here...">
</div>
<br>
<div class="col-6">
<label for="hideInputRes">Reason</label>
<input type="text" class="form-control w-100" id="hideInputRes" name="hideInputRes" title="Example: Fired, Retired, Leave of Absence, etc..." placeholder="Type Here...">
</div>
</div>
</div>

jQuery/PHP dynamic form submission

I'm looking for a way to submit multiple dynamic form fields in a single submission.
Each row of data when submitted will share certain attributes:
job id, client, type of work.
While also keeping their own independent variables:
role, name, tvl, start date, end date, start time, end time.
I think my solution will either require a for loop or the use of multi dimensional arrays (maybe both?) but I can't quite figure out where in my code to implement that or how to do so.
At the moment - only 1 "employee" is showing up in my database - typically the last entry made in the "details" div.
Here is the code:
HTML
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<head>
</head>
<body>
<form method="POST" action="include/ajax.inc.php" class="ajax">
<h2>Job Details</h2>
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Job ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="a" id="a">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Client</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="b" id="b">
<option value="" disabled selected>Select</option>
<option value="OPTION1" name="OPTION1">OPTION1</option>
<option value="OPTION2" name="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type of Work</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="c" id="c">
<option value="" disabled selected>Select</option>
<option value="OPTION1" name="OPTION1">OPTION1</option>
<option value="OPTION2" name="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<h2>Employee Details</h2>
<button class="btn btn-lg btn-primary btn-rounded m-sm" id="add">
<small>ADD EMPLOYEE</small>
</button>
<!--- ADD EMPLOYEES --->
<div class="ibox" id="details" name="details[]">
<div class="ibox-content">
<div class="container">
<div class="row">
<div class="col">
<label class="form-label">Position</label>
<select class="form-control" type="text" name="d" id="d">
<option value="" disabled selected>Select</option>
<option value="ROLE1" name="SPV">ROLE1</option>
<option value="ROLE2" name="REG">ROLE2</option>
</select>
</div>
<div class="col">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="e" id="e">
</div>
<div class="col">
<label class="form-label">TVL</label>
<input type="text" class="form-control" name="f" id="f">
</div>
<div class="col">
<label class="form-label">Start Date</label>
<input type="date" class="form-control" name="g" id="g">
</div>
<div class="col">
<label class="form-label">End Date</label>
<input type="date" class="form-control" name="h" id="h">
</div>
<div class="col">
<label class="form-label">Start Time</label>
<input type="time" class="form-control" name="i" id="i">
</div>
<div class="col">
<label class="form-label">End Time</label>
<input type="time" class="form-control" name="j" id="j">
</div>
<div class="col text-right m-t-lg">
</div>
</div>
</div>
</div>
</div>
<!--- ADD EMPLOYEES END --->
<div class="hr-line-dashed"></div>
<button type="submit" class="btn btn-primary btn-med" name="submit">Submit</button>
</form>
<!-- SCCRIPT-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
JS
main.js
$(document).ready(function(){
var html = ' <div class="ibox" id="details" name="details[i]"> <div class="ibox-content"> <div class="container"> <div class="row"> <div class="col"> <label class="form-label">Position</label> <select class="form-control" type="text" name="d" id="d"> <option value="" disabled selected>Select</option> <option value="SPV" name="SPV">SPV</option> <option value="REG" name="REG">REG</option> </select> </div> <div class="col"> <label class="form-label">Name</label> <input type="text" class="form-control" name="e" id="e"> </div> <div class="col"> <label class="form-label">TVL</label> <input type="text" class="form-control" name="f" id="f"> </div> <div class="col"> <label class="form-label">Start Date</label> <input type="date" class="form-control" name="g" id="g"> </div> <div class="col"> <label class="form-label">End Date</label> <input type="date" class="form-control" name="h" id="h"> </div> <div class="col"> <label class="form-label">Start Time</label> <input type="time" class="form-control" name="i" id="i"> </div> <div class="col"> <label class="form-label">End Time</label> <input type="time" class="form-control" name="j" id="j"> </div> <div class="col text-right m-t-lg"> </div> <div class="col text-right m-t-lg"> <button class="btn btn-sm btn-rounded btn-danger" id="remove"> <i class="fa fa-times"></i> </button> </div></div> </div> </div> </div>'
// Add rows to the form
$(function() {
$('#add').click(function(e) {
$('#details').append(html);
e.preventDefault();
});
// Remove rows from the form
$(this).on('click', '#remove', function(e) {
$(this).closest('#details').remove();
});
});
});
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[id]').each(function(index, value){
var that = $(this),
name = that.attr('id'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
PHP
ajax.inc.php
<?php
include 'form.dbh.php'; {
$jobid = mysqli_real_escape_string($conn,$_POST['a']);
$client = mysqli_real_escape_string($conn,$_POST['b']);
$type = mysqli_real_escape_string($conn,$_POST['c']);
$role = mysqli_real_escape_string($conn,$_POST['d']);
$name = mysqli_real_escape_string($conn,$_POST['e']);
$tvl = mysqli_real_escape_string($conn,$_POST['f']);
$sdate = mysqli_real_escape_string($conn,$_POST['g']);
$edate = mysqli_real_escape_string($conn,$_POST['h']);
$stime = mysqli_real_escape_string($conn,$_POST['i']);
$etime = mysqli_real_escape_string($conn,$_POST['j']);
$sql = "INSERT INTO timesheets(jobid, client, type, role, name, tvl, sdate, edate, stime, etime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, 'ssssssssss', $jobid, $client, $type, $role, $name, $tvl, $sdate, $edate, $stime, $etime);
mysqli_stmt_execute($stmt);
}
header("Location:../index.php?success");
}
?>
Does anyone have an idea? or any suggestions?
Consider the following.
$(function() {
var html = ' <div class="ibox" id="details" name="details[i]"> <div class="ibox-content"> <div class="container"> <div class="row"> <div class="col"> <label class="form-label">Position</label> <select class="form-control" type="text" name="d" id="d"> <option value="" disabled selected>Select</option> <option value="SPV" name="SPV">SPV</option> <option value="REG" name="REG">REG</option> </select> </div> <div class="col"> <label class="form-label">Name</label> <input type="text" class="form-control" name="e" id="e"> </div> <div class="col"> <label class="form-label">TVL</label> <input type="text" class="form-control" name="f" id="f"> </div> <div class="col"> <label class="form-label">Start Date</label> <input type="date" class="form-control" name="g" id="g"> </div> <div class="col"> <label class="form-label">End Date</label> <input type="date" class="form-control" name="h" id="h"> </div> <div class="col"> <label class="form-label">Start Time</label> <input type="time" class="form-control" name="i" id="i"> </div> <div class="col"> <label class="form-label">End Time</label> <input type="time" class="form-control" name="j" id="j"> </div> <div class="col text-right m-t-lg"> </div> <div class="col text-right m-t-lg"> <button class="btn btn-sm btn-rounded btn-danger" id="remove"> <i class="fa fa-times"></i> </button> </div></div> </div> </div> </div>'
$('#add').click(function(e) {
$('#details').append(html);
e.preventDefault();
});
// Remove rows from the form
$(this).on('click', '#remove', function(e) {
$(this).closest('#details').remove();
});
$('form.ajax').on('submit', function(e) {
e.preventDefault();
var that = $(this),
u = that.attr('action'),
t = that.attr('method'),
d = {};
that.find('[id]').each(function(i, el) {
d[$(el).attr("id")] = $(el).val();
});
$.ajax({
url: u,
type: t,
data: d,
success: function(response) {
console.log(response);
}
});
return false;
});
});
This cleans up some of the issues you are seeing. When using .each() you will have an Index and Element, not a Value.
Update
The code above will submit all data based on the form.ajax selector. When you have only one section of details in the form, that is all the data that will be submitted. If you add your HTML, you cause an HTML/JS issue where the ID attributes of the elements are no longer Unique. All IDs must be unique.
Consider ignoring the IDs and make use of name attribute instead. When you gather the data, for d through j, these would need to be Arrays, since these are the items that repeat.
Consider the following.
$(function() {
function getData(f) {
var myData = {
a: $("[name='a']", f).val(),
b: $("[name='b']", f).val(),
c: $("[name='c']", f).val(),
d: [],
e: [],
f: [],
g: [],
h: [],
i: [],
j: []
};
var k, v;
$("[name]", f).each(function(i, el) {
k = $(el).attr("name");
v = $(el).val();
if (i > 2) {
myData[k].push(v);
}
});
console.log(myData);
return myData;
}
$('#add').click(function(e) {
var html = $("#details > .ibox-content:eq(0)").clone(true);
$(".col:last", html).html("<button class='btn btn-sm btn-rounded btn-danger remove' id='remove-" + $(".ibox-content").length + "'> <i class='fa fa-times'></i> </button>");
$(".ibox-content:last").after(html);
e.preventDefault();
});
$("#details").on('click', '.remove', function(e) {
$(this).closest('.ibox-content').remove();
});
$("form.ajax").submit(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: getData(this),
success: function(response) {
console.log(response);
}
});
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="include/ajax.inc.php" class="ajax">
<h2>Job Details</h2>
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Job ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="a" id="a">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Client</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="b" id="b">
<option value="" disabled selected>Select</option>
<option value="OPTION1">OPTION1</option>
<option value="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type of Work</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="c" id="c">
<option value="" disabled selected>Select</option>
<option value="OPTION1">OPTION1</option>
<option value="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<h2>Employee Details</h2>
<button class="btn btn-lg btn-primary btn-rounded m-sm" id="add"><small>ADD EMPLOYEE</small></button>
<!--- ADD EMPLOYEES --->
<div id="details" class="ibox">
<div class="ibox-content">
<div class="container">
<div class="row">
<div class="col">
<label class="form-label">Position</label>
<select class="form-control" type="text" name="d" id="d">
<option value="" disabled selected>Select</option>
<option value="ROLE1">ROLE1</option>
<option value="ROLE2">ROLE2</option>
</select>
</div>
<div class="col">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="e" id="e">
</div>
<div class="col">
<label class="form-label">TVL</label>
<input type="text" class="form-control" name="f" id="f">
</div>
<div class="col">
<label class="form-label">Start Date</label>
<input type="date" class="form-control" name="g" id="g">
</div>
<div class="col">
<label class="form-label">End Date</label>
<input type="date" class="form-control" name="h" id="h">
</div>
<div class="col">
<label class="form-label">Start Time</label>
<input type="time" class="form-control" name="i" id="i">
</div>
<div class="col">
<label class="form-label">End Time</label>
<input type="time" class="form-control" name="j" id="j">
</div>
<div class="col text-right m-t-lg">
</div>
</div>
</div>
</div>
</div>
<!--- ADD EMPLOYEES END --->
<div class="hr-line-dashed"></div>
<button type="submit" class="btn btn-primary btn-med">Submit</button>
</form>
You may notice, only specific elements have the name attribute now. DIV elements should not use name and the same goes for OPTION. DIV is not a part of a Form. OPTION is a element part of SELECT which is the parent container and the form element, this should have name.
Your PHP will get a complex payload of data. For example:
{
"a": "2020",
"b": "OPTION1",
"c": "OPTION2",
"d": [
"ROLE1",
"ROLE2"
],
"e": [
"Bob",
"Nancy"
],
"f": [
"1",
"2"
],
"g": [
"2020-10-12",
"2020-10-12"
],
"h": [
"2020-10-16",
"2020-10-16"
],
"i": [
"08:00",
"08:00"
],
"j": [
"12:00",
"12:00"
]
}
You will need to adjust your PHP to handle this new data format.

Input fields required if certain select option is selected in a HTML form

I am trying to make the textbox required when select option is selected and submit.
When I select Education then input for Education is required
When I select Business then input for Business is required
When I select Business & Education then both inputs are required. is required
Any help would be greatly appreciated. Thanks.
function changePurpose(){
if(document.getElementById('TravelPurpose').value == "Education")
{
document.getElementById('PoT_Ebudget').setAttribute("required","");
}
else
{
document.getElementById('PoT_Ebudget').setAttribute("required","");
}
if(document.getElementById('TravelPurpose').value == "Business")
{
document.getElementById('PoT_Bbudget').setAttribute("required","");
}
else
{
document.getElementById('PoT_Bbudget').setAttribute("required","");
}
if(document.getElementById('TravelPurpose').value == "Education & Business")
{
document.getElementById('PoT_Bbudget').setAttribute("required","");
document.getElementById('PoT_Ebudget').setAttribute("required","");
}
else
{
document.getElementById('PoT_Bbudget').setAttribute("required","");
document.getElementById('PoT_Bbudget').setAttribute("required","");
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<form id="myform">
<div class="row">
<div class="col-sm-6">
<div class="form-group options">
<label class="form-label" for="purpose"> Purpose of Travel</label>
<div class="controls" onchange="purpose(this)">
<select class="form-control" id="TravelPurpose" name="PoT_TravelPurpose" onchange="changePurpose()" required>
<option selected value="">Select Travel Purpose</option>
<option value="Business">Business</option>
<option value="Education">Education</option>
<option value="Education & Business">Education and Business</option>
</select>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="form-label" for="Budget"> Education</label>
<div class="controls input-group primary">
<span class="input-group-addon">$</span>
<input type="number" style="text-align: right;" id="PoT_Ebudget" name="PoT_Ebudget" placeholder="00.00" min="0" max="10000" oninput="this.value = Math.abs(this.value)">
</div>
<br />
<label class="form-label" for="Budget"> Business</label>
<div class="controls input-group primary">
<span class="input-group-addon">$</span>
<input type="number" style="text-align: right;" id="PoT_Bbudget" name="PoT_Bbudget" placeholder="00.00" min="0" max="10000" oninput="this.value = Math.abs(this.value)">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit" >
</form>
You can set a field to become required by setting its required property:
Example:
document.getElementById('PoT_Ebudget').required = true;
//...or
document.getElementById('PoT_Ebudget').required = false;
Also, it's a good idea to cache your element references in variables, for both improved code readability and performance.
const PoT_Ebudget = document.getElementById('PoT_Ebudget');
const PoT_Bbudget = document.getElementById('PoT_Bbudget');
function changePurpose(){
const value = document.getElementById('TravelPurpose').value;
PoT_Ebudget.required = (value == "Education" || value == "Education & Business");
PoT_Bbudget.required = (value == "Business" || value == "Education & Business");
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<form id="myform">
<div class="row">
<div class="col-sm-6">
<div class="form-group options">
<label class="form-label" for="purpose"> Purpose of Travel</label>
<div class="controls">
<select class="form-control" id="TravelPurpose" name="PoT_TravelPurpose" onchange="changePurpose()" required>
<option selected value="">Select Travel Purpose</option>
<option value="Business">Business</option>
<option value="Education">Education</option>
<option value="Education & Business">Education and Business</option>
</select>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="form-label" for="Budget"> Education</label>
<div class="controls input-group primary">
<span class="input-group-addon">$</span>
<input type="number" style="text-align: right;" id="PoT_Ebudget" name="PoT_Ebudget" placeholder="00.00" min="0" max="10000" oninput="this.value = Math.abs(this.value)">
</div>
<br />
<label class="form-label" for="Budget"> Business</label>
<div class="controls input-group primary">
<span class="input-group-addon">$</span>
<input type="number" style="text-align: right;" id="PoT_Bbudget" name="PoT_Bbudget" placeholder="00.00" min="0" max="10000" oninput="this.value = Math.abs(this.value)">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit" >
</form>

Set text field min and max value based on the option selected in previous dropdown

I have a drop down and a text box next to it.
When some value is selected in the dropdown, the textbox should allow min and max characters based on the selected option.
Suppose I select option 1, then the textbox next to it should allow minimum 10 characters and max 16 characters.
How to achieve it?
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="required">Select Type</label>
<select class="form-control" id="prooftype">
<option value="0" disabled> </option>
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group md-form">
<label class="required" for="id" data-error="wrong" data-success="right">
<i class="fa fa-info pr-2"></i>
Enter Identity Card Number
</label>
<input id="id" type="number" minlength="3" class="form-control validate" autocomplete="off" onkeypress="return blockSpecialChar(event)" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" maxlength="20" />
</div>
</div>
</div>
you have to change a little your code
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="required">Select Type</label>
<select class="form-control" id="prooftype">
<option value="0/0" disabled> </option>
<option value="10/16">name1</option>
<option value="20/32">name2</option>
<option value="30/48">name3</option>
<option value="40/64">name4</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group md-form">
<label class="required" for="id" data-error="wrong" data-success="right">
<i class="fa fa-info pr-2"></i>
Enter Identity Card Number
</label>
<input id="id" type="text" minlength="3" class="form-control validate" autocomplete="off" onkeypress="return blockSpecialChar(event)" maxlength="20" />
</div>
</div>
</div>
and jQuery
$('#prooftype').change(function(){
var tmp = $(this).val().split('/');
$('input#id').attr('minlength',tmp[0]).attr('maxlength',tmp[1]);
})
If you pass the the option value of 12/16 to the backend, obviously the data will reflect. I think you need something like this:
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="required">Select Type</label>
<select class="form-control" id="prooftype">
<option value="0/0" disabled> </option>
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group md-form">
<label class="required" for="id" data-error="wrong" data-success="right">
<i class="fa fa-info pr-2"></i>
Enter Identity Card Number
</label>
<input id="inputid" type="text" minlength="3" class="form-control validate" autocomplete="off" onkeypress="return blockSpecialChar(event)" maxlength="20" />
</div>
</div>
</div>
And your JQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var selectedopt;
$('#prooftype').change(function(){
selectedopt= $(this).val();
//Add your condition here, and check the selected option value:
if(selectedopt== "name1")
{
//Set input min and max value based on the selected option value.
$('#inputid').attr('minlength','10').attr('maxlength','16');
}
elseif(selectedopt== "name2")
{
$('#inputid').attr('minlength','20').attr('maxlength','25');
}
// And so on........
})
</script>

Jquery Get iD and Value and display URL parameters

I used below HTML & JS script to get ID and value of each element inside the form.
But, i need to get all these value and like below and added to the URL on top when user submit the form to redirect booking engine.
Getting below output on console.log:
someaction?fromLocation=undefined&departureDate=undefined&tripType=undefined&returnDate=undefined
HTML:
<form method="POST" id="bookingForm" action="someaction">
<div class="col-lg-6">
<div class="form-group">
<label for="fromLocation">From:</label>
<select class="select form-control input-lg" id="fromLocation" form="fromLocation" name="fromLocation" required>
<option value="">From</option>
<option value="ADL">Adelaide</option>
<option value="DRW">Darwin</option>
<option value="MEL">Melbourne</option>
<option value="PER">Perth</option>
</select>
</div>
<div class="form-group">
<label for="departure">Departure Date:</label>
<input class="departureDate form-control" id="departureDate" type="text" placeholder="Departure Date" name="Departure Date" required>
</div>
<div class="form-group" id="tripType">
<label for="tripType">Trip Type:</label>
<div class="col-lg-12">
<div class="col-lg-2">
<input class="radio tripType" id="ReturnTrip" type="radio" name="tripType" value="Return" checked="">Return
</div>
<div class="col-lg-2">
<input class="radio tripType" id="SingleTrip" type="radio" name="tripType" value="One-way">One-way
</div>
<div class="col-lg-8"></div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="return">Return Date:</label>
<input class="returnDate form-control" type="text" id="returnDate" placeholder="Return Date" name="Return Date" required>
</div>
<div class="form-group" id="booking-btn--container">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
JS:
var url = $("#bookingForm").attr("action") + "?";
var urlElements = [];
$("#bookingForm").find('.form-group').each(function(){
urlElements.push($(this).find('.form-control').attr("id") + "=" + $(this).find('.form-control').attr("value") || $(this).find('.form-control').attr("id") + "=" + $(this).find('.form-control').attr("value"));
});
urlElements = urlElements.join("&");
url += urlElements;
console.log(url);
Just fix your name attributes to match your IDs, and use .serialize():
$("form").on("submit", function(event) {
event.preventDefault();
var form = $(this);
var url = form.attr('action') + '?' + form.serialize();
console.log(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" id="bookingForm" action="someaction">
<div class="col-lg-6">
<div class="form-group">
<label for="fromLocation">From:</label>
<select class="select form-control input-lg" id="fromLocation" name="fromLocation" required>
<option value="">From</option>
<option value="ADL">Adelaide</option>
<option value="DRW">Darwin</option>
<option value="MEL">Melbourne</option>
<option value="PER">Perth</option>
</select>
</div>
<div class="form-group">
<label for="departure">Departure Date:</label>
<input class="departureDate form-control" id="departureDate" type="text" placeholder="Departure Date" name="departureDate" required>
</div>
<div class="form-group" id="tripType">
<label for="tripType">Trip Type:</label>
<div class="col-lg-12">
<div class="col-lg-2">
<input class="radio tripType" id="ReturnTrip" type="radio" name="tripType" value="Return" checked="">Return
</div>
<div class="col-lg-2">
<input class="radio tripType" id="SingleTrip" type="radio" name="tripType" value="One-way">One-way
</div>
<div class="col-lg-8"></div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="return">Return Date:</label>
<input class="returnDate form-control" type="text" id="returnDate" placeholder="Return Date" name="returnDate" required>
</div>
<div class="form-group" id="booking-btn--container">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
As a bonus, it will properly URL-encode your values.
Try like this
var $input = $(this).find('.form-control');
urlElements.push($input.attr("id") + "=" + $input.val());

Categories