I have City and Building fields in my form. Before user submits the form I need to check if building already exist in selected city. Building number can be the same since building with the same number can belong to different city. I want to prevent same building numbers that belong to same city. In order to accomplish this I have to send City+Building concatenated value to the server and check if that value exist in database table. I'm trying to find good solution for this problem. So far I used focus/blur function for this purpose. If user clicks on the Building input field once finished entering value, on blur I will send an ajax request to the server and return true or false. In this case that is a little different, before I send request I have to make sure that City field has entered value. Here is example of my f
$("#frm_building").focus(function() {
var submitBtn = $(this).closest("form").find(":submit").prop("disabled", true), //Disable submit button on field focus.
}).blur(function() {
var fldObj = $(this),
frmMessage = $(this).closest("form").find(".message-submit"),
submitBtn = $(this).closest("form").find(":submit"),
distVal = $("");
if (String(fldObj.val()) && String(fldObj.val()) !== String(fldObj.attr("data-current"))) {
//if (obj.RESULT === true) { // This will be the result returned after ajax call
if(1===1)
fldObj.get(0).setCustomValidity("");
} else {
fldObj.get(0).setCustomValidity("Building already exists for that City.");
}
submitBtn.prop("disabled", false);
} else {
fldObj.get(0).setCustomValidity("");
submitBtn.prop("disabled", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmBuilding" id="frmBuilding">
<div class="form-group">
<label class="control-label" for="City"><span class="label label-primary">City:</span></label>
<select class="form-control" name="frm_city" id="frm_city" required>
<option value="">--Choose City--</option>
<option value="1003">New York</option>
<option value="2341">Chicago</option>
<option value="4343">Miami</option>
<option value="7865">San Francisco</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="Building"><span class="label label-primary">Building:</span></label>
<input type="text" class="form-control check-value" name="frm_building" id="frm_building" data-current="" data-fldname="building" maxlength="4" pattern="[0-9]{4}$" title="Number field requires 4 digits" placeholder="Select City first then enter Building number. Example: 1108"
required>
</div>
</form>
In code above if user first entered Building and City is blank my code won't send request to the server on blur. Then if user tries to submit the form they will get the message City field is required. Let's say they enter City, Building will remain the same as they originally entered. In that case on blur is never triggered and request won't be sent. I'm wondering how I can prevent this to happen, is there a way to prevent user entering Building if City field is empty? Also I have to consider the case when user want to update the record. If they click edit and form gets populated that functionality should work and populate both fields without Building being disabled. I hope this part make sense. Originally I have tried setting Building with attribute disabled and setting on change function on the City field. That worked fine until I discovered the issue with edit situation. If anyone knows a good way to solve this situation please let me know.
is there a way to prevent user entering Building if City field is empty?
When focus is on Buildings you can move focus on City if this field is empty.
$("#frm_building").on('focus', function (e) {
if ($('#frm_city').val().length==0) {
$('#frm_city').focus();
}
});
$("#frm_building").on('focus', function (e) {
if ($('#frm_city').val().length==0) {
$('#frm_city').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmBuilding" id="frmBuilding">
<div class="form-group">
<label class="control-label" for="frm_city"><span class="label label-primary">City:</span></label>
<select class="form-control" name="frm_city" id="frm_city" required>
<option value="">--Choose City--</option>
<option value="1003">New York</option>
<option value="2341">Chicago</option>
<option value="4343">Miami</option>
<option value="7865">San Francisco</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="frm_building"><span class="label label-primary">Building:</span></label>
<input type="text" class="form-control check-value" name="frm_building" id="frm_building" data-current=""
data-fldname="building" maxlength="4" pattern="[0-9]{4}$" title="Number field requires 4 digits"
placeholder="Select City first then enter Building number. Example: 1108"
required>
</div>
<input type="submit" value="submit">
</form>
Related
Having an odd issue where my javascript doesn't fire off correctly on a drop down item when the field is empty (when it should) and then cancels further items after it from being validated all together. When I pop open the browser console, there error I get is "Uncaught TypeError: Cannot read property 'value' of undefined" and it leads directly to the end of the "if" statement in my code. Unsure where I'm going wrong here, I have several identical lines of JS for number and text input fields that work fine, but this one is causing me grief.
There's quite a bit too it, but here's the HTML for that specific part:
<div id="countryRow" class="col-xl-6 justify-content-xl-center">
<form name="countryForm" onsubmit="return validateCountry()" method="post">
<h5> </h5>
<input type="text" list="Ctry" name="selectCountry" style="width:550px;" value="">
<datalist id="Ctry">
<option value="United States">
<option value="Canada">
</datalist>
<h5>Country</h5>
</form>
</div>
and here is the Javascript:
function validateCountry() {
valid = true;
if (document.countryForm.countryInput.value == "") {
shipMessage.innerHTML = "This field is required";
document.getElementById("countryRow").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
It's just a small mistake. You have incorrectly named your form input in the Javascript code. And the shipMessage field is not defined in this current example. In the below code I have fixed these small mistakes:
HTML
<div id="countryRow" class="col-xl-6 justify-content-xl-center">
<form name="countryForm" onsubmit="return validateCountry()" method="post">
<h5> </h5>
<input type="text" list="Ctry" name="selectCountry" style="width:550px;" value="">
<datalist id="Ctry">
<option value="United States">
<option value="Canada">
</datalist>
<p id="shipMessage"></p> <!-- Added this shipMessage p element to show the error -->
<h5>Country</h5>
<button type="submit">Submit</button>
</form>
</div>
Javascript:
function validateCountry() {
valid = true;
// since the name of the field is "selectCountry", so I have replaced "countryInput" with "selectCountry"
if (document.countryForm.selectCountry.value == "") {
const shipMessage = document.getElementById("shipMessage"); // defining the shipMessage variable
shipMessage.innerHTML = "This field is required";
document.getElementById("countryRow").style.backgroundColor = "#fff7f7";
valid = false;
}
return valid;
}
I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]
I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.
I have a form that may only be one page or may be two pages depending on whether it is a single individual or two people applying. What I am doing right now is enabling a link that allows the user to get to the next group of form elements for their co-applicant via an onchange event that shows the link that will slideToggle the first users inputs and show the inputs for the additional users. It's a pretty lengthy form so I cut it down to a few elements so I could fiddle it out:
Das Fiddle is here
<form method="POST" id="refiLoanForm" action="mailto:i#i.com">
<!--START PRIMARY APPLICANT -->
<div id="primary-applicant">
<label>
Application Type
<select name="applicationType" id="applicationType" class="wider" required>
<option value="individual">Individual</option>
<option value="joint">Joint</option>
</select>
</label>
<br>
<label for="loan-amount" id="loan-amount-label">Requested Finance Amount
<input type="text" id="loan-amount" name="loanAmount" required/></label>
<br>
<label for="remaining-term">Current Loan Remaining Term
<input type="text" id="remaining-term" name="remainingTerm" max="3" size="3" required class="override"/>
</label>
<br>
CONTINUE TO CO-APPLICANT
</div>
<!--END PRIMARY APPLICANT -->
<!--START CO_APPLICANT -->
<div id="co-applicant" style="display: none">
Back to Primary Applicant
<br>
<label for="co-first-name">First Name
<input type="text" id="co-first-name" name="coApplicantGivenName" maxlength="32" required/>
</label>
<br>
<label for="co-last-name">Last Name
<input type="text" id="co-last-name" name="coApplicantFamilyName" maxlength="32" required/>
</label>
</div>
JS:
$('#refiLoanForm').validate({
onkeyup: false,
ignore: ":disabled",
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
$("#singleSubmitBtnLoan").bind('click', function () {
$('#refiLoanForm').valid();
});
//Handle the content being shown
$("#singleSubmitBtnLink2").on('click', function () {
$("#primary-applicant").slideToggle("slow");
$("#co-applicant").slideToggle("slow");
});
$("#backToPrimary").on('click', function () {
$("#primary-applicant").slideToggle("slow");
$("#co-applicant").slideToggle("slow");
});
$('#applicationType').on('change', function() {
if ($(this).val() === 'joint') {
$('.primaryApplicantSwitch').slideToggle("slow");
$('.jointApplicantSwitch').slideToggle("slow");
} else {
$('.primaryApplicantSwitch').slideToggle("slow");
$('.jointApplicantSwitch').slideToggle("slow");
}
});
So in theory, the user can enter the fields and hit submit and the form is either valid or throws some errors. Or, the user can add a co-applicant, and validate the form on the link click before toggling to the next group of inputs.
Any ideas on how I would bind all of this to the one button and get it to play nice with jquery.validate?
You cannot dynamically "toggle" the rules of input fields.
However, you can use the .rules() method to dynamically add/change/remove rules, which essentially mimics the behavior of a toggle.
Also, since you're talking about fields that are hidden, you'll need to disable the option that makes validation ignore all hidden fields.
ignore: []
The following code is exhibiting a very strange behavior...
I have two html selects: one for regions and another one for departments bearing in mind that for one selected region I am trying to load the corresponding departments.
The first html select (region) is populated upon normal page load and the second html select (departments) by an ajax call retrieving JSON from the server.
I use jquery chosen.
The strange behavior I am referring to is as follows:
upon a first change of the region select (say region A is selected), the department select is not populated.
Upon a second change of the region select (say region B is selected), the department select is populated by region A's departments!!!!
Javascript:
$(document).ready(function() {
$(".chzn-select").chosen({no_results_text: "No results matched"});
var geolocationRegionSelect = $("#geolocationRegionSelect");
var geolocationDepartmentSelect = $("#geolocationDepartmentSelect");
geolocationRegionSelect.bind('change', function(event) {
$.get("/kadjoukor/geolocations/findDepartmentsByRegion?regionId="+$(this).val(), function(result){
geolocationDepartmentSelect.empty();
$.each(result, function() {
geolocationDepartmentSelect.append($("<option />").val(this.id).text(this.department));
});
}, 'json');
$(".chzn-select").trigger("liszt:updated");
});
});
Here is the corresponding html:
<div class="control-group">
<label class="control-label" for="geolocationRegionSelect">geolocation region</label>
<div class="controls">
<select id="geolocationRegionSelect">
<option th:value="''" th:text="'Non renseigne'"></option>
<option th:each="geolocationRegion: ${geolocationRegions}" th:value="${geolocationRegion.id}" th:text="${geolocationRegion.region}"></option>
</select>
</div>
<div class="controls">
<select id="geolocationDepartmentSelect" th:field="*{geolocationDepartments}" data-placeholder="Choose a department" multiple="multiple" class="chzn-select">
</select>
</div>
</div>
Can anyone please advise?
EDIT: Generated HTML:
<label class="control-label" for="geolocationRegionSelect">geolocation region</label>
<div class="controls">
<select id="geolocationRegionSelect">
<option value="">Non renseigne</option>
<option value="1">Alsace</option><option value="2">Aquitaine</option><option value="3">Auvergne</option><option value="4">Basse-Normandie</option><option value="5">Bourgogne</option><option value="6">Bretagne</option><option value="7">Centre</option><option value="8">Champagne-Ardenne</option><option value="9">Corse</option><option value="10">DOM-TOM</option><option value="11">Franche-Comté</option><option value="12">Haute-Normandie</option><option value="13">Ile-de-France</option><option value="14">Languedoc-Roussillon</option><option value="15">Limousin</option><option value="16">Lorraine</option><option value="17">Midi-Pyrénées</option><option value="18">Nord-Pas-de-Calais</option><option value="19">Pays de la Loire</option><option value="20">Picardie</option><option value="21">Poitou-Charentes</option><option value="22">Provence-Alpes-Côte d'Azur</option><option value="23">Rhône-Alpes</option>
</select>
</div>
<div class="controls">
<select id="geolocationDepartmentSelect" data-placeholder="Choose a department" multiple="multiple" class="chzn-select">
</select>
</div>
You should trigger update after element updated, inside handler...
$(document).ready(function() {
$(".chzn-select").chosen({no_results_text: "No results matched"});
var geolocationRegionSelect = $("#geolocationRegionSelect");
var geolocationDepartmentSelect = $("#geolocationDepartmentSelect");
geolocationRegionSelect.bind('change', function(event) {
$.get("/kadjoukor/geolocations/findDepartmentsByRegion?regionId="+$(this).val(), function(result){
geolocationDepartmentSelect.empty();
$.each(result, function() {
geolocationDepartmentSelect.append($("<option />").val(this.id).text(this.department));
geolocationDepartmentSelect.trigger("liszt:updated"); // <--TO HERE
});
}, 'json');
//<-FROM HERE
});
});
http://jsfiddle.net/oceog/rQJeX/
You not get epected results because $.get() here is asynchronous, get the analogy:
You ask your wife to go to the post office and ask them how much you should pay for your father's annual magazine subscription, you tell her - "when you back leave note on that table, and remove old note from here" (on table already the note for 100$, subscription is 50$).
After she leaves you ask your mother to check a note on the table and give it to your father to make him pay...
your question is equal to that - "why my father payed 100$" ?
the answer is equal to that - you had to ask your wife to tell your mother to bring note to your father, when note on the table will be refreshed by your wife.
sorry for english, feel free to edit that if needed.