Javascript loop and final alert, FOR or WHILE? - javascript

Novice in programming, this is my practice the code, I can't figure out how to code my concept and I am not sure if I need to use for or while for the following requirement:
After 3 or 5 times the user fails to input something in the prompt box, then a final alert shows up telling something like "No more Opportunities!" and then turns the div background grey color.
Any help will be welcome to help me improve.
JS
var mObjt = {
userInput: "",
setInput: function(){
document.getElementById("div1").innerHTML = mObjt.userInput;
},
conRequest: function(){
if(mObjt.userInput != ""){
mObjt.setInput();
} else {
alert("There is no input!");
mObjt.popRequest();
}
},
popRequest: function(){
mObjt.userInput = prompt("Enter a word:");
mObjt.conRequest();
}
}
HTML:
<div id="div1" style="width:200px; height:30px; border:1px solid;"></div>
<button type="button" onClick="mObjt.popRequest()">Add Property</button>

You shouldn't use any type of loop for that. Keep a counter variable. Every time the user fails, increase the counter. When the counter gets to 5, do whatever needs to be done.
var failCount = 0;
function handleInput() {
// This is a totally fake example just to show you want to do
if(input) {
// Input valid, yay
} else {
// Input invalid
failCount++;
if(failCount >= 5) {
// Disable your stuff
alert('Oh no, input failed: you have no more remaining attempts');
} else {
alert('Oh no, input failed');
}
}
}

Related

Javascript won't trigger not if nor else

I have JavaScript code that must move a div up and down. When I click it I want it to go up, then when I click the second time I want it to go down. My code is this:
function why()
{
if (document.getElementById("newton").style.bottom == 23) {
alert("I entered the IF");
document.getElementById("newton").style.bottom = 0;
}
else {
alert("I entered the ELSE");
document.getElementById("newton").style.bottom = 23;
}
}
The strange thing is that the first time I click the div it goes up and tells me the ELSE part was executed, but after this, clicking it won't produce any effect, it wont go back down. Why is this?
You need to specify a unit, like % or px or whatever.
function why() {
if (document.getElementById("newton").style.bottom == '23px') {
alert("I entered the IF");
document.getElementById("newton").style.bottom = 0;
} else {
alert("I entered the ELSE");
document.getElementById("newton").style.bottom = '23px';
};
}
<button id="newton" onclick="why()">click</button>
But I would toggle a class instead and put this change in CSS.
function why(el) {
el.classList.toggle('up');
}
#newton {
bottom: 0;
}
#newton.up {
bottom: 23px;
}
<button id="newton" onclick="why(this)">click</button>
I found out that if other js functions are wrong, it can affect my whole code,even other functions. The code was right, but since another function was wrong that made my code not work...Thanks for the toogle the class advice, I will implement it ;)

Jquery Input Text

