Validation for dropdown menu - javascript

This is my first post here, so please no penalty points for me if there is anything unclear with my question. If so, I will edit or add necessary info.
I have an assignment for creating javascript validation method for html input and select, that validates both fields and removes error message after entering details or selecting drop-down option. And, I am having a problem with the second part which I do not seem to be able to find a solution for, and precisely:
1) error message does not disappear when an option from select is chosen (it works for input)
I was trying few things but obviously I do not see my mistakes and I really hope someone could point me in the right direction here.
And here is the code for validation:
var validations = {
req: function(data){
return (data != '' && data.length > 0);
}
}
$(document).ready(function(){
function addError(fname, error){
$('[name=' + fname + ']').after('<span class="validationError"> ' + error + '</span>');
}
function removeError(fname){
$('[name=' + fname + ']').parent('div').find('.validationError').remove();
}
var map = {};
for(var x in validationRules){
var fname = validationRules[x][0];
if(typeof fname == 'undefined') continue;
if(typeof map[fname] == 'undefined') map[fname] = [];
map[fname].push({
'method' : validationRules[x][1],
'error' : validationRules[x][2]
});
};
for(var x in map){
$('[name=' + x + ']').on('keyup', function(){
var fname = $(this).attr('name'),
validators = map[fname];
removeError(fname);
for(var y in validators){
if(typeof validators[y] == 'function') continue;
if(!validations[validators[y].method]($(this).val())) addError(fname, validators[y].error);
}
});
}
$('#send, #insert').on('click', function(ev){
var isOk = true;
$('.validationError').remove();
for(var x in map){
for(var y in map[x]){
if(typeof map[x][y] == 'function' || !$('[name=' + x + ']').is(':visible')) continue;
if(!validations[map[x][y].method]($('[name=' + x + ']').val())){
addError(x, map[x][y].error);
isOk = false;
}
}
};
return isOk;
});
});
and html form:
<form action="form-handler.php" method="post" class="form-contacts">
<div class="row col-sm-12 form-break1">
<div class="col-sm-3 col-lg-3 form-label">Your name</p></div>
<div class="col-sm-6 col-lg-6">
<input class="textInput" type="text" name="Name" value="" placeholder="Name & Surname" maxlength="50" />
</div>
</div>
<div class="row col-sm-12 form-break1">
<div class="col-sm-3 col-lg-3 form-label">Vehicle Make </div>
<div class="col-sm-3 col-lg-3">
<select name="Vehicle">
<option value=""></option>
<option value="Vehicle 1">Vehicle 1</option>
<option value="Vehicle 2">Vehicle 2</option>
</select>
</div>
</div>
<div class="wrapper sendButtons">
<div class="col-sm-3 col-lg-3"><input id="send" type="submit" value="Send Request"></div>
</div>
</form>
And finally, just before closing body tag, validation rules
<script>
var validationRules = [
// section 1
["Name","req","Please enter your full name & surname"],
["Vehicle","req","Select Vehicle"]
]
</script>

Related

Fields Added Via Javascript not posting Data into $POST

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.

On particular javascript function call HTML control's value changes to its default value

I have a form where I need such facility where user input some data in textfield and hits enter that time using jquery it should create new controls like new textfield, dropdown menu, textfield. and it works also, but it has a bug like when user input another data and hits enter that time value of previous controls, dropdown and textfield changes to its default.
Here is my code:
<script type="text/javascript">
function addMbo(value){
var div = document.getElementById('mboTable');
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
event.preventDefault();
var divName = document.getElementById('mboName');
var divState = document.getElementById('mboState');
var divProgress = document.getElementById('mboProgress');
divName.innerHTML = divName.innerHTML + "<input class=form-control type=text name=mboName value='" + value + "' id=mboNamw/>"
divState.innerHTML = divState.innerHTML + "<select class=form-control > <option value=1>In Progress </option><option <value=2>Completed</option><option value=3>Cancled</option></select>"
divProgress.innerHTML = divProgress.innerHTML + "<input class=form-control type=text name=progress id=progress />"
document.getElementById('mboNameInput').value = null;
}
}
</script>
HTML code:
<div class="col-sm-4">
<div class="row">
<div class="col-sm-5">
<b>Objectives</b>
</div>
<div class="col-sm-4">
<b>Status</b>
</div>
<div class="col-sm-3">
<b>Compl. %</b>
</div>
</div>
<div class="row">
<div id="mboTable">
<div id="mboName" class="col-sm-5"></div>
<div id="mboState" class="col-sm-4"></div>
<div id="mboProgress" class="col-sm-3"></div>
</div>
</div>
<div class="row" >
<div class="col-sm-5">
<input type="text" id="mboNameInput" class="form-control " onkeydown="addMbo(this.value)" placeholder="Your MBO...">
</div>
</div>
</div>
here is jsfiddle
When you do innerHTML on any element, it will completely destroy what ever content already there inside the elment.
Rather you should appndChild as shown below,
var divName = document.getElementById('mboName');
var mboName = document.createElement("INPUT");
mboName.setAttribute("type", "text");
mboName.setAttribute("class", "form-control");
divName.appendChild(mboName );
you can do the related changes to above code and make your things work.
See below code to add select dropdown.
var divState = document.getElementById('mboState');
var selectData = [{name:"In Progress",value:"1"},{name:"Completed",value:"2"},{name:"Cancelled",value:"3"}];
var selectList = document.createElement("select");
selectList.class = "form-control";
divState.appendChild(selectList);
for (var i = 0; i < selectData.length; i++) {
var option = document.createElement("option");
option.value = selectData[i].value;
option.text = selectData[i].name;
selectList.appendChild(option);
}

