Why does this codes stuck and doesn't work (javascript) - for-loop

This simple code makes me crazy.
It doesn't work in any browser or JSFiddle. The page won't be responsive and gets stuck.
https://jsfiddle.net/dckkj4uu/6/
Html:
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>
First number:<br>
<input type="number" id="fir">
<br>
Second number:<br>
<input type="number" id="sec">
<br>
Increment:<br>
<input type="number" id="inc">
<br>
</p>
<button id="btn">Click</button>
</body>
</html>
JS:
document.getElementById("btn").addEventListener("click", me);
var first = document.getElementById("fir");
var f = first.value;
var second = document.getElementById("sec");
var s = second.value;
var inc = document.getElementById("inc");
var ic = inc.value;
var str = "";
function me(){
for(var i=f; i<=s; i=i+ic){
str+=i;
}
return document.write(str);}
It always crashes
Edit: JSlint says no error

If you call initialize 'f = first.value' outside the event handler there won't be any value assigned to f because the code executes when the page is loaded, not after you've clicked on the submit button. Same goes with 's' and 'ic'.
This should fix the issue:
function me(){
var f = parseInt(first.value);
var s = parseInt(second.value);
var ic = parseInt(inc.value);
for(var i = f; i <= s; i = i + parseInt(inc.value)) {
str += i;
}
return document.write(str);
}

Related

validating a user's value length (javascript)

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" />';
}
}

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!

onclick calling object working ONLY in Firefox

as I stated in the title, I can get the onclick calling object only in Firefox: not in Chrome, not in IE, not in Safari.
I am pretty new to ajax and javascript in general, so I built my code around the answers you guys gave here.
I have a html page with a number of 'products': for each one of them, I have a form with hidden fields which contain the information about the product. Every form has two (submit) buttons: one is to 'add' the product to the shopping cart, the other is to take it 'off' of it.
I want to identify the button that gets clicked in order to identify the product it refers to and then add it to or cancel it from the cart list.
Here is the html code for the page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
TEST
</title>
<meta charset="utf-8">
<script src="form_submit.js" type="text/javascript">
</script>
</head>
<body>
<form id="ajax_1" name="ajax_form" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="1" /><br />
<button id="ajax_1" type="submit" name="on">On</button>
<button id="ajax_1" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<form id="ajax_2" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="2" /><br />
<button id="ajax_2" type="submit" name="on">On</button>
<button id="ajax_2" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<form id="ajax_3" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="3" /><br />
<button id="ajax_3" type="submit" name="on">On</button>
<button id="ajax_3" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<div id="responseArea"> </div>
</body>
</html>
This is the script code:
window.onload = checkButton;
var xhr = false;
var on;
var stnz;
var opz;
var url;
function checkButton() {
var el = document.getElementsByTagName('button');
for(var i=0; i<el.length; i++){
el[i].onclick = function (e) {
// Capturing the event
e = e || window.event;
var targ = e.target || e.srcElement;
on = (targ.name == 'on') ? true: false;
var form = document.getElementById(targ.id);
url = form.action;
stnz = form.stnz.value;
opz = form.opz.value;
makeRequest();
return false;
};
}
}
function makeRequest(){
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr){
var data = "stnz=" + stnz + "&opz=" + opz + "&act=";
if(on){
data = data + "1";
} else {
data = data + "0";
}
xhr.onreadystatechange = showContents;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(data);
}
}
function showContents(){
if(xhr.readyState == 4 && xhr.status == 200) {
var return_data = xhr.responseText;
console.log(return_data);
} else {
var return_data = "Sorry, but I couldn't create an XMLHttpRequest";
console.log(return_data);
}
/*document.getElementById("responseArea").innerHTML = return_data;*/
}
The test.php file is just:
<?php
if (isset($_POST['stnz'],$_POST['opz'],$_POST['act'])){
$stnz= $_POST['stnz'];
$opz = $_POST['opz'];
$act = $_POST['act'];
echo "Stnz: " . $stnz . ", Opz: " . $opz . ", Azt: " . $act;
}
?>
Please, help me fixit this thing for Chrome, IE and Safari....
Also, is there a better way to get the same functionality? (maybe not using forms?)
Thanks a lot!
each browser has its own event handling method , use a library like jquery to be able to handle all the browsers .
$(el[i]).click(function(e){});
using jquery isn't the only solution you can optimize your code for every browser by adding the browser specific codes but that is a recipe for disaster.same goes for your ajax request(cross browser problems).
jquery designed with all the browsers in mind , so you write just one code and jquery handles the browser specific stuff .
example for your ajax with jquery :
https://api.jquery.com/jQuery.ajax/
$.ajax({
url : url,
type:'POST',
data:{"stnz" : stnz , "opz" : opz , "act" : (on ? 1 : 0)}
success : function (data){
},
error:function(){}
});

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