Clear the cache for a jQuery variable - javascript

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();

Related

Why is my validation method for zip codes not working correctly

I have a form that uses asp:requiredvalidator and some custom javascript to apply a red 1px border around any field that hasn't been correctly filled in.
This works perfectly, but now I want to be able to immediately remove the red border when the user correctly fills in the field.
To achieve this, I am using Jquery's focusout() method to compare the user input to a regular expression. So far I have this correctly working on every field (including email validation) except zip code. For some reason, all the validation methods I have written work perfectly except for zip code.
Here is a working email validation for example
if (id == "email1" || id == "email2") {
emailValue = e.target.value;
if (validateEmail(emailValue)) {
$("#" + id).removeClass("ErrorControl");
}
else {
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
This works perfectly and removes the red border as soon as the field losses focus and the email is valid.
But I cannot get my zip validator working, even though it works almost the exact same way.
Here is the non working zip example
//Zip code also require special validation to confirm
if (id == "zip") {
zipValue = e.target.value;
if (validateZip(zipValue)) {
$("#" + id).removeClass("ErrorControl")
}
}
//Simple zip validator
function validateZip(zip) {
var re = /^[0-9]{5}$/;
return re.test(zip);
}
Unfortunately this still removes the red border, even when I enter just letters in it! Why is this happening?
https://jsfiddle.net/hhjvstp3/
I have given both email and zip a class of ErrorControl since I cannot run asp validators on jsfiddle. This works exactly like I am describing. Email validates well, zip code removes the border no matter what.
Updated fiddle
You can see which line removes the ErrorControl class from zip
if (id == "firstname" || id == "lastname" || id == "address1" || id == "city" || id == "amount") {
//id == "zip" shouldn't be here
if (e.target.value != "") {
$("#" + id).removeClass("ErrorControl");
}
}

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

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
}

make a field mandatory using javascript

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..
<!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;
if (countryValue == "")
{
alert("field value missing");
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == "")
{
alert("state field value missing");
return false;
}
}
</script>
</head>
<body>
<form method = "post" action = "33.html">
Country: <input type="text" id="count ID">
state: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
<br>
<input type = "submit">
</form>
<script>window.onload=f1</script>
</body>
</html>
Please help.
Have a look at this since you have messed up the IDs
Live Demo
window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == "") {
alert("Please enter a country");
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert("Please select a state");
return false;
}
return true; // allow submission
}
}
PS: It is likely that POSTing to an html page will give you an error
To get the last button to do the submission
window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}
Once you've got a function to detect improper values (empty mandatory field or anything else, like a bad e-mail address for instance) you have a few different options :
disable the submit button
cancel the onclick event on the button
cancel the submit event on the form
disabling the submit button can be annoying for the user (it might flash on and off while the values are entered).
I had the same issue, but i made a extension. Using hook system to translate fields with "*", in the names, to validate like required field. This is a simple solution not intrusive where is not required addition of fields in the database, only by the use of sufix "*" in configuration of custom fields.
There is the code: https://github.com/voiski/bugzilla-required-field

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.

jQuery script fails executing for some of the users

