validating a user's value length (javascript) - validation

I am practicing my javascript beginners knowledge on a simple form. I want the user to enter a 10 digits phone number (in case it's less than 10 or more than 10 I have created the invalid style class so the user will only be allowed to enter 10 digits for his phone number). Also, once they entered the phone number of 10 digits, the user should be able to click "+" and get a second box for a second phone number (the second box will appear when you click + only if the user entered 10 digits for his first phone number).
I used an if() for validating the phone number, but it doesn't seem to work. Below is my code, any ideas maybe?
<!DOCTYPE html>
<html>
<head>
<title>Numere de telefon</title>
<style>
.invalid {
background-color: rgb(139,0,0,0.2);
color: darkgreen;
border: 1px green solid;
}
</style>
<script>
function minL(elem,event,nr){
var v = elem.value;
if(v.length < nr ){
elem.classList.add("invalid");
} else if (v.length > nr) {
elem.classList.add("invalid");
} else {
elem.classList.remove("invalid");
}
}
function addInput(elem,event){
event.preventDefault();
var container = document.querySelector("#containerNrTel");
if(minL(document.querySelector("[name=numarTelefon]"))){
container.innerHTML += '<input type="text" placeholder="nr telefon" />';
}
}
</script>
</head>
<body>
<form>
<fieldset>
<legend>Cont nou</legend>
<input type="text" placeholder="nume">
<input type="text" placeholder="prenume">
<input type="text" placeholder="nr telefon" name="numarTelefon" oninput="" onchange="minL(this,event,10);">
<input type="button" value="+" onclick="addInput(this,event);">
<div id="containerNrTel"></div>
<input type="button" value="Submit">
</fieldset>
</form>
</body>
</html>
Thanks in advance,
Ioana

There are two main issues.
The call to minL in the addInput function doesn't have the right number of parameters.
minL doesn't return a boolean value when addInput expects it to.
function minL(elem,event,nr){
var v = elem.value;
if(v.length < nr ){
elem.classList.add("invalid");
} else if (v.length > nr) {
elem.classList.add("invalid");
} else {
elem.classList.remove("invalid");
return true;
}
}
function addInput(elem,event){
event.preventDefault();
var container = document.querySelector("#containerNrTel");
if(minL(document.querySelector("[name=numarTelefon]"), event, 10)){
container.innerHTML += '<input type="text" placeholder="nr telefon" />';
}
}

Related

Kendo Numeric text box custom validation for percentage value

We are trying to display a validation error message by overriding the default behavior of Kendo numerictextbox for displaying percentage value.
our expectation is to provide a custom message when user type in any value more than 100.
By default Kendo NumericTextbox for percentage auto corrects the value if the user type in anything more than 100 (we don't want this behavior)
Please find a jsfiddle reference URL for the same to understand it better
https://jsfiddle.net/6uyp825h/57/
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/numerictextbox/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2018.2.620/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.2.620/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="add-product" class="demo-section k-content">
<p class="title">Add new product</p>
<ul id="fieldlist">
<li>
<label>
Price Discount:
<input id="percentage" value="5" title="percentage" style="width: 100%;" />
</label>
</li>
</ul>
</div>
<script>
$(document).ready(function() {
// create Percentage NumericTextBox from input HTML element
$("#percentage").kendoNumericTextBox({
format: "##.00 \\%",
min: 0,
spinner: false
});
var container = root;
kendo.init(container);
container.kendoValidator({
rules: {
checkPercentageMaxValue: function (input) {
var maxAllowedValue = 100;
var currentValue = parseInt($("#percentage").val());
if (currentValue > maxAllowedValue)
{
return false;
}
else {
return true;
}
return true;
}
},
messages: {
checkPercentageMaxValue: "Percentage value cannot be greater than 100."
}
});
});
</script>
<style>
.demo-section {
padding: 0;
}
#add-product .title {
font-size: 16px;
color: #fff;
background-color: #1e88e5;
padding: 20px 30px;
margin: 0;
}
#fieldlist {
margin: 0 0 -1.5em;
padding: 30px;
}
#fieldlist li {
list-style: none;
padding-bottom: 1.5em;
}
#fieldlist label {
display: block;
padding-bottom: .6em;
font-weight: bold;
text-transform: uppercase;
font-size: 12px;
}
#fieldlist label .k-numerictextbox {
font-size: 14px;
}
</style>
</div>
Here is the html which I gets in real scenario
<div class="col-sm-8">
<span class="k-widget k-numerictextbox single-line text-box form-control">
<span class="k-numeric-wrap k-state-default k-expand-padding">
<input tabindex="0" title="112.00 %" class="k-formatted-value single-line text-box form-control k-input k-valid" role="spinbutton" aria-disabled="false" aria-valuenow="112" style="display: inline-block;" type="text">
<input name="PercentHeld3" class="single-line text-box form-control k-input k-valid" id="PercentHeld3" role="spinbutton" aria-disabled="false" aria-valuenow="112" style="display: none; border-color:black; " type="text" maxlength="16" data-role="numerictextbox" data-bind="value: PercentHeld" data-spinners="false" data-numberformat="percentage" data-decimals="2" data-validate="true" data-maxallowedvalue="100" data-max-msg="Percentage value cannot be greater than 100.">
<span class="k-select" style="display: none;">
<span title="Increase value" class="k-link k-link-increase" style="touch-action: none;" aria-label="Increase value" unselectable="on">
<span class="k-icon k-i-arrow-60-up" unselectable="on"></span>
</span>
<span title="Decrease value" class="k-link k-link-decrease" style="touch-action: none;" aria-label="Decrease value" unselectable="on">
<span class="k-icon k-i-arrow-60-down" unselectable="on"></span>
</span>
</span>
</span>
</span>
</div>
Rule used in real scenario
checkPercentageMaxValue: function (input) {
$('input[data-maxallowedvalue][data-validate="true"]').each(function (index, item) {
var maxAllowedValue = parseInt($(item).attr('data-maxallowedvalue'));
var currentValue = parseInt($(item).val().replace(/%?$/, ''));
if (currentValue > maxAllowedValue) {
return false;
}
else {
return true;
}
});
return true;
}
Right after some trial and error and finally understanding what it is you want. I think you have misunderstood how the validator rules work.
http://dojo.telerik.com/UHIhACOh
The rules:
checkPercentageMaxValue: function(input) {
var valid = true;
singlerule += 1;
if ($(input).is('[data-maxallowed-value][data-validate="true"]')) {
var maxAllowedValue = parseFloat($(input).attr('data-maxallowed-value'));
var currentValue = parseFloat($(input).val());
if (isNaN(currentValue)) {
currentValue = 0;
}
valid = (currentValue <= maxAllowedValue);
$('#control1').html('Max Allowed Value::' + maxAllowedValue + ',Current Parsed Value::' + currentValue);
} else {
$('#control1').html('<pre><code>' + JSON.stringify($(input), null, 4) + '</code></pre>');
}
$('#control1').append('I ran <b>checkPercentageMaxValue</b> rule: ' + singlerule + 'time(s)<br/>');
singlerule = 0;
return valid;
},
yourrule: function(input) {
$('input[data-maxallowed-value][data-validate="true"]').each(function(index, item) {
multirule += 1;
$('#control1').append('I ran <b>yourrule</b> rule: ' + multirule + 'time(s)<br/>');
var maxAllowedValue = parseFloat($(item).attr('data-maxallowed-value'));
var currentValue = parseFloat($(item).val());
if (isNaN(currentValue)) {
currentValue = 0;
}
if (currentValue > maxAllowedValue) {
return false;
} else {
return true;
}
});
multirule = 0;
return true;
}
}
Each rule listed in the custom rules list is ran on every control that is being validated.
So your current rule is checking each input control and then any other input controls of that type again assuming they meet the approved condition.
So you are running the checks multiple times and if one passes then your rule assumes all have passed if it hits a true condition and the same is true for an error'd item which is why you are getting the issues you are currently getting. Obviously if this is what you want (checking multiple items are the same time) then you need to hold the true/false value in a variable so that it will return back the message (but this message will only be displayed next the control that kicked off the initial validation/focus)
Hopefully adding the second control will show you what is happening clearer.
As you can see the first time you enter a control your rule will run twice until one of the input boxes states that is in an error state and then you rule will only run when one of the controls is in a invalid state, if you put a value incorrectly in the second box then your rule states that it has exited successfully and is valid.
I added a button so you can see if the validator thinks it is in a valid/invalid state based on the rules provided.
If anything isn't clear or you need more info let me know and I will update the answer accordingly.