Change value of dropdown with javascript

I'm using codeigniter framework and I have some fields that I want to fill when I check a checkbox (it takes data from other fields).
The thing is I want to fill the dropdown list with the value of an other dropdown list.
Here's the javascript code that I use to fill the fields :
function FillinEmail(info) {
if (info.checked)
{
document.getElementById('adresse_fact').value = document.getElementById('adresse').value;
document.getElementById('npa_fact').value = document.getElementById('npa').value;
document.getElementById('nomprenom_fact').value = document.getElementById('nom').value + ' ' + document.getElementById('prenom').value;
}
else
{
document.getElementById('adresse_fact').value = '';
document.getElementById('npa_fact').value = '';
document.getElementById('nomprenom_fact').value = '';
}
}
And here is how I do my dropdown list with codeigniter :
<div class="form-group">
<label class="col-md-2 control-label" for="id_npa_localite">Localité</label>
<div class="col-md-4">
<?php echo form_dropdown('id_npa_localite', $id_localite, null,'class="form-control"')?>
</div>
</div>
The null value is where I can put a default value, and that's what I would change in the javascript method, but I don't know how to do that in that case, since the other elements are html elements, it was easy to do.
I would give that select an ID, and use innerHTML in your JS. Do it in this manner:
<select id="the_other">
<option>test1</option>
<option>test2</option>
<option>test3</option>
</select>
<input type="checkbox" onchange="FillinEmail(this)">
<div class="form-group">
<label class="col-md-2 control-label" for="id_npa_localite">Localité</label>
<div class="col-md-4">
<?php echo form_dropdown('id_npa_localite', $id_localite, null, 'id="ci_form" class="form-control"') ?>
</div>
</div>
<script>
function FillinEmail(info) {
document.getElementById('ci_form').innerHTML = document.getElementById('the_other').innerHTML;
/*
if (info.checked) {
document.getElementById('adresse_fact').value = document.getElementById('adresse').value;
document.getElementById('npa_fact').value = document.getElementById('npa').value;
document.getElementById('nomprenom_fact').value = document.getElementById('nom').value + ' ' + document.getElementById('prenom').value;
}
else {
document.getElementById('adresse_fact').value = '';
document.getElementById('npa_fact').value = '';
document.getElementById('nomprenom_fact').value = '';
}
*/
}
</script>

Not reading .val() of some inputs

