JS Issue with form validation on drop down input - javascript

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;
}

Related

Angular Validation not working with reference variables

Below is my component.html
<form (ngSubmit)="save(myForm.form)" #myForm="ngForm" novalidate>
<select required id="language" [(ngModel)]="myModel.language" name="language" #language="ngModel">
<option *ngFor="let lang of languages" value={{lang.key}}>
{{lang.value}}
</option>
</select>
<div *ngIf="myForm.submitted && language.invalid" class="ErrorTxt">
<div *ngIf="language.errors.required">Language is required</div>
</div>
<button type="submit" class="btn btn-default ">Save</button>
</form>
It should show message "Language is required" when user click on submit without selecting a value from dropdown , but it does not.
I tried printing value of reference variables like below
{{myForm.submitted}}-{{language.invalid}}-{{language.errors.required}}
and got this output all the time:
false-true-true
After clicking on submit button, {{myForm.submitted}} should be true but it is always set to false. The save method is defined as follows in my component.ts file:
save(form: any) {
if (!form.valid) {
let elements = document.getElementsByClassName("ng-invalid");
if (elements.length > 1) {
(elements[1] as HTMLElement).focus();
}
return;
}
// save code here
}
Can someone please suggest whats wrong with this validation and how to make it work ?

How to prevent user entering value if previous field is empty?

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>

Concatenate two fields and use this value to change/set value of a hidden field

Here is what I want to achieve. I have a requirement in which there is one dropdown for country codes and another input field for mobile number. I want to send country code and mobile input value as combined value so for that I am using a hidden field. When not using a hidden field it is easy to change value of a third tag element but that will not send value when form is submitted. So hidden field has to be used. So I have tried doing this but it is not changing value of hidden field.
<html>
<head>
<script language="javascript">
var dropdown = '';
var mobilenum = '';
function calldropdown()
{
dropdown = document.getElementById("country_code_id").value;
return dropdown;
}
function calltxtfield()
{
mobilenum = document.getElementById("mobileid").value;
return mobilenum;
}
function codemobile()
{
document.getElementById("codemobileid").value = calldropdown() + ' ' + calltxtfield;
alert(document.getElementById("codemobileid").value);
}
</script>
</head>
<body>
<form>
<select name="country_code" id="country_code_id" onchange="calldropdown()">
<option value="">Select</option>
<option value="+975">Bhutan</option>
<option value="+977">Nepal</option>
<option value="+94">Sri Lanka</option>
</select>
<input type="text" name="mobile" id="mobileid" onchange="calltxtfield()" />
<input type="hidden" name="codemobile" id="codemobileid" value="" />
<input type="submit" name="submit" value="Submit" onclick="return codemobile();" />
</form>
</body>
</html>
I can not explain it right now, but name="codemobile" seems to silently shadow function codemobile(). Rename one of the two and it works.
Also note that right now you are concatenating the function body (... + calltxtfield;), it should rather be ... + calltxtfield();

Get a value from a PHP Page to a Javascript in Another Page Issue