Blank page after submitting external HIT in MTurk

If I submit my external HIT with the https://workersandbox.mturk.com/mturk/externalSubmit URL, it gets succesfully submitted to MTurk (in my requester Sandbox, i can see the result), but for the worker an empty / blank page appears, instead of the confirmation, that her/his HIT got submitted succesfully...
I guess, something with the action-parameter in my form could be wrong...
The HTML-Code of this blank page looks like:
<html><head>
<title><bean:message key="external_submit.title" /></title>
<script type="text/javascript">
function reloadOuterPage() {
var boxes = top.document.getElementsByName('autoAcceptEnabled');
if( boxes.length == 0 || !boxes[0].checked ) {
top.location = top.document.getElementById('hitExternalNextLink').href;
} else {
top.location = top.document.getElementById('hitExternalNextAcceptLink').href;
}
};
</script>
</head>
<body onload="reloadOuterPage();"><bean:message key="external_submit.body">
</bean:message></body></html>
The form I'm submitting:
<form target="_parent" name="hitForm" style="visibility:hidden" id="hitForm" method="POST"
action="https://workersandbox.mturk.com/mturk/externalSubmit">
<input type="hidden" id="assignmentId" name="assignmentId">
<input type="hidden" id="hitId" name="hitId"/>
<input type="hidden" id="workerId" name="workerId"/>
<input type="hidden" id="caption" name="caption" value="TEST">
<input type="submit" name="Submit" id="submitButton" value="submit" disabled="true">
</form>
<button ng-show="!hasAccepted()" disabled>You must first accept the HIT in order to Submit it!</button>
<button ng-click="submitHit(inputText)" ng-show="hasAccepted()">Submit</button>
where the submitHit Method looks like this (the ids get assigned properly - i checked that):
$scope.submitHit = function (cap) {
$scope.form = document.getElementById("hitForm");
$scope.assignmentId = "";
$scope.hitId = "";
$scope.workerId = "";
$scope.assignmentId = $scope.turkGetParam("assignmentId");
$scope.hitId = $scope.turkGetParam("hitId");
$scope.workerId = $scope.turkGetParam("workerId");
document.getElementById("assignmentId").value = $scope.assignmentId;
document.getElementById("hitId").value = $scope.hitId;
document.getElementById("workerId").value = $scope.workerId;
$scope.form.submit();
}
thank you very much for your help!
As always, one works nearly 2 days on this "bug" and after overcoming to ask on stackoverflow, one finds the solution: I had to delete the target="_parent" in my form and now everything works fine!

