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.
Related
I have this logic that is in a form that some users are able to process without selecting a source. Is there a better way to do this logic so it will not fail I am unable to get it to fail so I am very limited.
html
<div id="sources">
<label id="lblSources" class="control-label">* Source</label>
<label id="lblSourcesError" class="pl-4 text-danger" style="display:none">At least one 'Source' must be selected</label>
<input type="checkbox" value=#item.Value name="chkProduct" />
</div>
Js
var checked_sourcecheckboxes = $("#sources input[type=checkbox]:checked");
if (checked_sourcecheckboxes.length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
}
else {
$("#lblSourcesError").hide();
}
Consider the following example.
$(function() {
var checked_sourcecheckboxes = $("#sources input[type=checkbox]");
if (checked_sourcecheckboxes.filter(":checked").length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
} else {
$("#lblSourcesError").hide();
}
checked_sourcecheckboxes.change(function() {
if (checked_sourcecheckboxes.filter(":checked").length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
} else {
$("#lblSourcesError").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sources">
<label id="lblSources" class="control-label">* Source</label>
<label id="lblSourcesError" class="pl-4 text-danger" style="display:none">At least one 'Source' must be selected</label>
<input type="checkbox" value=#item.Value name="chkProduct" />
</div>
This checks the status when the page loads and whenever the checkbox is changed.
I am created the select box to choose the option, my options have condition to hide and show the input fields. My problem is how to write if else logic to check the $category_id value to show and hide in the input div in the backend page. Hope someone can guide me how to solve it. Thanks.
Below is my coding:
Frontend page:
<div class="form-group">
<label for="cp1" class="control-label col-lg-4">Move to Sub Folder/New Category<span style="color:red;"> *</span></label>
<div class="col-lg-3">
<select class="form-control blank" id="parentid" name="parentid" title="parentid">
<option>Please Select</option>
<option value="0">New Category</option>
<?php
$sql_incharge = 'select * from filing_code_management where status=1 order by id';
$arr_incharge = db_conn_select($sql_incharge);
foreach ($arr_incharge as $rs_incharge) {
$folder_location = $rs_incharge['folder_location'];
$category_id= $rs_incharge['category_id'];
echo '<option value="' . $rs_incharge['id'] . '">' . $rs_incharge['name'] . '</option>';
}
?>
</select>
<!--<input type="text" class="form-control blank" id="parentid" name="parentid" title="parentid" onblur="capitalize(this.id, this.value);">-->
</div>
</div>
<div class="form-group" id="show_hide_fc">
<label for="cp1" class="control-label col-lg-4">Function Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_code" name="function_code" title="function_code">
</div>
</div>
<div class="form-group" id="show_hide_fn">
<label for="cp1" class="control-label col-lg-4">Function Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_name" name="function_name" title="function_name">
</div>
</div>
<div class="form-group" id="show_hide_ac">
<label for="cp1" class="control-label col-lg-4">Activity Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_code" name="activity_code" title="activity_code">
</div>
</div>
<div class="form-group" id="show_hide_an">
<label for="cp1" class="control-label col-lg-4">Activity Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_name" name="activity_name" title="activity_name">
</div>
</div>
Backend page:
<?php
$parentid = $_POST['parentid'];
$sql5 = 'select folder_location,name,category_id from filing_code_management where id='. $parentid;
$arr_sql5 = db_conn_select($sql5);
foreach ($arr_sql5 as $rs_sql5) {
$sub_category_name = $rs_sql5['name'];
$folder_location = $rs_sql5['folder_location'];
$categoryID= $rs_sql5['category_id'];
}
$show_hide_fc = $_POST['show_hide_fc'];
$show_hide_fn = $_POST['show_hide_fn'];
$show_hide_ac = $_POST['show_hide_ac'];
$show_hide_an = $_POST['show_hide_an'];
if ($category_id == '0') {
// $show_hide_fc will show
// $show_hide_fn will show
// $show_hide_ac style display = 'none';
// $show_hide_an style display = 'none';
} else if ($category_id == '1') {
// $show_hide_fc style display = 'none';
// $show_hide_fn style display = 'none';
// $show_hide_ac will show
// $show_hide_an will show
} else if ($category_id == '2') {
// $show_hide_fc will show
// $show_hide_fn will show
// $show_hide_ac will show
// $show_hide_an will show
}
?>
For example if I choose the $category_id number is 1 it will show two input div, like below the sample picture.
If I choose the $category_id number is 2 it will show 4 input div, like below the sample picture.
There are two ways of solving this, depending on the size of your dataset. If there are not too many records with a $parentid (from the backend code, also please read up on SQL injection, you are inserting user data into a SQL query), you can just check the options ahead of submitting (when the form page is requested), and show or hide the items with JS depending on the option selected. This has the advantage of having no additional requests.
If you have a lot of entries in the filing_code_managment table then you should not check them all in advance, as this would be very resource intensive, and 90% of the work done will never be seen by anyone. In this case you can use AJAX to check with the server, and check what fields will be shown or hidden depending on the result. This solution has the advantage of checking only the options that are used, but it introduces latency, as the request needs to be completed before the user can fill the next fields.
Update with example for first option
Example for first option in your front end code:
<div class="form-group">
<label for="cp1" class="control-label col-lg-4">Move to Sub Folder/New Category<span
style="color:red;"> *</span></label>
<div class="col-lg-3">
<select class="form-control blank" id="parentid" name="parentid" title="parentid">
<option >Please Select</option>
<option value="0">New Category</option>
<?php
$sql_incharge = 'SELECT * FROM filing_code_management WHERE status = 1 ORDER BY id';
$arr_incharge = db_conn_select($sql_incharge);
// Test array, I don't have your database
// $arr_incharge = [
// ['category_id' => '0', 'id' => '0', 'name' => 'Nummer 0'],
// ['category_id' => '1', 'id' => '1', 'name' => 'Nummer 1'],
// ['category_id' => '2', 'id' => '2', 'name' => 'Nummer 2']
// ];
$show = [];
foreach ($arr_incharge as $rs_incharge) {
$folder_location = $rs_incharge['folder_location'];
$category_id = $rs_incharge['category_id'];
echo '<option value="' . $rs_incharge['id'] . '">' . $rs_incharge['name'] . '</option>';
// Added
switch ($category_id) {
case '0':
$fc = true;
$fn = true;
$ac = false;
$an = false;
break;
case '1':
$fc = false;
$fn = false;
$ac = true;
$an = true;
break;
case '2':
$fc = true;
$fn = true;
$ac = true;
$an = true;
break;
}
// Save in one big array, to use in JS later
$show[$rs_incharge['id']]['show_fc'] = $fc;
$show[$rs_incharge['id']]['show_fn'] = $fn;
$show[$rs_incharge['id']]['show_ac'] = $ac;
$show[$rs_incharge['id']]['show_an'] = $an;
}
?>
</select>
<!--<input type="text" class="form-control blank" id="parentid" name="parentid" title="parentid" onblur="capitalize(this.id, this.value);">-->
</div>
</div>
<div class="form-group" id="show_hide_fc">
<label for="function_code" class="control-label col-lg-4">Function Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_code" name="function_code" title="function_code">
</div>
</div>
<div class="form-group" id="show_hide_fn">
<label for="function_name" class="control-label col-lg-4">Function Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_name" name="function_name" title="function_name">
</div>
</div>
<div class="form-group" id="show_hide_ac">
<label for="activity_code" class="control-label col-lg-4">Activity Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_code" name="activity_code" title="activity_code">
</div>
</div>
<div class="form-group" id="show_hide_an">
<label for="activity_name" class="control-label col-lg-4">Activity Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_name" name="activity_name" title="activity_name">
</div>
</div>
<script>
// Added, add this after the inputs
const fc = document.getElementById('function_code');
const fn = document.getElementById('function_name');
const ac = document.getElementById('activity_code');
const an = document.getElementById('activity_name');
const select = document.getElementById('parentid');
const show = JSON.parse('<?= json_encode($show) ?>');
updateVisibility();
select.addEventListener('change', function () {
updateVisibility();
});
function updateVisibility() {
const currentOption = show[select.options[select.selectedIndex].value];
if (typeof currentOption !== 'undefined' && currentOption !== null) {
if (currentOption.show_fc) {
fc.style.display = '';
} else {
fc.style.display = 'none';
}
if (currentOption.show_fn) {
fn.style.display = '';
} else {
fn.style.display = 'none';
}
if (currentOption.show_ac) {
ac.style.display = '';
} else {
ac.style.display = 'none';
}
if (currentOption.show_an) {
an.style.display = '';
} else {
an.style.display = 'none';
}
} else {
// Hide everything when no known option is selected
fc.style.display = 'none';
fn.style.display = 'none';
ac.style.display = 'none';
an.style.display = 'none';
}
}
</script>
I have 4 text boxes. I want to validate according to bewlow criteria:-
1). IF first textbox value not blank and anotherthree are blank than addclass error on that blank textbox.
2). If second textbox value not blank and 1st, 3rd and 4th textbox valueare blank than addclass error on that blank textbox.
3). If first two textbox value are not blank and another textox value are blank than addClass error on that blank textbox.
4). If First and third textbox value are not blank and 2nd and 4th textbox value are blank than addclass error on that blank textbox.
5).If 3 textboxs value are not blank and one textbox value blank than addclass error on that blank textbox.
This is My jquery validation code:-
$(".submit_data").click(function(){
input1 = $("#data1").val();
input2 = $("#data2").val();
input3= $("#data3").val();
input4= $("#data4").val();
if(input1 == "" && input2 == "" && input3 == "" && input3 == "")
{
$(".data-form").addClass('required');
$(".data-form").addClass('error');
$(".new-data-form").addClass('required');
$(".new-data-form").addClass('error');
}
if( input1 != "" && input2 == "" && input3 == "" && input3 == "" )
{
$("#data2").addClass("error");
$("#data3").addClass("error");
$("#data4").addClass("error");
return false;
}
});
HTML:-
<div id="painting_form" class="painting-form-wrap">
<div class="form-group">
<label class="col-sm-2 control-label">Input 1</label>
<div class="col-sm-10">
<input type="text" name="data1" value="" id="data1" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 2</label>
<div class="col-sm-10">
<input type="text" name="data2" value="data2" id="input-ceilheight" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 3</label>
<div class="col-sm-10">
<input type="text" name="data3" value="" id="data3" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 4</label>
<div class="col-sm-10">
<input type="text" name="data4" value="" id="data4" class="form-control painting-form1">
</div>
</div>
</div>
You can loop through all input boxes and check if any of the input field is filled with value the add error class to all other empty input boxes.
Try this:
$(document).ready(function() {
$(".submit_data").click(function(){
flag = 0; // check if eny input box is filled with value or not
$("input[type=text]").each(function() {
if($(this).val() != '') {
flag = 1; // set flag one if any of the inputbox has value entered
}
});
if(flag == 0) { // if flag is 0 means all input are empty then remove error class from all inputs
$("input[type=text]").each(function() {
$(this).removeClass('required');
$(this).removeClass('error');
});
}
if(flag == 1) { // if any of the input box is filled with value
$("input[type=text]").each(function() {
if($(this).val() == '') {
$(this).addClass('required'); // add error class to empty inputboxes
$(this).addClass('error');
} else {
$(this).removeClass('error'); // remove error class if inputbox has value
}
});
}
return false;
});
});
Use jquery validation plugin for this.
It's quickly and easy to implement.
Will be something like this
$(form).validate()
If you want to add some rules, like minlength/maxlength and so on .
// Try this
$(form).validate(rules:{
inputname: {
minlength: 8
}
})
I am trying to debug a function call in my JSP program and really confused on the ordering of how things worked. I am using NetBeans. When I run the project in debug mode, it goes into my '$("#searchEFT").mouseup(function ()' function and trace through all of it. 'searchEFT' is a button that I am using to access my servlet. When I process the page and then click the 'searchEFT' button, it hits the function call based on getting the right alert but doesn't trace in the debug. Why is it doing that? Is the first call of the function on load setting up the check when the user does the mouseclick?
This function is outside of the '$(document).ready(function ()' at the top and the function call is after the button declaration in the JSP.
EDIT: here is the JSP code:
<head>
<script>
$(document).ready(function ()
{
$(function ()
{
$("#CMDCreationDate").datepicker({
dateFormat: "yy-mm-dd"
});
});
}) ;
window.onbeforeunload = confirmExit;
function confirmExit()
{
alert("Alert-- leaving this page.");
}
function numbersonly(myfield, e, dec) {
//function to check that only numeric values are entered
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == ".")) {
myfield.form.elements[dec].focus();
return false;
} else
return false;
}
</script>
</head>
<body>
<header>
<?audit suppress oracle.ide.xml.validation-error?>
<div class="floatL appTTL">SAMS - EFT Schedule Number Search/Update Screen</div>
<div id="navWrap">
<nav class="floatR">
<ul>
<li>
Home
</li>
<li>
Search
</li>
<li>
Help
</li>
<li>
Help
</li>
</ul>
</nav>
</div>
<div class="clear"></div>
</header>
<main class="mainWrapper">
<form id="formID" method="POST" action="EFTscreen?action=searchEFT" >
<div class="commandcontainer">
<div id="divBox">
<h1 class="formTTL">Please Enter Schedule Number/Contract Year or either Schedule
Status/Creation Date value</h1>
<label class="labelTTL">Schedule Number</label>
<label class="labelTTL3">Contract Year</label>
<label class="labelTTL3">Status</label>
<label class="labelTTL">Creation Date</label>
<br/>
<input id="CMDScheduleNumber" name="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
value="${ScheduleNum}" onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" name="CMDContractYear" type="number" class="textsmall" maxlength="4"
value="${ContractYear}" onKeyPress="return numbersonly(this, event)"/>
<select size="1" id="CMDSchedStatus" name="CMDSchedStatus" class="combosmall">
<c:forEach items="${statusList}" var="current">
<option value="${current}"
<c:if test="${current == Status}"> selected="selected"</c:if>
>${current}</option>
</c:forEach>
</select>
<input id="CMDCreationDate" name="CMDCreationDate" type="text" class="textsmall"
value="${CreationDate}" maxlength="10"/>
<br/>
<button id="searchEFT" class="btn smBtn">Search</button>
</div>
<div id="divButton">
<button id="searchMEFTS" type="submit" formaction="EFTscreen?action=searchMEFTS&screen=mainEFT"
class="btn midBtn">Update Schedule Status</button>
<button id="clearMenu" type="submit" formaction="EFTscreen?action=clearMenu"
class="btn midBtn Space">Return to Menu</button>
</div>
<div id="clear"></div>
</div>
<article class="divBoxdet">
<fmt:formatNumber var="trdettotal" value="${detResults.getTOTAL_AMOUNT()}" pattern="$##,###,##0.00"/>
<label class="labelTTLdet floatL">
Schedule Number
<input id="txtScheduleNumber" type="number" class="textdet"
value="${detResults.getSCHEDULE_NUMBER()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Contract Year
<input id="txtContractYear" type="number" class="textdet"
value="${detResults.getEFT_CONTRACT_YEAR()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Date Created
<input id="txtCreationDate" type="text" class="textdet"
value="${detResults.getCREATION_DATE()}" readonly/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Num of Records
<input id="txtNumRecords" type="number" class="textdet"
value="${detResults.getNUM_OF_PAY_RECORDS()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Status
<br/>
<input id="txtStatus" type="text" class="textdet"
value="${detResults.getSTATUS()}" maxlength="2"/>
</label>
<label class="labelTTLdet floatL">
Status Date
<input id="txtStatusDate" type="text" class="textdet"
value="${detResults.getSTATUS_DATE()}" maxlength="10"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Schedule Total
<input id="txtScheduleTotal"
type="text" class="textdet" value="${trdettotal}" readonly/>
</label>
<label class="labelTTLdet floatL">
Schedule Post Date
<input id="txtPostDate" type="text" class="textdet"
value="${detResults.getSCHEDULE_POST_DATE()}" maxlength="10"/>
</label>
<label class="labelTTLdet floatL">
Reel Number
<input id="txtReelNumber" type="text" class="textdet"
value="${detResults.getREEL_NUMBER()}" maxlength="8"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<button id="pullMEFTD"
class="btn largeBtn Space floatL">Update Schedule Payment Status</button>
<script>
$("#searchEFT").mouseup(function ()
{
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
var schedLen = Cmd_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Cmd_Contract_Year = $('#CMDContractYear').val();
var yearLen = Cmd_Contract_Year.length;
//var Cmd_Status = document.getElementById("CMDSchedStatus").value;
var Cmd_Status = $('#CMDSchedStatus').val();
var statStr = Cmd_Status.replace(/\s/g, "");
var statLen = statStr.length;
//var Cmd_Creation_Date = document.getElementById("CMDCreationDate").value;
var Cmd_Creation_Date = $('#CMDCreationDate').val();
var createLen = Cmd_Creation_Date.length;
if ((schedLen > 0 && yearLen === 0) || (schedLen === 0 && yearLen > 0))
{
alert("Schedule Number and EFT Contract Year must be both populated");
}
;
if ((statLen === 0) && (createLen === 0) && (schedLen === 0) && (yearLen === 0))
{
var r = confirm("Are you sure you want to pull all EFT schedule numbers?");
if (r === false)
{
alert("Please enter information in any of the command line fields");
return false;
}
else
{
$('#formID').submit();
}
} ;
});
$("#pullMEFTS").mouseup(function ()
{
var Det_Sched_Number = $('#txtScheduleNumber').val();
var detschedLen = Det_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Det_Contract_Year = $('#txtContractYear').val();
var detyearLen = Det.length;
var Det_Status = $('#txtStatus').val();
if (detschedLen > 0)
{
alert("Schedule Number not found. Please investigate");
}
;
if ( holdStatus.matches("RP") ||
holdStatus.matches("VP") ||
holdStatus.matches("CP") )
{
alert("User can only update schedule number in NP status");
}
});
</script>
</article>
</form>
</main>
</body>
Thanks
The line:
$("#searchEFT").mouseup(function ()
is the function call that sets the mouseup handler; it is not the mouseup handler itself.
If you want to break inside the mouseup handler then you need to set a breakpoint somewhere inside the handler function itself, e.g.,
// First executable line of the mouseup handler
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
Unrelated, but I would break up the handler function into much smaller pieces, roughly:
function getFormData() {
return {
number: $('#CMDScheduleNumber').val().trim(),
year: $('#CMDContractYear').val().trim(),
status: $('#CMDSchedStatus').val().replace(/\s/g, '').trim(),
date: $('#CMDCreationDate').val().trim()
};
}
function invalidNumberAndYear(formData) {
return ((formData.number !== '') && (formData.year === '')) ||
((formData.year !== '') && (formData.number === ''));
}
function isPullAll(formData) {
return formData.number === '' &&
formData.year === '' &&
formData.status === '' &&
formData.date === '';
}
function searchEftMouseup(e) {
e.preventDefault();
var formData = getFormData();
if (invalidNumberAndYear(formData)) {
alert('Schedule Number and EFT Contract Year must be both populated');
return;
}
if (isPullAll(formData)) {
if (confirm('Are you sure you want to pull all EFT schedule numbers?')) {
$('#formID').submit();
} else {
alert('Please enter information in any of the command line fields');
}
}
}
$('#searchEFT').on('mouseup', searchEftMouseup);
This allows small stuff to be thought about easily, and begins to reveal your validation needs, and suggests a shape for your remaining code.
(Most of which, btw, was not relevant to the question–it's good to post only the minimum amount necessary to help people understand the issue :)
I'm trying to use form validation using JavaScript, however I don't seem to get any response, not even an alert even though it's there.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="2013.php" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
</html>
use === or == for condition checking in javascript.
if(document.getElementById('name').value === ""){
alert("enter something valid");
return false;
}
You have to use == for comparison.= is used for assigment
if(document.getElementById('name').value == ""){
alert("enter something valid");
return false;
}
Working Demo
Here Your issue is regarding if condition only! You must use == OR === in JavaScript for comparison.
Below is corrected script!
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
If you remove Or avoid return false, form will postback Even if Validation fails! So, return false means, exiting from function after if is must, and which is missed out in another answer!!
You are using = that is assignment operator, use == comparison operator that's work fine
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
I can't believe I've never realised this until now, although if you attach your Javascript to the form submission event, instead of the button submit event; the normal browser verification works (ie. input[type="email], required="required", etc.).
Works in Firefox & Chrome.
// jQuery example attaching to a form with the ID form
$(document).on("submit", "#form", function(e) {
e.preventDefault();
console.log ("Submitted! Now serialise your form and AJAX submit here...");
})
I have done a better way to do form validation using bootstrap. You can take a look at my codepen http://codepen.io/abhilashn/pen/bgpGRw
var g_UnFocusElementStyle = "";
var g_FocusBackColor = "#FFC";
var g_reEmail = /^[\w\.=-]+\#[\w\.-]+.[a-z]{2,4}$/;
var g_reCell = /^\d{10}$/;
var g_invalidFields = 0;
function initFormElements(sValidElems) {
var inputElems = document.getElementsByTagName('textarea');
for(var i = 0; i < inputElems.length; i++) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
/* Add the code for the input elements */
inputElems = document.getElementsByTagName('input');
for(var i = 0; i < inputElems.length; i++) {
if(sValidElems.indexOf(inputElems[i].getAttribute('type') != -1)) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
}
/* submit handler */
com_abhi.EVENTS.addEventHandler(document.getElementById('form1'), 'submit' , validateAllfields, false);
/* Add the default focus handler */
document.getElementsByTagName('input')[0].focus();
/* Add the event handlers for validation */
com_abhi.EVENTS.addEventHandler(document.forms[0].firstName, 'blur', validateFirstName, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].email, 'blur', validateEmailAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].address, 'blur', validateAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].cellPhone, 'blur', validateCellPhone, false);
}
function highlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = g_FocusBackColor;
}
}
function unHightlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = "";
}
}
function validateAddress() {
var formField = document.getElementById('address');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpAddress');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "Please enter your address";
}
return ok;
}
}
function validateFirstName() {
var formField = document.getElementById('firstName');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpfirstName');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "Please enter your first name";
}
return ok;
}
}
function validateEmailAddress() {
var formField = document.getElementById('email');
var ok = (formField.value.length != 0 && g_reEmail.test(formField.value));
var grpEle = document.getElementById('grpEmail');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "Please enter your valid email id";
}
}
return ok;
}
function validateCellPhone() {
var formField = document.getElementById('cellPhone');
var ok = (formField.value.length != 0 && g_reCell.test(formField.value));
var grpEle = document.getElementById('grpCellPhone');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "Please enter your valid mobile number";
}
}
return ok;
}
function validateAllfields(e) {
/* Need to do it this way to make sure all the functions execute */
var bOK = validateFirstName();
bOK &= validateEmailAddress();
bOK &= validateCellPhone();
bOK &= validateAddress();
if(!bOK) {
alert("The fields that are marked bold and red are required. Please supply valid\n values for these fields before sending.");
com_abhi.EVENTS.preventDefault(e);
}
}
com_abhi.EVENTS.addEventHandler(window, "load", function() { initFormElements("text"); }, false);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<h1 class="text-center">Interactive form validation using bootstrap</h1>
<form id="form1" action="" method="post" name="form1" class="form-horizontal" role="form" style="margin:10px 0 10px 0">
<div id="grpfirstName" class="form-group">
<label for="firstName" class="col-sm-2 control-label"><span class="text-danger">* </span>First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" placeholder="Enter first name">
<span id="firstNameIcon" class=""></span>
<div id="firstNameErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastName" placeholder="Enter last name">
</div>
</div>
<div id="grpEmail" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Email </label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter email">
<span id="EmailIcon" class=""></span>
<div id="emailErrorMsg" class="text-danger"></div>
</div>
</div>
<div id="grpCellPhone" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Cell Phone </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="cellPhone" placeholder="Enter Mobile number">
<span id="cellPhoneIcon" class=""></span>
<div id="cellPhoneErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group" id="grpAddress">
<label for="address" class="col-sm-2 control-label"><span class="text-danger">* </span>Address </label>
<div class="col-sm-10">
<textarea id="address" class="form-control"></textarea>
<span id="addressIcon" class=""></span>
<div id="addressErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
</div> <!-- End of row -->
</div> <!-- End of container -->
Please check my codepen to better understand code.