this time i am having a problem to get a value of a php file where the goal is make a query (that part is done), validate if the query doesn't work, return false or else true.
That file is called into a javascript var to get the true/false value, but it doesn't work. I know that i'm failing because i printed the boolean value and alert shows "[object][object]".
Here is my HTML file
<form class="form-inline" id="formpqrs1" onSubmit="Validate()" method="get">
<label> <h4><b>Information</b></h4></label>
<br>
<select id="s2" name="s2" style="min-width:25%"></select>
<br><br>
<label><h4><b>Insert Element Name</b></h4></label>
<br>
<input name="Nombre" id="Lugarpqrs" type="text" class="form-control" placeholder="NOMBRE" required>
<br> <br>
<div id="motivos">
<label> <h4><b>Choose Type:</b></h4></label>
<br>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="1"><h5>Type 1</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="2"><h5>Type 2</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="3"><h5>Type 3</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="4"><h5>Type 4</h5>
</label>
</div>
<br><br>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Here my Javascript file where i get the value of the php file, i validate from a radio button, then i create a var to get the value of the php file where the query is done.
function Validate(){
if($("#opcion:checked").val() === "1"){
var validar = false;
var validar = $.get("validaciones/Validar_Ubicacion.php?lugar="+$("#Lugarpqrs").val()+"");
if(!validar){
$.get("php/Ingresar_tipo.php?lugar="+$("#Lugarpqrs").val()+"");
alert("Success" + validar);
}
else{
alert("Element Already Exist in DB" + validar);
}
}
Here is my php file
<?php
$lugar=$_GET["lugar"];
$conexion = mysqli_connect($server, $user, $pass,$bd)
or die("ERROR");
$confirmacion = false;
$sql = "SELECT * FROM `lugar` WHERE `nombre` = '".$lugar."'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$close = mysqli_close($conexion)
or die("ERROR");
if(!$sql){
echo $confirmacion;
}
else{
$confirmacion = true;
echo $confirmacion;
}
?>
The last part if/else is where i validate if query fails that means the element doesn't exist then return $confirmacion value which is false or else $confirmacion = true which means element already exist and show an alert message in the script that is on another page.
Previously i tested other validations like the query and if/else validations of the radio button (first if validation) and it works, so, the problem is in my var validar, maybe i'm doing wrong when i get the value from my php file.
As always, thanks for your time and attention, all answers are welcome to me.
Good day.
You need to update your logic inside the jquery's .get function (since it's asynchronous.
Update your PHP file to output string "true" and "false" (best practice is to use JSON format & header) - this may work for you.
I updated for you your Javascript file:
function Validate(){
if($("#opcion:checked").val() === "1"){
var validar = false;
$.get("validaciones/Validar_Ubicacion.php?lugar="+$("#Lugarpqrs").val()+"",
function(data){
if(data=="true"){
$.get("php/Ingresar_tipo.php?lugar="+$("#Lugarpqrs").val()+"");
alert("Success" + validar);
}
else{
alert("Element Already Exist in DB" + validar);
}
});
}

I am trying to validate within my HTML code with text-boxes and drop-downs

The code I am currently trying to work out is I have one drop down box that is a required drop-down. If "Complete" is selected from that drop down box a text box appears. If "Abandon" is selected from that drop down box a second drop down box appears with other options.
I am trying to add validation onto those 2nd options after the first drop down is selected. In my code I have the first drop down box "ActionDD" marked as a required field. But I can not do that with the textbox "REMtextBox" or the "ReasonDD" drop down box since they will never appear at the same time.
Here is the code for my form
<form name=StudentForm action="javascript:window.close();">
<div class="DDbox">
<select name="Action" id="ActionDD" required onchange="showHide()">
<option value="">Action:</option>
<option value="complete">Complete</option>
<option value="abandon">Abandon</option>
<option value="transfer">Transfer</option>
</select>
</div>
<br>
<div class="COMPLETEbox" id="COMPLETEbox" >
<input class="hidden-items" type="text" name="RemNUM" id="REMtextBox" placeholder="Remedy Number" min="1" maxlength="10" style="display:none;"/><br>
<select class="hidden-items" name="Reason" id="ReasonDD" style="display:none;">
<option value="">Reason:</option>
<option value="NoShow">No Show</option>
<option value="Unfixable">Unfixable</option>
<option value="other">Other</option>
</select><br><br>
<br>
<input type="submit" value="submit" onclick="checkform();">
</div>
</form>
Then here is the code I have been working on for my JavaScript to check conditions when the Submit button is pressed.
function checkform() {
if (document.getElementById('ActionDD').value ="abandon" && (document.getElementById('ReasonDD').value =""))
{
validationMessage = validationMessage + 'Enter Reason';
valid = false;
}
else valid = true;
}
</script>
I am looking for a solution for how to check if the first drop down has a value selected, then whatever corresponding textbox or drop down appears from the choice that was made in the first drop down has a value selected.
Thanks in advance for any help.
Try the below code.
Idea is to set/remove the 'required' attribute during onchange of the ActionDD drop-down. Hope it helps.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>HTML code with text-boxes and drop-downs</title>
<script type="text/javascript">
var actionBox,
reasonBox,
completeBox,
remTextBox,
selectedAction,
isFormValid,
validationMessage = "Not all required fields are filled in; ";
function init() {
actionBox = document.getElementById('ActionDD');
reasonBox = document.getElementById('ReasonDD');
completeBox = document.getElementById('COMPLETEbox');
remTextBox = document.getElementById('REMtextBox');
selectedAction = actionBox.value;
remTextBox.style.display = 'none';
remTextBox.removeAttribute("required");
reasonBox.style.display = 'none';
reasonBox.removeAttribute("required");
isFormValid = false;
}
function checkform() {
// Include other logic if needed here...
}
function showHide() {
init();
if (selectedAction == 'complete') {
remTextBox.style.display = 'block';
remTextBox.setAttribute("required", "required");
}
else if (selectedAction == 'abandon') {
reasonBox.style.display = 'block';
reasonBox.setAttribute("required", "required");
}
}
</script>
<style>
</style>
</head>
<body>
<form name="StudentForm">
<div class="DDbox">
<select name="Action" id="ActionDD" required onchange="showHide()">
<option value="">Action:</option>
<option value="complete">Complete</option>
<option value="abandon">Abandon</option>
<option value="transfer">Transfer</option>
</select>
</div>
<br>
<div class="COMPLETEbox" id="COMPLETEbox">
<input class="hidden-items" type="text" name="RemNUM" id="REMtextBox" placeholder="Remedy Number" min="1" maxlength="10" style="display:none;" /><br>
<select class="hidden-items" name="Reason" id="ReasonDD" style="display:none;">
<option value="">Reason:</option>
<option value="NoShow">No Show</option>
<option value="Unfixable">Unfixable</option>
<option value="other">Other</option>
</select>
<br>
<br>
<br>
<input type="submit" value="submit" onclick="checkform();">
</div>
</form>
</body>
</html>
You have a little mistake in your JavaScript validation function,
instead of a comparison (x==y) you did an assignment (x=y).
In addition to that, there is a slightly different technique for getting aselectbox selected value.
This is your code with a little change:
function checkform() {
var action = document.getElementById('ActionDD'),
reason = document.getElementById('ReasonDD');
if (action.options[action.selectedIndex].value =="abandon" && reason.options[reason.selectedIndex].value =="")
{
validationMessage = validationMessage + 'Enter Reason';
valid = false;
}
else valid = true;
}
Hope it helps a bit.
Try this.
function checkform() {
if (document.getElementById('ActionDD').value =="abandon" && (document.getElementById('ReasonDD').value ==""))
{
//Your validation message
return false;
}
else return true;
}
</script>
onchange()
function showHide() {
if(document.getElementById('ActionDD').value =="abandon")
{
document.getElementById("ReasonDD").style.display= 'block';
document.getElementById("ReasonDD").required = true;
}
else
document.getElementById("ReasonDD").style.display= 'none';
}
Change your html little bit.Remove checkform() from button and add to form as shown below.
<form name=StudentForm onsubmit="return checkform()" action="javascript:window.close();">

Categories