Javascript validate all radio buttons if checked

Im so dumb in javascript, I would like to ask your help about radio button validation. I have 3 set of questions, each has 3 radio buttons. I want to validate if all the 3 questions have been answered or checked.
Thanks in advance
Here is the code I have tested, it only validates 1 radiobutton
<script type="text/javascript">
function validateForm() {
var radios = document.querySelectorAll("#option1, #option2, #option3, #option4, #option5, #option6");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must check some option!");
return formValid;
}
</script>
I have solved the problem with this code
if ($('div.quizbox:not(:has(:radio:checked))').length) {
alert("You missed answering one or more of the questions.");
}
try this it works for me
<script type="text/javascript">
function validateForm(){
var inputs = document.querySelectorAll("#option1,#option2,#option3,#option4,#option5,#option6")
var formValid = false;
for(var i=0;i<inputs.length;i++){
if(inputs[i].checked){
formValid = true;
}
}
if(!formValid ){
alert("Must check some option!");
}
}
</script>
html code
<body>
<form name="frm">
Question 1<br>
<input type="radio" name="group1" value="Ans1" id="option1">Ans1<br>
<input type="radio" name="group1" value="Ans2" id="option2">Ans2<br>
Question 2<br>
<input type="radio" name="group2" value="Ans1" id="option3">Ans1<br>
<input type="radio" name="group2" value="Ans2" id="option4">Ans2<br>
Question 3<br>
<input type="radio" name="group3" value="Ans1" id="option5">Ans1<br>
<input type="radio" name="group3" value="Ans2" id="option6">Ans2<br>
<input type="submit" value="Test" onclick="validateForm();" />
</form>
</body>

Getting a response from Cfajaximport / ajax with coldfusion

