Not reading .val() of some inputs - javascript

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

Related

Regular Expression always false

So I am writing some javascript to check if a user inputs a gmail address.
At the moment I have the code thats below, but no matter what I do it is giving me false. even when the input has #gmail.com...I feel that the mistake is how I am grabbing the user input in a variable and then testing it with test().
Javascript:
<script>
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {
}
}
</script>
html
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input
type="text"
class="form-control col-sm-1"
id="inputEmail"
placeholder="username#gmail.com"
/>
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>
You need to check the value of the input, var emailMatch = gmailPatt.test(email.value);
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email.value);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {}
}
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input type="text" class="form-control col-sm-1" id="inputEmail" placeholder="username#gmail.com" />
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>

How to check for required radio and checkbox inputs in a form and then display a message if they're checked or unchecked?

I implemented some user feedback for users. If required fields are empty, some error messages will appear to alert users that the inputs are empty.
I have been working all weekend on this. I get the correct feedback for empty 'text' values. I'm having a hard time checking for empty checkbox and radio inputs. By default, when you click submit/check, you get the correct error message for empty 'text' fields but not radio and checkbox items.
My code:
HTML
<form id="my-form" class="form" action="/" method="post">
<div class="form-row">
<label for="name" class="form-label">Name *</label>
<div class="form-field">
<input id="name" name="name" placeholder="Please enter your name" type="text" required>
</div>
</div>
<div class="form-row">
<label for="email" class="form-label">Email *</label>
<div class="form-field">
<input id="email" name="email" placeholder="Please enter your email address" type="email" required>
</div>
</div>
<div class="form-row">
<label for="radio" class="form-label">Radio Buttons *</label>
<div class="form-field">
<span class="form-radios">Select 1: </span>
<input id="radio" name="radiobutton" value="selection-one" type="radio" required>
<span class="form-radios">Select 2: </span>
<input name="radiobutton" value="selection-two" type="radio">
</div>
</div>
<div class="form-row">
<label for="checkbox" class="form-label">Checkboxes *</label>
<div class="form-field">
<span class="form-radios">Select 1: </span>
<input id="checkbox1" name="checkbox" type="checkbox" value="checkbox1value" required>
<span class="form-radios">Select 2: </span>
<input id="checkbox2" value="checkbox2value" name="checkbox" type="checkbox">
</div>
</div>
<div class="form-row">
<label for="tel" class="form-label">Telephone *</label>
<div class="form-field">
<input id="tel" name="telephone" placeholder="Please enter your number" type="tel" required>
</div>
</div>
<div class="form-row">
<label for="website" class="form-label">Website *</label>
<div class="form-field">
<input id="website" name="website" placeholder="Begin with https://" type="url" required>
</div>
</div>
<div class="form-row">
<label for="message" class="form-label">Message *</label>
<div class="form-field">
<textarea id="message" name="How long were you away for?" placeholder="Include all the details you can" required></textarea>
</div>
</div>
<div class="form-row">
<button id="check" name="submit" type="submit" class="form-submit">Send Email</button>
</div>
</form>
JAVASCRIPT
const requiredElements = document.getElementById("my-form").querySelectorAll("[required]"),
submitButton = document.getElementById("check"),
errorMsgOutput = document.getElementById("output");
submitButton.addEventListener("click", function() {
var errorMsg = "";
var radios = document.getElementById("my-form").radiobutton;
var checboxes = document.getElementById("my-form").checbox;
for (var i = 0; i < requiredElements.length; i++) {
var form = requiredElements[i];
// Checking for empty text fields
if (form.value.length) {
errorMsg += form.name + ": " + "Filled" + "<br>";
} else if (form.value.length === 0) {
errorMsg += form.name + ": " + "Not Filled" + "<br>";
}
// My attempt to check that radio values are filled. By default, the error message says that it's checked ('filled') even when it's not.
// for(var j = 0, k = radios.length; j < k; j++){
// if (form.type == 'radio' && radios[k].checked) {
// errorMsg += form.name + ": " + "Filled" + "<br>";
// } else {
// errorMsg += form.name + ": " + "Not Filled" + "<br>";
// }
// }
}
errorMsgOutput.innerHTML = errorMsg;
});
Even before you click the send email button, the checkbox and radio inputs display the 'filled' error message. See: https://jsfiddle.net/krisixco/zgdf2sec/10/ to see what I mean...
It seems to me that you ask two questions. The first is why the required does not display a pop-up for radio and checkbox and the second is how to check if they were filled in or not by javascript.
About the first question, in the code you put in your question, the checkbox and radio inputs do not have the required attribute
For the second question use the checked method
example:
let checkbox = document.querySelector('input[type=checkbox]')
if(checkbox.checked){
// checked
else {
// not checked
}
for (var i = 0; i < requiredElements.length; i++) {
var form = requiredElements[i];
// Checking for empty text fields
if(form.name === "radiobutton" || form.name === "checkbox" ){
if(!form.checked) errorMsg += form.name + ": " + "Not Filled" + "<br>";
if(form.checked) errorMsg += form.name + ": " + "Filled" + "<br>";
} else{
if (form.value.length) {
errorMsg += form.name + ": " + "Filled" + "<br>";
} else if (form.value.length === 0) {
errorMsg += form.name + ": " + "Not Filled" + "<br>";
}
}

Validation for dropdown menu

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>

document.getElementById.value not working

I have a html page that has input fields for the user to enter the quantity of fruits. On key press/ key up, it is suppose to call the javascript file method and checks if it is a digit. If it is not a digit, the textbox field will be cleared. However, my textbox is not cleared when i tried to enter a non numerical value. Is there something missing in my code?
Html
<div class="form-group ">
<label class="control-label " for="name"> Name </label>
<input class="form-control" id="name" name="name" type="text" /> <span class="help-block" id="hint_name"> Enter your name </span>
</div>
<div class="form-group ">
<label class="control-label" for="apple"> Apple ( 69cents ) </label>
<input class="form-control form-control-input" id="apple" name="apple" type="text" autocomplete="off" onkeyup="isNumber(this,event)" /> <span class="help-block" id="hint_number"> Enter Qty </span>
</div>
<div class="form-group ">
<label class="control-label" for="orange"> Orange ( 59cents ) </label>
<input class="form-control form-control-input" id="orange" name="orange" type="text" autocomplete="off" onkeyup="isNumber(this,event)" /> <span class="help-block" id="hint_number1"> Enter Qty </span>
</div>
<div class="form-group ">
<label class="control-label" for="banana"> Banana ( 39cents ) </label>
<input class="form-control form-control-input" id="banana" name="banana" type="text" autocomplete="off" onkeyup="isNumber(this,event)" /> <span class="help-block" id="hint_number2"> Enter Qty </span>
</div>
Javascript
function isNumber(idValue, evt) {
evt = (evt) ? evt : window.event;
var sum = 0;
var costOfApple = 0;
var costOfOrange = 0;
var costOfBanana = 0;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
document.getElementById('idValue.id').value = "";
document.getElementById('totalCost').value = "NaN";
$("#invalid-alert").fadeTo(2000, 500).slideUp(500, function() {
$("#invalid-alert").slideUp(500);
});
} else {
costOfApple = document.getElementById('apple').value * 69;
costOfOrange = document.getElementById('orange').value * 59;
costOfBanana = document.getElementById('banana').value * 39;
sum = (Number(costOfApple) + Number(costOfOrange) + Number(costOfBanana)) / 100;
document.getElementById('totalCost').value = "$" + (sum).toFixed(2);
}
}
Problem statement is
document.getElementById('idValue.id').value = "";
You are passing string 'idValue.id' to the function and the element with ID doesn't exists, thus the code is not working and you must be getting error in the browser console.
As idValue refers to element which invoke the event handler. You can just use it directly to set its property.
idValue.value = ""
I thinks
document.getElementById('idValue.id').value = "";
should be
document.getElementById(idValue.id).value = "";
or
idValue.value = "";
and , It's good to console.dir( idValue ) in isNumber function!
test please!
you are passing this to a function , and this is here the input you should use it as an object not as a string.
don’t do that :
document.getElementById('idValue.id').value = "";
try this instead
document.getElementById(idValue.id).value = "";
$(document).on('change', 'input', function() {
if($('#Id').val() == "" ) {
// Do something
}
});
OR
document.getElementById(yourID).value = "";

Confused on ordering of function calls and debugging

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 :)

Categories