Need a simple adjustment made to this function with data retaining variable. - javascript

I recently posted a question asking for help with storing information in a variable. I was given an answer I that I thought solved my problems. It did, but there's one issue. First, here's the post and answer I was given: https://stackoverflow.com/a/21980101/2603319
TLDR: I wanted to have a textarea where you add a value like "hey" and press submit for example, it's stored in the variable as seen in the fiddle, and then if you type "hey" again for example, you'll receive a message that says "This text is the same". If you type something new like "Hello" after, you get the message, "This text is different" but if you type "Hello" again, you'll get the message "This text is the same". The code below and in the jsfiddle work fine however my issue is, the very first time you type anything into the textarea and submit, you get the message "This text is different". What can I do to keep that from happening yet keep the functionality I want?
Here's the code and jsfiddle for it:
<textarea id="mytext"></textarea>
<button onclick="MyFunction();" type="button" value="submit"/>Submit</button>
var previousValue = null;
var currentValue = null;
function MyFunction(){
var currentValue = document.getElementById("mytext").value;
if(previousValue === currentValue){
alert('the text is the same');
}
else
{
alert('the text is different');
}
previousValue = currentValue;
}
http://jsfiddle.net/2eFD2/9/

I would have your function like this, to avoid output at the initial insert of a value by the user;
function MyFunction(){
var currentValue = document.getElementById("mytext").value;
if(previousValue === null){
//alert('first data entry'); //<-- you can put any code you want to happen when the user initially enters a value
}else{
if(previousValue === currentValue){
alert('the text is the same');
}else{
alert('the text is different');
}
}
previousValue = currentValue;
//I thought maybe you'd want to clear the textfield after the user submits as well;
document.getElementById("mytext").value = ""; //just a suggestion
}

Related

Clear the cache for a jQuery variable

I am working on sharepoint edit form, and we can define a function named PreSaveItem(), which will get executed before the form is submitted to the server, as follow:-
<script language="javascript" type="text/javascript">
function PreSaveItem(){
var result = true;
var status=$("select[id*='Status_'] option:selected").text();
if (status == "Closed") {
var analysis = $('input[id^="Analysis_"]').val().trim();
alert(analysis);
alert(Date.now());
if (analysis == "") {
alert("Please Enter Analysis before closing the item");
result = false;
}
}
return result;
}
</script>
The above script will show and alert() if the users change the status to "Closed", while they left an Input field named "Analysis" empty. but seems i am facing a caching issues when the script is reading the updated value for the $('input[id^="Analysis_"]').val().trim();. as follow:-
let say i changed the status to "Closed" + i left the "Analysis" input field empty
click on save
then i will get this alert correctly alert("Please Enter Analysis before closing the item");.
then after getting the alert, i entered some text inside the "Analysis" input field >> click on Save again.
then i will get the same error. and the alert(analysis); will still show the old empty value, while the alert(Date.now()); will show updated date-time.. so seems the var status=$("select[id*='Status_'] option:selected").text(); is being cached?
also the weird thing is that the $("select[id*='Status_'] option:selected").text() is not being cached ...
Clear value after alerting.
<script language="javascript" type="text/javascript">
function PreSaveItem(){
var result = true;
var status=$("select[id*='Status_'] option:selected").text();
if (status == "Closed") {
var analysis = $('input[id^="Analysis_"]').val().trim();
alert(analysis);
alert(Date.now());
if (analysis == "") {
alert("Please Enter Analysis before closing the item");
result = false;
var analysis = undefined;
}
}
return result;
}
</script>
Though clearly not getting what you are trying to achieve but would suggest you to update the method for selected text. It might work
suppose your select options are as follows
<select id="CountryName">
<option>India</option>
<option>Australia</option>
<option>England</option>
</select>
To get the selected text you can directly achieve selected text by:
var getSelected = $('#CountryName').find(":selected").text();

JQuery - How to check if input is comming from keyboard or not?