I have been searching for a similar question/answer and didn't see one. Apologies in advance if this is a duplicate.
I am creating a text-based game in JS. This is my 1st time creating a project from scratch. All the text happens in the #dialog div and I want to have the user input to correspond to if-else function choices and generate text in the for the new options.
I have the first transition(the text from intro game changes to the text in scene one when clicked)working. What is not working is the choice selection text input. Anything I enter refreshes the game. I also put in an alert to test it and that does not run.
Another question I have is if the variables for the new choices which I have put in the if/else statement will run as coded or if I need to make changes. Some options will occur more than once so I will want it to run from inside multiple scenes.
HTML
<div id="dialog">
</div>
<div class="form">
<form id="my-form">
<input type="text" id="userData" placeholder="enter move here">
<button type="submit" class="btn">play</button>
</form>
</div>
JS
// game dialog box / adds paragraph to the #dialog div
// User move - form input
var addParagraph = $('#dialog');
var userMove = $("#userData").val();
//intro game text
var introGame = $(function () {
$(addParagraph).append('<p> My Text.. </p>');
});
//1st scene of game. Player chooses 1,2 or 3. Choice triggers new text in dialog box and new set choices or player outcomes.
var scene1 = $(function () {
$(introGame).click(function() {
$(addParagraph).text('Move Question Text');
$(addParagraph).append("<p> 1.Choice Description </p>");
$(addParagraph).append("<p> 2.Choice Description </p>");
$(addParagraph).append("<p> 3.Choice Description </p>");
$(addParagraph).append("<p> Enter: 1, 2, or 3 below </p>");
var playMove = function() {
$("#my-form").submit(function() {
var text = userMove;
var move = template(text);
if(text == '') {
return false;
} else if(text == '1') {
$(scene1).click(function () {
evasiveManuevers();
});
}else if(text == '2') {
$(scene1).click(function () {
lightSpeed();
});
} else if(text == '3') {
$(scene1).click(function () {
fightEnemy();
});
} else {
alert("Working!");
}
});
};
});
});
Thank you in advance!
I guess what you are doing wrongly is expecting that this
var userMove = $("#userData").val();
will change during the game. $("#userData").val() is a value, not a function, so if I understand what you want correctly, you should create a getter like this
var getUserMove = function(){ $("#userData").val(); };
and use it as var text = getUserMove();. But it's not clear where your
var addParagraph = $('#dialog');
var userMove = $("#userData").val();
code is (is it inside some handler? I'd recommend to show the whole code as one script, not separate it into some parts).
I don't think your IF statements will run like that. You could do your IF condition testing inside your scene1 click function like this:
$(scene1).click(function (){
if(text == '1') {
evasiveManuevers();
} else {
if(text == '2') {
lightSpeed();
} else {
// etc
}
})

jquery validation loop producing false positives

$(document).ready( function()
{
// hides the story and error text when the page loads
$('.errorText').hide();
$("#story").hide();
// global variables for the blanks and the textarea forms
var input = $("form").children();
var storyBlank = $('#story').children();
// Main Event on Click
$('button.submit').on( "click", function (event)
{
// if the form is not validated, highlights errors and prevents the submit from going through
if(!validate())
{
event.preventDefault();
}
// if the form is validated, fills the blanks in the story and displays it
else
{
fillInTheBlanks();
}
});
// Checks to see if there are any empty fields and highlights them if they are empty
function validate()
{
console.log('validate() initiated')
var success = false;
errcnt = 0;
cnt = 0;
while (cnt < 9)
{
if (input.eq(cnt).val().length == 0)
{
errcnt++;
input.eq(cnt).removeClass("hide");
console.log('errorcount', errcnt, 'at input', cnt);
}
else if (input.eq(cnt).val().length !== 0 && !(input.eq(cnt)).hasClass("hide"))
{
input.eq(cnt).addClass("hide");
}
cnt++;
}
if (errcnt == 0)
{
success = true;
}
return success;
}
// Fills in the blanks of the story
function fillInTheBlanks()
{
console.log('fillInTheBlanks() executed');
var blankCount = 0;
while (blankCount < 9)
{
storyBlank.eq(blankCount).empty().append(input.eq(blankCount).val());
blankCount++;
}
$("#story").show();
}
});
I am trying to make a mad libs style page with 9 textboxes for input. I am running into two problems.
First, when I click submit with all textboxes empty, only the the first four show an error (this is done in css, I have two classes on all the textboxes "error hide", I remove the class hide in my loop to show the error).
The second problem I'm having is if I click submit with text in all the textboxes, my validate functions errorcount goes up to 4 errors at every other textbox. I've even tried '$('input').eq(0).val().length == 0' for every textbox in the index and it's returning false every time. I don't understand how it's getting into that if then statement if it doesn't satisfy the argument.
i don't understand your problem, but if is validation on inputs empty... using
http://parsleyjs.org/

Why is my .blur() code only working on second blur?

I have an input, when the user enters something, my script sends the info over to a php script, which returns whether or not the entered text can be used.
If the text can not be used, it disables the submit button and adds a class to the reult text.
The problem have is strange, the ajax works, the result is returned, but the button disabling and adding of the class doesn't happen unless you focus and blur the input a second time.
Here is my code:
$('#alias').blur(function() {
if ($('#alias').val()) {
var aliascheck = $('#alias').val();
$(".aliascheck").load('checkalias.php?alias='+aliascheck);
var result = $('.aliascheck').text();
if (result.indexOf("Taken") != -1) {
$('#shorten').attr("disabled","disabled");
$('.aliascheck').addClass('error');
} else {
$('#shorten').removeAttr("disabled");
$('.aliascheck').removeClass('error');
}
}
});
The code is live here: http://markhenderson.ws/dev/tmtmu/
To replicate the "taken" event, enter "taken" as the alias. Any thing else will return available.
Does anyone know why this is happening?
Thanks
You need to put the code after the .load call into a callback function of the async call.
Something like:
$('#alias').blur(function() {
if ($('#alias').val()) {
var aliascheck = $('#alias').val();
$(".aliascheck").load('checkalias.php?alias='+aliascheck, function() {
var result = $('.aliascheck').text();
if (result.indexOf("Taken") != -1) {
$('#shorten').attr("disabled","disabled");
$('.aliascheck').addClass('error');
} else {
$('#shorten').removeAttr("disabled");
$('.aliascheck').removeClass('error');
}
});
}
});

make use of the enter key

I have a list of urls(div) underneath an input field(div). I need the ability to come down in the list and than by hitting enter this will trigger some function designated to the url. This is the fidle: the script
Over the last days I have tried to much things to explain, but in conclusion none of it worked. Help would be appreciated.
After this line of code :
// set timers to do automatic hash checking and suggestions checking
setInterval(checkHash,500);
setInterval(checkSuggest,500);
Insert this :
$('#searchbox').keyup(
function (e){
var curr = $('#suggest').find('.current');
if (e.keyCode == 40)
{
if(curr.length)
{
$(curr).attr('class', 'display_box');
$(curr).next().attr('class', 'display_box current');
}
else{
$('#suggest li:first-child').attr('class', 'display_box current');
}
}
if(e.keyCode==38)
{
if(curr.length)
{
$(curr).attr('class', 'display_box');
$(curr).prev().attr('class', 'display_box current');
}
else{
$('#suggest li:last-child').attr('class', 'display_box current');
}
}
if(e.keyCode==13)
{
var search_terms = $('.current a').text();
// perform a search with this text...
doSearch(search_terms,true,false);
//update the search textbox
$('#searchbox').val(search_terms);
}
})
And don't forget to delete the previous code at the bottom...

Categories