I made a JQuery function to check for empty required fields inside a closed custom dropdown.
If a required field is empty inside one of the dropdown and if the dropdown is currently closed I want the dropdown to open and if there are no empty values in the required fields I want the dropdown to close.
The problem is that the required fields aren't accessible if the dropdowns are closed and I tried to fix that problem with this function.
For some reason, it only checks for these input fields if the form is submitted at least once and the required fields are opened at least once.
find(':input[required]') doesn't give any output if the dropdown isn't opened at least once, once u open and close the dropdown the function works.
This is the function:
function dropdown_required() {
var required = 0;
$('#visible_fields').find(':input[required]').each(function () {
if (!this.value) {
for (var i = 1; i < 15; i++) {
$('.form_' + i).find(':input[required]').each(function () {
$(this).prop('required', false);
});
}
required++;
}
});
if (required == 0) {
for (var i = 1; i < 15; i++) {
var empty = 0;
$('.form_' + i).find(':input[required]').each(function ()
{
if(!this.value) {
empty++;
}
});
if (empty !== 0) {
if ($(".arrow_" + i).hasClass("rotate_2")) {
$(".arrow_" + i).addClass("rotate_1").removeClass("rotate_2");
$(".form_" + i).fadeToggle();
}
} else if ($(".arrow_" + i).hasClass("rotate_1")) {
$(".arrow_" + i).addClass("rotate_2").removeClass("rotate_1");
$(".form_" + i).fadeToggle();
}
}
}
}
This is the dropdown:
<div id="visible_fields">
//all visible input fields outside of the dropdowns
</div>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="bkr">BKR</label>
<select name="bkr" class="form-control" required>
<option selected hidden></option>
<option value="10">BKR toetsing open</option>
<option value="11">BKR toetsing accoord</option>
<option value="12">Vrijgesteld van BKR toetsing</option>
</select>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="bkr_bestand">BKR bestand</label>
<input type="file" name="bkr_bestand" id="bkr_bestand"
data-default-file=""
class="form-control dropify">
<input type="hidden" name="verwijder_foto" class="verwijder_foto" value="0">
</div>
</div>
</div>
</div>
<div class="form-group">
<input type="hidden" id="input_iframe" name="input_iframe" value="">
<button type="submit" onclick="dropdown_required()"
class="btn btn-primary">Toevoegen </button>
</div>
</form>
</div>
</body>
</html>
Related
I have created a form which can be dynamically changed using the buttons included. These buttons allow for more input fields to be added/removed. The issue is that the input fields created are not posting any data/ Values in those fields not being added to the $POST array on the submit of the form.
The main functions below resposible for adding and removing rows is RemoveRows() and addRows()
What should happen is that on submit all values in the form should be "posted" then I can access all of those fields via $_POST["nameOfField"].
The way I have currently approached this is to create an input fields with the relevant id's and names then append that field to where the "hard coded" fields exists.
From my initial debugging none of the fields that have been added via javascript are in $Post which I have checked via var_dump($_REQUEST);
I have also seen that the nodes that are added are not elements of the form tag even though the nodes are added between the opening and closing tag. This can be seen in the doBeforeSubmit() Function where we can see all elements that are children of the and this never changes as rows are added/removed.
function showPlatforms() {
let nacellesOptions = ["Option1", "option2", "Option3"];
let milOptions = ["Option1", "option2", "Option3"]
let highOptions = ["Option1", "option2", "Option3"]
let entry = document.getElementById("vs")
let platfom = document.getElementById("platform")
if (platform.hasChildNodes()) {
var lastChild = platfom.lastElementChild
while (lastChild) {
platfom.removeChild(lastChild)
lastChild = platform.lastElementChild
}
}
if (entry.value == "Nacelles") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = nacellesOptions[i]
option.innerHTML = nacellesOptions[i]
platform.appendChild(option)
}
} else if (entry.value == "Military") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = milOptions[i]
option.innerHTML = milOptions[i]
platform.appendChild(option)
}
} else {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = highOptions[i]
option.innerHTML = highOptions[i]
platform.appendChild(option)
}
}
}
function formOptions() {
let entry = document.getElementById("type")
if (entry.value == "Engineering MAM") {
document.getElementById("WBS").disabled = false
document.getElementById("Desc").disabled = false
document.getElementById("ProName").disabled = false
} else {
document.getElementById("WBS").disabled = true
document.getElementById("Desc").disabled = true
document.getElementById("ProName").disabled = true
}
}
function formoptions2() {
let entry2 = document.getElementById("organisation")
if (entry2.value == "Aftermarket") {
document.getElementById("COT").disabled = false
document.getElementById("COC").disabled = false
} else {
document.getElementById("COT").disabled = true
document.getElementById("COC").disabled = true
}
}
count = document.getElementById("partNum").childElementCount
function addRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(addRow, count)
count = document.getElementById("partNum").childElementCount
//doBeforeSubmit()
}
function doBeforeSubmit() {
var es = document.getElementById("form").elements;
var l = es.length;
var msgs = [];
for (var idx = 0; idx < l; idx++) {
var e = es[idx];
msgs.push('name=' + e.name + ', type=' + e.type + ', value=' + e.value);
}
alert(msgs.join('\n'));
return false;
}
function addRow(id) {
let col = document.getElementById(id)
var box = document.createElement("INPUT")
box.setAttribute("type", "text")
box.setAttribute("id", id + count)
box.setAttribute("name", id + count)
box.setAttribute("class", "form-control")
col.appendChild(box)
}
function RemoveRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(removeBoxes)
count = document.getElementById("partNum").childElementCount
}
function removeBoxes(item) {
let box = document.getElementById(item)
let last = box.lastChild
box.removeChild(last)
}
function checkData() {
// if all stuff is correct do this:
document.getElementById("submit").disabled = false
// else dont activate the submit button.
}
<form method="post" id="form" action="SubmitMAM.php">
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNo" class="col-2">
<h3>Part Number:</h3>
</div>
<div class="col-2">
<h3>Part Description:</h3>
</div>
<div class="col-1">
<h3>Lead Time:</h3>
</div>
<div class="col-1">
<h3>Quantity:</h3>
</div>
<div class="col-1">
<h3>Date Required:</h3>
</div>
<div class="col-1">
<h3>Unit Cost:</h3>
</div>
<div class="col-2">
<h3>Unit Cost Extension:</h3>
</div>
<div class="col-1">
<h3>Unit Sale Value:</h3>
</div>
<div class="col-1">
<h3>Est Sales Value:</h3>
</div>
</div>
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNum" class="col-2">
<input type="text" id="partNum0" class="form-control" name="partNum0">
</div>
<div id="partDesc" class="col-2">
<input type="text" id="partDesc0" class="form-control" name="partDesc0">
</div>
<div id="leadTime" class="col-1">
<input type="text" id="leadTime0" class="form-control" name="leadTime0">
</div>
<div id="quantity" class="col-1">
<input type="text" id="quanitity0" class="form-control" name="quantity0">
</div>
<div id="dateReq" class="col-1">
<input type="text" id="dateReq0" class="form-control" name="dateReq0">
</div>
<div id="unitCost" class="col-1">
<input type="text" id="unitCost0" class="form-control" name="unitCost0">
</div>
<div id="unitExtention" class="col-2">
<input type="text" id="unitExtention0" class="form-control" name="unitExtention0">
</div>
<div id="unitSaleValue" class="col-1">
<input type="text" id="unitSaleValue0" class="form-control" name="unitSaleValue0">
</div>
<div id="estSalesValue" class="col-1">
<input type="text" id="estSalesValue0" class="form-control" name="estSalesValue0">
</div>
<button onclick="addRows()" class="btn btn-primary" type="button">Add a Product</button>
<button onclick="RemoveRows()" class="btn btn-primary" type="button">Remove Row</button>
<button onclick="checkData()" class="btn btn-primary" type="button">Check Data</button>
<br>
<button type="submit" name="submit" id="submit" class="btn btn-primary" disabled>Submit</button>
</form>
PHP:
<?php
var_dump($_REQUEST)
?>
UPDATE:
The code has been changed to use a php array by adding square brackets into the name which produces the following html:
<input type="text" id="partNum0" class="form-control" name="partNum[]">
<input type="text" id="partNum1" name="partNum[]" class="form-control">
<input type="text" id="partNum2" name="partNum[]" class="form-control">
You just need to use the name property of the input and add [] at the end, as GrumpyCrouton said. PHP parse it as an array, and you can access it as:
$partNum = $_POST["partNum"];
FIXED: It turns out the above code did not have any issues with the logic or the way it should work, in the source code in visual studio the indentation of some of the Divs was off causing the browser to have issues in rendering the form correctly hence why the added boxes were not included in the form and their values not POSTED.
As a heads up to anyone with maybe a similar issue, it pays to have your code neat.
I am trying to do the following:
I have drop down menu with four options in it. When I choose Shipped a text box should enabled. So I tried the following:
<div class="col-md-3">
<select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" <?php if ($dispatch_status == "Uploaded") echo "selected='selected'";?> >Uploaded</option>
<option value="Processing" <?php if ($dispatch_status == "Processing") echo "selected='selected'";?> >Processing</option>
<option value="Dispatched" <?php if ($dispatch_status == "Dispatched") echo "selected='selected'";?> >Dispatched</option>
<option value="Shipped" <?php if ($dispatch_status == "Shipped") echo "selected='selected'";?> >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
Java script:
<head>
<script type="text/javascript">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});
</script>
</head>
Doesn't seem to trigger? I don't see log on console too. What could be wrong here?
Update:
I have pasted the html code here:
https://justpaste.it/6zxwu
Update
Since you've now shared your other code I think I know what you want. You have multiple modals, each with a select list and shipping_notes textbox which should be enabled when the selection is Shipped for that particular modal. I've modified your HTML to get this working.
I've updated your HTML a bit. You have multiple elements with the same ID. HTML IDs should be unique. If you want to target multiple elements it's safer to use class (or data-) attributes. I've added class="order-status" to each select and class="shipping_notes_txt" to each textbox. I've used element.querySelector() and document.querySelectorAll() to select DOM elements.
The snippet below mimics two modals. When the select is updated, it only enables/disabled the textbox within the same form element.
// wait for the DOM to load
document.addEventListener('DOMContentLoaded', function() {
// get all select elements with class=order-status
var selects = document.querySelectorAll('.order-status');
// iterate over all select elements
for (var i = 0; i < selects.length; i++) {
// current element
var element = selects[i];
// add event listener to element
element.addEventListener('change', function()
{
console.log(this.value);
// get the form closest to this element
var form = this.closest('form');
// find the shipping notes textbox inside form and disable/enable
if (this.value == 'Shipped') {
form.querySelector('.shipping_notes_txt').disabled = false;
} else {
form.querySelector('.shipping_notes_txt').disabled = true;
}
});
// default value if status == Shipped: enable textbox
if (element.value == "Shipped")
{
var form = element.closest('form');
form.querySelector('.shipping_notes_txt').disabled = false;
}
}
});
.modal1 {
display:inline-block;
vertical-align:top;
padding: .5em;
padding-bottom:5em;
border: 1px solid black;
}
<div class="modal1">
<h3>First Modal</h3>
<div id="edit1" class="modal fade" role="dialog">
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus1" name= "ostatus">
<option value="Uploaded" selected='selected' >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped">Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes1" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
<div class="modal1">
<h3>Second Modal</h3>
<div id="edit20" class="modal fade" role="dialog" >
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus20" name= "ostatus">
<option value="Uploaded" >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped" selected='selected' >Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes20" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
Add onchange to your <select>
<select class="form-control" id="ostatus" name= "ostatus" onchange = "statuschange()">
And change the JavaScript to :
<script type="text/javascript">
function statuschange(){
var drpDownValue = document.getElementById('ostatus').value;
if (drpDownValue == 'Shipped')
{
document.getElementById('shipping_notes').disabled = false;
}
else
{
document.getElementById('shipping_notes').disabled = true;
}
}
</script>
assuming everything on the server side this works HTML comes first
<div class="col-md-3"> <select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" selected="selected" >Uploaded</option>
<option value="Processing" >Processing</option>
<option value="Dispatched" >Dispatched</option>
<option value="Shipped" >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});
I'm building this form were the user can add input field dynamically by clicking the + sign.
Then the user can remove the previously added input by clicking the - sign.
My problem is when the user removes one field, all fields are removed. I believe it depends on the position of the .field_wrapper.
I've moved the .field_wrapper to various positions but nothing seems to work. Either way the previously added input is not removed or all inputs are removed.
Can someone advise me on what I'm missing.
here is a link to a fiddle
$(document).ready(function() {
var max_fields = 10;
var add_input_button = $('.add_input_button');
var field_wrapper = $('.field_wrapper');
var new_field_html = '<input name="title[]" class="form-control form-item type="text" value="" data-label="title" />-';
var input_count = 1;
//add inputs
$(add_input_button).click(function() {
if (input_count < max_fields) {
input_count++;
$(field_wrapper).append(new_field_html);
}
});
//remove_input
$(field_wrapper).on('click', '.remove_input_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="row field_wrapper">
<label class="col-md-offset-1 col-sm-3 control-label" for="title">Title</label>
<div class="col-md-6 col-sm-9 col-10">
<input id="title" class="form-control form-item required" name="input_title[]" type="text" value="" data-label="title" />
+
</div>
</div>
</form>
The reason is because the parent('div') from the remove button is the div which holds all the content. The simple way to fix this would be to wrap the new input and remove link in its own div.
Also note that add_input_button and field_wrapper already contain jQuery objects, so you don't need to wrap them again. Try this:
$(document).ready(function() {
var max_fields = 10;
var $add_input_button = $('.add_input_button');
var $field_wrapper = $('.field_wrapper');
var new_field_html = '<div><input name="title[]" class="form-control form-item type="text" value="" data-label="title" />-</div>';
var input_count = 1;
//add inputs
$add_input_button.click(function() {
if (input_count < max_fields) {
input_count++;
$field_wrapper.append(new_field_html);
}
});
//remove_input
$field_wrapper.on('click', '.remove_input_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="row field_wrapper">
<label class="col-md-offset-1 col-sm-3 control-label" for="title">Title</label>
<div class="col-md-6 col-sm-9 col-10">
<input id="title" class="form-control form-item required" name="input_title[]" type="text" value="" data-label="title" />
+
</div>
</div>
</form>
I have a HTML form that is for payment status in my panel. In this form if i select payment status Advance Paid Then displays The another input box that i can enter for the advanced paid price. There is another input box is available that is remaining price if i entered the value of advance paid the remaining price should be display the remaining value using java script. If I choose payment status is Null then display total price in remaining price input box and if i choose Paid then display 0 in remaining price input box...all things run good ...but only one thing is not working that is if i enter the value of advance price the remaining price is not displyed. Here is my HTML Code
<div class="col-md-6">
<div class="form-group">
<label>Final Total</label>
<input type="text" value="100" name="total" id="Ftotal" class="form-control" >
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="paymentstatus">Payment Status</label>
<select class="form-control" name="paymentstatus" style="height: 40px;" onchange="yesnoCheck(this);">
<option value=""> ---Select Payment Status---</option>
<option>Advance</option>
<option>Null</option>
<option>Paid</option>
</select>
</div>
</div>
<div class="col-md-6" id="ifYes" style="display: none;">
<div class="form-group">
<label for="advancepaid">Advanced Paid</label>
<input type="text" name="advancedPiad" id="advancedPiad" onKeyUp="remaining()" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="remainingammount">Remaining Ammount</label>
<input type="text" name="remaining" id="remaining" class="form-control remaining" >
</div>
</div>
this is my javascript
function yesnoCheck(that) {
if (that.value == "Advance") {
document.getElementById("ifYes").style.display = "block";
} else {
document.getElementById("ifYes").style.display = "none";
}
if (that.value == "Null") {
a = Number(document.getElementById('Ftotal').value);
document.getElementById('remaining').value = a;
}
if (that.value == "Paid") {
a = 0;
document.getElementById('remaining').value = a;
}
}
function remaining()
{
a = Number(document.getElementById('Ftotal').value);
b = Number(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}
Try
document.getElementsByClassName("remaining")[0].value = c;
document.getElementsByClassName gives you the array of the elements with the class name specified. In your case just set the value of first element.
Try to use js parseInt() method to convert it into integer
function remaining()
{
a=parseInt(document.getElementById('Ftotal').value);
b = parseInt(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}
I've stacked some input text fields, drop downs, radio gruop inside a DIV. Now how do I check if all text fields, radio groups and dropdowns inside this DIV have some value?
I've created a simple mockup in JSFiddle
jQ:
$("#continue_btn").click(function(){
if($('#myForm input:text[value=""]').length > 0){
alert("yes");
} else {
alert("no")
}
}
All you have to do is to wrap your markup in a form element and to each input add attr required
this is pure css.
DEMO ON JSFIDDLE
function highlight(event)
{
event.preventDefault();
alert('Done!!!');
return false;
}
var highlightForm = document.querySelector("form#myForm");
highlightForm.addEventListener('submit',highlight , false);
/**
$("#continue_btn").click(function(){
if($('#myForm input:text[value=""]').length > 0){
alert("yes");
} else {
alert("no")
}
}
*/
<form id="myForm">
<div class="myF">
<div class="input-group">
<span class="input-group-addon"><input type="radio" name="radioGroup" id="radio1" value="option1" required></span>
<input class="form-control" value="Fruits" autofocus required />
</div>
<div class="input-group">
<span class="input-group-addon"><input type="radio" name="radioGroup" id="radio2" value="option2" required></span>
<input class="form-control" value="Vegitables" required/>
</div>
</div>
<div class="input-group">
<span class="input-group-addon quotationFields">City</span><input type="text" class="form-control numericOnly" id="weight_oq" name="weight_oq" required/>
</div>
<div class="input-group onlineQuoteForm">
<span class="input-group-addon">Type </span>
<select class="form-control" id="ptype_oq" required>
<option value="">Please selelct</option>
<option value="Satisfatory">Documents</option>
<option value="val1">OPtion 1</option>
<option value="val2">OPtion 2</option>
</select>
</div>
<input type="submit" value="Continue" id="continue_btn" class="btn btn-primary"/>
</form>
Now you can style it using this
input:required:focus {
}
input:required:hover {
}
/**--------VALID----------*/
input[type="text"]:valid,
input[type="name"]:valid,
input[type="password"]:valid,
input[type="email"]:valid {
}
input[type="text"]:valid:focus,
input[type="name"]:valid:focus,
input[type="password"]:valid:focus,
input[type="email"]:valid:focus {
}
input[type="text"]:valid:hover,
input[type="name"]:valid:hover,
input[type="password"]:valid:hover,
input[type="email"]:valid:hover {
}
/**---------INVALID---------*/
input[type="text"]:invalid,
input[type="name"]:invalid,
input[type="password"]:invalid,
input[type="email"]:invalid {
}
input[type="text"]:invalid:focus,
input[type="name"]:invalid:focus,
input[type="password"]:invalid:focus,
input[type="email"]:invalid:focus {
}
input[type="text"]:invalid:hover,
input[type="name"]:invalid:hover,
input[type="password"]:invalid:hover,
input[type="email"]:invalid:hover {
}
/**---------REQUIRED---------*/
input[type="text"]:required,
input[type="name"]:required,
input[type="password"]:required,
input[type="email"]:required {
}
/**---------OPTIONAL---------*/
input[type="text"]:optional,
input[type="name"]:optional,
input[type="password"]:optional,
input[type="email"]:optional {
}
input[type="text"]:optional:focus,
input[type="name"]:optional:focus,
input[type="password"]:optional:focus,
input[type="email"]:optional:focus {
}
input[type="text"]:optional:hover,
input[type="name"]:optional:hover,
input[type="password"]:optional:hover,
input[type="email"]:optional:hover {
}
The main difficulty here is radio buttons which you need to check separately. Try something like this:
var $form = $('#myForm');
$("#continue_btn").click(function () {
var $radio = $form.find(':radio:checked');
var hasEmpty = $.grep($form.serializeArray(), function(el) {
return !$.trim(el.value);
}).length || $radio.length == 0;
if (hasEmpty) {
alert("yes");
} else {
alert("no")
}
});
Demo: http://jsfiddle.net/tq3jL2d6/9/
Note, that for this demo I improved HTML a little:
wrapped everything with form tag, since you deal with form
added name attributes to all form elements
added placeholder attributes.
You can use this code, here is the link
http://jqueryvalidation.org/files/demo/
And here is the code
view-source:http://jqueryvalidation.org/files/demo/
You can use filter function which can filter every value in form like this
$("#continue_btn").click(function(){
var anyFieldIsEmpty = $("#myForm input,select").filter(function() {
return $.trim(this.value).length === 0;
}).length > 0;
if(anyFieldIsEmpty){
alert("yes");
} else {
alert("no")
}
});
you can select multiple form elements like i have done input,select,textarea etc..
FIDDLE DEMO