Check if button has been pressed - javascript

I want to add an if statement that checks if the user is undefined for my program. It should alert: "no more profiles".
The problem is that my "likeId" is undefined to start with and I will get the alert first time i run the function. I would like to know that I can make an if statement that checks if a certain button has been pressed exactly one time.
This is my code:
if (localStorage.getItem('likeId') == "undefined"){
alert("no more profiles to swipe")
}
My code should look something like this:
if (localStorage.getItem('likeId') == "undefined" && Button has been clicked exactly one time){
alert("no more profiles to swipe")
}

Just add a counter when the function tied to the button is called. You then check if buttonClickedCounter == 1 and you should be good to go.

Related

Why does my while loop with an if statement not work properly?

i am trying to code a to do list in java script, where a prompt will ask the user what they want to do and then the user has 3 options, either "new" to add a new element or "list" to check the elements already added or "quit" to quit the loop.
i tried changing the syntax by changing the position of the semicolons but it only resulted in a never ending loop which crashes my laptop!
var todo=[];
var answer=prompt("what do you want to do?");
while (answer!=="quit") {
if (answer=="list") {
console.log(todo);
}
else if (answer="new") {
var newtodo=prompt("what do you want to add?");
todo.push(newtodo);
}
}
alert("ok we're done here");
when i open the HTML file that my script is attached to, the first prompt appears as expected, when i type in "quit" it quits the loop as expected and shows the alert but when i type in "new" it keeps asking me what do u want to add? no matter what i type and it just never ends. Also when i type in list it keeps asking me what do u want to add even though it's supposed to list my array. i think i have done a mistake in the syntax but i don't know what.
The issue here is that you are only prompting once, before the while loop.
Fix: at the end of the while, prompt again:
var answer=prompt("what do you want to do?");
while (answer!=="quit") {
if (answer=="list") {
console.log(todo);
}
else if (answer=="new") { //plus here it's '==', not '='
var newtodo=prompt("what do you want to add?");
todo.push(newtodo);
}
answer=prompt("what do you want to do?");
}

is there a way to stop a form from processing based on true or false using java script

/*--------------------SUBMIT FORM -------------------*/
//Validate Form Fields
function FormValidation()
{
// validation fails if the input is blank
var verdba =document.getElementById('verdba').value;
if(verdba.value == "") {
alert("Error: VERDBA FIRST!");
verdba.focus();
return false;
}
// validation was successful
return true;
processForm();
}
function processForm() {
// window.alert("processForm Reached"); // (Stub)
// Collect Values from the Form
// First section and verification
var callback = document.getElementById('callback').value;
var verdba = document.getElementById('verdba').value;
var comments = document.getElementById('comments').value;
// Concatenate the Page Content
var pageBody = " CB#:"+callback+" "+verdba+comments;
pageBody += "";
window.clipboardData.setData('Text',pageBody);
//Hides table on submit
$("#forms").hide();
$(".myClass").hide();
//Copies pagebody to clipboard
var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
// Hides table with clear button
function cleartable(){
$("#forms").hide();
$(".myClass").hide();
}
I have included a very bare bones example in a fiddle.
I noticed on the fiddle that it doesn't fully work but in the HTA I have it does work. What it does is collects input fields and option fields by id, concatenates them into what I call a note. It also copies the clipboard data to a text area.
What I want is to be able to click submit and have it collect the form data and check to see if two fields were used or not.
So in the phone number field I need to be sure a phone number is entered ( does not really matter to me if it checks that its a certain amount of digits or that it is digits at all as long as it isnt blank) and next check to see if the option box was selected, either yes or no, again not blank.
Upon discovering one or both were left blank or not selected I would like the process to stop and notify the user that it needs to be done. I would like it to give them a chance to fix it and then resubmit.
The problem I am having is that I can't get both to happen.
I have it where it collects the data and checks for the data, but the problem I ran into is that it doesnt care if its blank and you click ok, it still submits the request anyway and then clears the forms.
I just cant seem to figure out how to get both things working in one swing.
I hope someone can shed some light on this as it has been bugging me for days with endless online research and failed attempts.
https://jsfiddle.net/joshrt24/roqjoyhr/1/
At the end of your function FormValidation(),
// validation was successful
return true;
processForm();
}
You have put return true, before your function has chance to call the processForm, return will immediately exit your function.
Fix, just call processForm() first.
// validation was successful
processForm();
return true;
}

Disable Inputs on Dropdown Change