I am using a custom form to submit data to Google Spreadsheets. When user attempts to submit the form, it is validated (with jQuery) and if the validation is passed, the main input field is being modified with jQuery and then the submission continues.
The user inputs a URL and during submission the script cuts off unnecessary parts of the link and adds IP (that is also gathered with jQ) of the user to it. After the modification is completed, the form continues submission and in result, only the modified data is being sent to Google Spreadsheet.
It works pretty well with 99% of submissions but there are several users whose browsers do not execute the script properly; i.e.: the URL they input is not being modified during the submission and thus, wrong data (unmodified) is sent to the Spreadsheet. I am not completely sure, but the problem may be caused by Firefox (but I am not 100% sure that all the faulty submission come from Firefox, if you want I could research and confirm whether it is only Firefox's issue). I have asked some of them (users, whose browsers seem not to execute script) about addons/if they had turned JS off but they say they did not do anything special with their browsers.
I am posting whole js file below so you could check whether I did some errors that could cause problems. Also, the script is running here (link), you can inspect the code to see what other jQuery stuff I use.
$(document).ready(function() {
//Tabbiing page is being initialised, doesn't really matter, I think
$.ionTabs("#fppp_taby");
//Script that checks whether user has been redirected back after submission, that's not the main problematic part yet
if (window.location.search != 0) {
var query = window.location.search.substring(1);
ideo = query.split("=")[1];
if (isNaN(ideo) || (ideo.length < 3) || (ideo.length > 10)) {
$("form").html("Wystąpił błąd podczas wysyłania Twojego zgłoszenia. Powiadom mnie o tym poprzez prywatną wiadomość podając również obecną godzinę za pomocą <a class='uline' href='http://www.erepublik.com/pl/main/messages-compose/2417512'>tego linka</a>.");
} else {
$("form").html("Dziękujemy za zgłoszenie!<br /><br />Możesz teraz przeczytać któryś z artykułów epolskiej prasy - lista wartch uwagi znajduje się po lewej stronie!");
var poZglosz = "Dziękujemy za zgłoszenie!<br />Spodziewaj się chlebków i broni od któregoś z tych graczy: Kijek93, twatwaratwa, Gregoric bądź Zawa99";
$("#poZglos").html(poZglosz);
$("#poZglos").removeClass();
}
} else {
var query = 0;
}
//Some simple stuff
$("#wlaczirc").click(function() {
$(this).hide();
$("#irc").html("<iframe src='http://webchat.quakenet.org/?channels=fppp&uio=OT10cnVlJjExPTM0OQ1f'></iframe>");
$("#irc").show("slow");
$("#info_irc").show("slow");
});
//Some data
infoPodkr = "Wklej tutaj prawidłowy link do twojego profilu!";
inputLink = $("#ffpolelinku");
//Resetting validation info in input
$(inputLink).focus(function() {
if ($(this).hasClass("podkresl") || $(this).val() == infoPodkr) {
$(this).val("");
$(this).removeClass("podkresl");
}
});
//Gathering ip
$.getJSON("http://jsonip.com/",
function(data) {
ip = data.ip;
});
//MAIN PART (executed when user pressses 'submit')
$("form").submit(function() {
//Form is being hidden (display:none class is being added)
$('aside').addClass("hidden");
//Check whether input is empty or contains error message (infoPodkr = error message vlaue), if yes, add class 'podkresl'
if (($(inputLink).val() == "") || ($(inputLink).val() == infoPodkr)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
} else {
$(inputLink).removeClass("podkresl");
}
//Tesing whether user added proper link, if not, 'podkresl' is added
//if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&##\/%?=~_|!:,.;]*[\-A-Za-z0-9+&##\/%=~_|]/.test(inputLink.val())){
if (!/http\:\/\/www\.erepublik\.com\/[a-z]{2}\/citizen\/profile\/\d{5,}$/i.test(inputLink.val())) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Split link, and get the last part of it ('wycId'), check if it's numeral, if not - add 'podkresl' class
podzielony = $(inputLink).val().split('/');
wycId = podzielony.pop();
if (isNaN(wycId)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Check whether the input class 'podkresl' class (= something was wrong in some of the steps above). If yes, remove the 'hidden' class from 'aside' which holds the form and show it to the user. If there were no errors, add the IP to the 'wycId' and additional "-n" to the end of the value and put it into input. Then, submit form.
if ($(inputLink).hasClass("podkresl")) {
$('aside').removeClass();
return false;
} else {
if (ip !== '') {
$(inputLink).val(wycId + "-" + ip + "-n");
} else {
$(inputLink).val(wycId + "-0-n");
}
}
return true;
});
});

Categories

Resources