I have the following form:
<div class="col-md-12">
<div class="inLabel go-bottom hvz-street-smaller">
<div class="inLabelDiv">
<input type="text" name="locStreetAddress" id="locStreetAddress" placeholder="Straße" class="hvz-form-control triggerAddress">
<label for="locStreetAddress">Straße</label>
</div>
</div>
<div class="inLabel go-bottom hvz-number-smaller">
<div class="inLabelDiv">
<input type="text" name="locNumber" id="locNumber" placeholder="HNr." class="hvz-form-control triggerAddress">
<label for="locNumber">HNr.</label>
</div>
</div>
</div>
<div class="col-md-12">
<div class="inLabel go-bottom hvz-zip-smaller">
<div class="inLabelDiv">
<input type="text" name="locZip" id="locZip" placeholder="Postleitzahl" class="hvz-form-control triggerPrice triggerAddress" value="">
<label for="locZip">Postleitzahl</label>
</div>
</div>
<div class="inLabel go-bottom hvz-city-smaller">
<div class="inLabelDiv">
<input type="text" name="locCity" id="locCity" placeholder="Stadt" class="hvz-form-control triggerAddress" value="">
<label for="locCity">Stadt</label>
</div>
</div>
<div class="inLabel go-bottom hvz-country-smaller">
<div class="inLabelDiv">
<input type="text" name="locCountry" id="locCountry" placeholder="Land" class="hvz-form-control triggerAddress" value="Deutschland">
<label for="locCountry">Land</label>
</div>
</div>
</div>
For each .triggerAddressinput I do this:
$(document).on('change', '.triggerAddress', function (event) {
var street = $('#locStreetAddress').val();
var number = $('#locNumber').val();
var zip = $('#locZip').val();
var city = $('#locCity').val();
var country= $('#locCountry').val();
var address = street + ' ' + number + ', ' + zip + ' ' + city + ', ' + country;
if(street !== '' && number !== '' && zip !== '' && city !== '' && country !== ''){
//..DO STUFF
}else{
console.log(address);
}
});
Unfortunatley, var street and var number never get any value? Doing console.log(street) or console.log($('#locStreetAddress').val()) returns a blank line for street and number.
All the other fields work as intended.
What am I missing?
//EDIT
Final Edit / Cleanup
It is an issue with featherlight.js I am using: https://github.com/noelboss/featherlight/issues/122
For future reference: To update/read inputs properly, make persist: true and everything is working as intended.
change to input type="text" acts more like blur
You can use input,keypress,keyup,paste
check this jsfiddle
EDIT
Check this line
if(street !== '' && number !== '' && zip !== '' && city !== '' && country !== '')
You are using && so if loop will execute when none of them are empty, otherwise else loop
Check this second jsfiddle

Knockout observable not getting bound

I am using a form for editing purposes.The Taxonomy Code gets populated when the form is getting loaded.The fields are bound to knockout observables in HTML using the data-bind attribute.The only issue I am facing is this particular field(Taxonomy Code) is NULL when the data is sent to the controller.
The HTML is
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Certification:</label>
<div class="col-sm-6">
<select class="form-control" id="certification" name="certification" data-bind="value:certification,options:certificationArray, optionsCaption: 'Select a Certification'">
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Specialization:</label>
<div class="col-sm-6">
<select class="form-control" id="specialization" name="specialization" data-bind="value:specialization,options:specializationArray, optionsCaption: 'Select a Specialization'"></select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Taxonomy Code:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Taxonomy code" id="taxonomyCode" name="taxonomyCode" data-bind="textInput: taxonomyCode,valueUpdate: 'input'" disabled="disabled">
</div>
</div>
JavaScript is
var provider = function() {
var self = this;
if ((providerEditInfo.Certification == "M.D.") || (providerEditInfo.Certification == "M.B.B.S")) {
specialities = ["Dermatology", "Hematology", "Neurology"];
} else if ((providerEditInfo.Certification == "R.N.") || (providerEditInfo.Certification == "M.S.N.")) {
specialities = ["Pediatric Nursing", "Critical Care Nursing", "Occupational Health Nursing"];
}
self.certificationArray = ko.observableArray(["M.B.B.S", "M.D.", "R.N.", "M.S.N."]);
self.certification = ko.observable(providerEditInfo.Certification);
self.specializationArray = ko.observableArray(specialities);
self.specialization = ko.observable(providerEditInfo.Specialization);
self.taxonomyCode = ko.observable(providerEditInfo.TaxonomyCode);
self.certification.subscribe(function(val) {
self.specializationArray([]);
if (val == "M.D." || val == "M.B.B.S") {
self.specializationArray(["Dermatology", "Hematology", "Neurology"])
} else if (val == "R.N." || val == "M.S.N.") {
self.specializationArray(["Pediatric Nursing", "Critical Care Nursing", "Occupational Health Nursing"])
} else {
self.specializationArray([]);
}
});
self.specialization.subscribe(function(val) {
self.taxonomyCode("");
if (val == "Dermatology")
self.taxonomyCode("207N00000X");
else if (val == "Hematology")
self.taxonomyCode("207RH0000X");
else if (val == "Neurology")
self.taxonomyCode("2084N0400X");
else if (val == "Pediatric Nursing")
self.taxonomyCode("363LP0200X");
else if (val == "Critical Care Nursing")
self.taxonomyCode("363LC0200X");
else if (val == "Occupational Health Nursing")
self.taxonomyCode("363LX0106X");
});
};
$(document).ready(function() {
ko.applyBindings(new provider());
});
I have added only minimal code.Could someone please tell me why the taxonomy field is null.Please refer the attached images.
Most browsers do not submit the values of disabled fields. If you want the value to be sent to the server you need figure out a different way to prevent the user from editing the field.

Categories