How can I check if input is coming from script or is inputed from keyboard to the textarea?
Is there an easy way to check that?
Im doing the form to send partly auto-generating messages where Im using drop-lists to genearte text and just pasting it to one textarea.
In have a function like:
function refresh() {
var str2 = "";
$('input[type="checkbox"]:checked').each(function() {
if (($('textarea', $(this).parent()).val()))
str2 += $('textarea', $(this).parent()).val() + " \n";
});
$('#Body').val(str2);
}
Any ideas?
You can use on keyup function like
$('#textAreaID').on('keyup',function(){
alert('its keyboard');
//do your stuff
})

Encoded value is displaying on textbox :- encodeURIComponent()

I'm calling a javascript function on OnClientClick of my button control to encode a textbox value .
That JS function calls encodeURIComponent() to encode the text value of textbox.
My Javascript function is
function Validate() {
var d = document.getElementById('<%=NoteText.ClientID %>');
var Hdn = document.getElementById('HdnProcessing');
if (d.value == '') {
alert(document.getElementById('<%=NotesMessage.ClientID %>').value);
d.focus();
return false;
}
if (Hdn.value == "Processing") {
return false;
} else {
Hdn.value = "Processing";
var headObj = document.getElementById('<%=NoteHeading.ClientID %>');
headObj.value = encodeURIComponent(headObj.value);
d.value = encodeURIComponent(d.value);
return true;
}
}
Here my inputs are textboxes ie NoteText and NoteHeading.
If anyone is reading this I was wondering is there anyway to pass the encoded text to the server without the user seeing the encoded text updating in the textbox. Currently when the user clicks the SAVE button they see the text change to the encoded text for a split second before the page refreshes. I was just curious if I could prevent the user from seeing that.
I recently provided an answer to a very similar question that should help you out:
JavaScript encode field without spoiling the display

Simple Guess my Number Game in Javascript