So I'm working on a webform right now and I need to disable all forms of input once one has a specific value. Is there an easy way to handle as soon as that dropdown gets to that value?
Currently I'm doing this:
setInterval('check()', 5000);
function check() {
// Disable all fields if the answer was no.
if ($("#has_contract").val() == 0) {
disable();
}
function disable() {
$("#inputs *").prop('disabled', true);
alert("There is no contract, please get a contract.");
}
has_contract is my element, and #inputs contains all of the inputs I would like to disable if #has_contract's value is 0.**
But this isn't ideal.
Is there a better way to do this rather than constantly checking every X amount of seconds?
Instead of checking for the value every 5 seconds, you can check the value on change.
// collect elements
var $hasContract = $("#has_contract");
var $inputs = $("#inputs input");
// on change, check the input
$hasContract.on('change', checkForm);
// Checks the hasContract input for a value
// of 0. If it does, disable the form.
function checkForm() {
if($hasContract.val() == 0) {
$inputs.attr('disabled', true);
}
}
Also, when you use setTimeout, or setInterval you don't have to use a string. Javascript supports passing functions as variables. See below.
// Do NOT do this
setInterval('check()', 5000);
// Do this instead
setInterval(check, 5000);
// or this
setInterval(function() {
//preform the check...
}, 5000);
I'm not completely certain that I understand your requirements, but would this work for you?
The below assumes that #has_contract is a <select> element:
$("#has_contract").change(function() {
if ($("#has_contract").val() == 0) disable();
});
First off, you should cache the elements as a variable and then run the function against that variable.
var myInputs
$(document).ready(function(){
myInputs = $("#inputs input"); // or '#inputs *' if you're excited about the asterix
});
Second thing, if I'm reading your setup correctly, you're going to pop an alert box every 5 seconds until the user has selected 'yes' to the contract. That will get QUITE annoying and they probably won't want to open a contract with you after that.
Without actually seeing your page, I'd imagine a better solution would be to check for the contract=yes when the click a submit button of some sort on the page.
$('#mySubmitButton').click(function(){
if ($("#has_contract").val() == 0) {
disable();
}
});
But maybe go one step further, what you really want to do is give them access to the form once they agree to the contract. So you should have the form disabled by default (coded into the html that everything is disabled), and attach a function to the 'yes' button that enables the form. Additionally, you can attach a function to the 'no' button that re-disables it, if they had previously clicked 'yes'.
$('#myYesBtn').click(function(){
myInputs.prop('disabled', false);
});
$('#myNoBtn').click(function(){
myInputs.prop('disabled', true);
});

How can I make this username suggestion work in javascript?

I have an application that requires both first name and last name. I need to have the username field automatically fill up as the user types in their first and last names to suggest a username. Right now, it works to a degree. This is the function that executes on a keyup for the name fields.
suggestUsername: function() {
var username = this.$('#user_login_field').val();
var first = this.$('#user_first_name_field').val();
var last = this.$('#user_last_name_field').val();
if(first == '' && last == ''){
this.$('#user_login_field').val('');
} else {
this.$('#user_login_field').val(first+'.'+last);
}
},
This works unless the user adds something to the username manually and then goes back to one of the name fields and enters something else. In the case that that happens, whatever the user added manually disappears. Not sure how to go about fixing it
Add an jQuery focus handler to the #user_login_field that unbinds the keypress events from the first and last name fields. (http://api.jquery.com/focus/)
$('#user_login_field').focus(function (e) {
// Unbind the keyup events
$('#user_first_name_field').unbind('keypress');
$('#user_last_name_field').unbind('keypress');
});
you can add a
$('#user_last_name_field').blur(function(){
//do username suggestion
})

$.get() troubles before submitting page

Think a shopping basket with some "goods" in it.
I have a <li> list of elements and each of them has a field containing a number - the amount.
Conceptually this is what i want: When the user presses a button, i loop through each <li> element picking the amount. Then i do a $.Get() to call the server with the goods id + the amount to check if the store has enough of the particular item. The server replies either True og False.
This reply is temporary stored in a html field.
Now after the looping is done, i check if there were a False reply on any of the goods.
If so i highlight the "false" items. Or else i simply submit.
OK, the problem is that my code seams to continue past my $.get() call-back function, so the final check to see if any false was returned is evaluated before the $.get() actually receives a result from the server.
Anyway this is what i think is happening...
Now lets look at some code:
var tmp = new Array();
var id = '';
var c = '';
var n = 0;
var z=0;
$('#basket').find('li.list').each(function() {
c = $(this).find('input.fldamount').val(); // this is the amount field
id = $(this).attr('id'); // this is the id no of the item
$.get('./(RPC)?OpenAgent&cmd=movewhcheckamount&unid='+id+'&count='+c, function(data) {
$('#RPCResult').val(data); // i store the returned value in a html field
if ( $('#RPCResult').val() == "true" ) {
tmp.push( id+'|'+c ); // if true is returned, i push the id & amount to an array
} else {
$(this).addClass('red'); // else i tag the item
n=n+1; // and then increment a counter
}
} ); // $('#basket')
var t = window.setTimeout( function() {
if (tmp.length > 0 && n == 0) { // if i got items in the array AND my false counter is zero
$('#SelectedArtikler').val( tmp.join(";") ); // then i store the array as text in a field
document._FlyttArtikel.submit(); // and submit
} else if (n > 0) {
// show a popup
alert("You're trying to move more items than exists...");
} else {
alert("ops, nothing to move..."); // should never end up here...
}
}, 1000);
window.clearTimeout(t);
As you can see, i have tried to counter-act the code running past my call-back function with a setTimeout, so that i basically wait a sec to give the server time to respond.
I did have another loop around the setTimeout the continued as long as my #RPCResult field was empty, but that resulted in an infinite loop.
I have the #RPCResult field visible so i can see what happens and what i see is that the popup "You're trying to move more items..." is shown and RIGTH AFTER i press ok on that popup THEN the #RPCResult field gets the result true/false.
I now some of the code can be optimized but what i'm interested in right now is getting the $.get() result in a proper fashion.
Thanks in advance ;-)
You're going to have to place the code that's going to run when all the "$.get()" calls are finished inside the callback routine. That's the only place where you can be sure that you've actually gotten the server response(s). Keep a counter of how many calls have returned, and when the counter increments up to be equal to the total number of items, then you know that all of the responses are available.
Thus:
var basketSize = $('#basket').find('li.list').length, completed = 0;
gives you the number of items and initializes the counter. Inside the callback function passed to "$.get()" you can then do something like this:
if (++completed === basketSize) {
// code currently in the "setTimeout()" callback
}
Your code already appears to be doing some of this work (the "n" variable that you increment).
Now, that said, I'll also note that it's quite crazy to perform separate HTTP transactions for each of your "items". You should bundle them all up into one HTTP request that returns a list of answers.
Also, there's really no point at all in storing the response to the "$.get()" in that "RPCresult" field; just examine the value of "data", since nothing ever looks at "RPCresult" again anyway.

Categories

Resources