I've searched a number of the previous responses, but none of them have helped me. I'm actually extrapolating on another script I found earlier.... but I'm not sure how to capture the response in AJAX. I was guessing that handleResponse would just capture whatever is outputted on checkdomain.cfm, but I can't seem to make that happen so I can output it. So in the example below, somehow the person who developed this script was able to get back AVAILABLE from checkdomain.cfm, but I can't figure out how to do that.
Thanks in advance!
<head>
...
<cfajaximport />
...
<script>
function handleResponse(s) {
if(s == "AVAILABLE") {
//rewrite span
var domainspan = document.getElementById('DomainStatus');
var newcontent = "Available To Register :)";
domainspan.innerHTML = newcontent;
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' value='GO!' class='search_domain_go' type='submit' />";
loadingspan.innerHTML = newcontent;
} else {
//rewrite span
var domainspan = document.getElementById('DomainStatus');
var newcontent = "Unavailable To Register :(";
domainspan.innerHTML = newcontent;
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' value='GO!' class='search_domain_go' type='submit' />";
loadingspan.innerHTML = newcontent;
}
}
function CheckDomain() {
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' type='image' class='search_domain_go' src='images/ajax-loader.gif' alt='' />";
loadingspan.innerHTML = newcontent;
ColdFusion.Ajax.submitForm('frmDomainCheck','checkdomain.cfm',handleResponse);
}
</script>
...
</head>
<body>
...
<div class="search_domain">
<div class="search_domain_form">
Search Your Domain Here<br />
<form method="post" action="" onSubmit="CheckDomain();return false;" id="frmDomainCheck">
<input class="search_domain" name="frmURL" id="frmURL" value="Please enter your domain name here..." onfocus="if(this.value == 'Please enter your domain name here...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Please enter your domain name here...';}" type="text" />
<span id="frmGO"><input name="" value="GO!" class="search_domain_go" type="submit" /></span>
<form>
</div><!-- /# end search form -->
<div class="domain_features">
<ul>
<li><span id="DomainStatus">Type in the domain and click 'GO' to check its availability.</span></li>
</ul>
</div>
</div>
...
</body>
I used your code and then added the following for checkdomain.cfm
<cfoutput>AVAILABLE</cfoutput>
It worked just fine. In your handleResponse function, put an alert(s); statement at the top to see just what you're getting back from checkdomain.

Google AJAX Transliteration API :- How do i translate many elements in page to some language at one stretch?

I have many elements on page and all of which i want to translate to some language. The language is not the same for all fields, that is, for 1st field it may be fr and for third field it may be en then again for 7th field it may be pa.
Basically i wrote the code and it's working :-
<script type="text/javascript">
//<![CDATA[
google.load("language", "1");
window.onload = function(){
var elemPostTitles = document.getElementsByTagName("h4");
var flag = true;
for(var i = 0 ; i < elemPostTitles.length ; i++){
while(flag == false){
}
var postTitleElem = elemPostTitles[i];
var postContentElem = document.getElementById("postContent_" + i);
var postTitle = postTitleElem.innerHTML;
var postContent = postContentElem.innerHTML;
var languageCode = document.getElementById("languageCode_" + i).value;
google.language.detect(postTitle, function(result) {
if (!result.error && result.language) {
google.language.translate(postTitle, result.language, languageCode,
function(result) {
flag = true;
if (result.translation) {
postTitleElem.innerHTML = result.translation;
}
});
}
});
flag = false;
}
As you can see, what i am trying to do is restrict the loop from traversing until the result of previous ajax call is receieved. If i don't do this only the last field gets translated. My code works nicely, but because of the infinite loop, i keep getting errors from Mozilla to "stop executing scripts". How do i get rid of this? Also, is my approach correct? Or some inbuilt function is available which can ease my task? Thanks in advance :)
Why don't you call the function to check the next h4 recursively from within the detect/translate completed callbacks. Send the next recursion the next h4 using something like JQuery's next() function.
What you're doing is running the endless loop on the same thread as the outer loop.
I suggest you post a more complete question and code next time to prevent people who like to provide working answers from having to spend time guessing what you are trying to do.
Here is a working example using recursion. Unless you have thousands of items, the tail should be tolerable.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var elemPostTitles = document.getElementsByTagName("h4");
var index = elemPostTitles.length - 1;
foo(index);
function foo(index) {
var postTitleElem = elemPostTitles[index];
var postTitle = postTitleElem.innerHTML;
var postContentElem = document.getElementById("postContent_" + index);
var postContent = postContentElem.innerHTML;
var languageCode = document.getElementById("languageCode_" + index).value;
google.language.detect(postTitle, function(result) {
if (!result.error && result.language) {
google.language.translate(postTitle, result.language, languageCode,
function(result) {
if (result.translation) {
postTitleElem.innerHTML = result.translation;
}
if (--index > -1) {
foo(index);
}
});
}
});
};
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<h4>
this is some text</h4>
<input type="text" id="languageCode_0" value="en" />
<div id="postContent_0">
</div>
<input type="text" id="languageCode_1" value="hi" />
<div id="postContent_1">
</div>
<input type="text" id="languageCode_2" value="es" />
<div id="postContent_2">
</div>
<input type="text" id="languageCode_3" value="fr" />
<div id="postContent_3">
</div>
<input type="text" id="languageCode_4" value="ar" />
<div id="postContent_4">
</div>
</body>
</html>

Resources