I'm working on a javascript program that is a simple guessing game. It comes up with a random number between 1 and 10 and provides an input field and a button for the user to make their guess. The program tells after each guess whether the user guessed too high or too low, and it keeps up with the number of guess it took the user to get the correct answer which it displays along with a "congratulations" message when they get it right.
I'm having some trouble getting it to work properly. The page displays properly, but when I enter a guess and click my submit button, nothing happens.
Here is my code:
<html>
<head>
<title>Guess My Number</title>
<script type="text/javascript">
var game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum() : function() {
this.num = parseInt(Math.random() * 10) +1;
},
checkNum() : function(guess) {
try {
guess = parseInt(guess);
}
catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
if (guess == this.num) {
alert("Correct! It took you " + this.turns + "turns to guess my number.");
return true;
}
else if(guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
}
else (guess < this.num) {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="button" value="Reset Game" onclick="resetGame()" />
</p>
</body>
</html>
I've never actually worked with Javascript before so I know this is probably a very basic thing that I'm overlooking. Any ideas as to why this isn't working correctly?
You variable guess is undefined.
Just initialize it with :
var guess = 0;
However be careful there's a possibility that num is initialize to 0. So, the user guessed immediatly without doing nothing.
var num = Math.random() *10 + 1;
BR
You should call your function in first place, one possible thing you can do is:
<input type = "button" value = "Submit Guess" onclick="guessNumber()">
now that your function is called you need to get the value entered by the user into your guess variable, which I don't see in your code, you can do it as:
Your guess:<input type = "text" name = "guess" size = "10" id="guess" /> <br />
and then in your java script initialize the variable guess as:
guess=document.getElementById("guess").value;
This should do the thing!
EDIT:
Also make sure that Math.random() returns an Integer,as others have suggested use Math.ceil() !
Several other answers have pointed out some issues in the test code:
type="submit" but no <form> tags.
Misspelled variable name tunrs instead of turns.
Use of the while loop
No event connections between the buttons and the JavaScript
This is a simple code example, and there are so, SO many ways to tackle it in JavaScript. Here is my method.
When creating a simple game board where the page does not need to be reloaded, I like to create a game object. In JavaScript you can create objects in a variety of ways. But one of the simplest is this:
var game = {};
This creates an empty object with no properties or methods. To create a couple of properties:
var game = {
num: 0,
turns: -1
};
Each of these properties can be referenced globally like var x = game.num;. To create the object with a function:
var game = {
num: 0,
turns: 0,
reset: function() {
this.turns = 0;
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
//Note: "this" lets you refer to the current object context. "game" in this case.
//There are a couple of ways to force the value to an Int, I chose parseInt
}
};
Game now has a game.reset() function that will set game.turns back to 0 and get a new game.num. Here is the full javascript code for my example (slightly different than the above examples):
<script type="text/javascript">
//Create an object to hold the game info
var game = {
num : 0,
turns : 0,
reset : function() {
//function to reset
this.turns = 0;
this.newNum();
},
newNum : function() {
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
},
checkGuess : function(guess) {
//try to convert the guess into a integer
try {
guess = parseInt(guess);
} catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
//perform strict check of equality
if (guess === this.num) {
alert("Correct! It took you " + this.turns + " turn(s) to guess my number");
return true;
} else if (guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
} else {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
Note: I didn't do a window.onload event here because those are only needed when the code will be interacting with elements on the document, or DOM elements. If you try to execute JS code in the head of the document, it gets executed instantly before the rest of the document gets loaded. This is bad if your JS code is trying to get, set, or manipulate elements in the page because you're still in the head and the body hasn't been loaded yet.
So in the case where your code needs to get access to elements of the page, often a window.onload = someInitFunction(); will be used so that the JS code will be executed after the document has completed it's load.
Below is my HTML code. It is mostly similar to your code except that I change the name attribute to id on the "guess" input to make it easier to access with document.getElementById(). Using name is helpful when you are in a form and will be submitting values to a server. Only fields with the name attribute set get submitted in that case. Often on forms you will have something like <input type="text" id="textfield" name="textfield" />. The id is used in JavaScript for easy of access, and name is used when submitting the form back to the server.
I also added onclick attributes to the buttons, and changed the input type="submit" to input type="button".
<h1>Would You Like To Play A Game?</h2>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Instructions</h2>
<p>
The game is very simple, I am thinking of a non-decimal number between 1 and 10
and it is your job to guess what that number is. If you do not guess my number
correctly on your first attempt, that's ok, you can keep guessing until you are correct.
</p>
<p>
Your guess:<input type="text" id="guess" size = "10" />
<br />
<input type="button" value = "Submit Guess" onclick="guessNumber()" />
<input type="button" value = "Reset Game" onclick="resetGame()" />
</p>
Here is a JSFiddle example that operates, I believe, the way you want it to.
update
As I was saying there are so many ways to do this. Here is an alternate way to give number selections.
A few issues with your code:
Math.random()*10 will return something that looks like 8.523525235, so you'll have a hard time matching that to any guesses. Instead, use Math.ceil(Math.random()*10). This generates a random number and then rounds up to the nearest integer.
In your JavaScript code, you're calling guessNumber() on the last line, which will execute the function as soon as the browser gets to that line. This will mean the function being executed before the user puts in any guesses. Instead you need to attach an event listener to the button, so that when the button is clicked, guessNumber() is called. Something like:
document.getElementById('button').addEventListener('click', guessNumber).
Right now you're not setting the variable guess in any way. You need to grab the value of the text box and assign that to guess. Something like:
guess = document.getElementById('textbox').value
Using a while loop is not appropriate here, since the user is using the textbox and the button to submit guesses each time. There are ways of doing this with a while loop, but let's stick with your current setup.
You want something that resembles this:
HTML:
<p>Your guess:
<input type="text" id="textbox" />
<input type="button" id="button" value="Guess" />
</p>
JS:
var rand = Math.ceil(Math.random()*10);
var turns = 0;
var guess;
document.getElementById('button').addEventListener('click', guess);
function guess() {
guess = document.getElementById('textbox').value;
if (guess == rand) {
alert('Correct! It took you ' + turns + ' turns to guess the number!');
} else if (guess < rand) {
alert('Your guess is too low. Try again.');
turns++;
} else if (guess > rand) {
alert('Your guess is too high. Try again.');
turns++;
} else {
alert('You didn\'t enter a number. Try again.');
}
}
Here's a fiddle. I added some for the reset functionality.

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

Categories

Resources