Outdated value issue in JavaScript form - javascript

Here's the HTML:
<input type="text" placeholder="Answer..." id="ansbox1">
<input type="submit" onclick="submit1();" id="sp1">
Here's my JS:
var txt1 = document.getElementById("ansbox1").value;
function submit1() {
if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
alert("Yaay!");
}
else {
alert("Nope, its wrong!");
}
}
When I put (even the decoded matching string) in the input box, it still always shows "Nope, its wrong!".
Any error?
I referred to this, yet I still get the same issue...
JS - Check if the input field equals the solution

Since txt1 is outside the function call, it has stale data. Put it inside the function call, so it can be updated everytime.
function submit1() {
var txt1 = document.getElementById("ansbox1").value;
if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
alert("Yaay!");
}
else {alert("Nope, its wrong!");}
}

Your txt1 variable is outside the function, which could have a stale/previous value.
This variable should be put inside the function so that it's always updated:
function submit1() {
var txt1 = document.getElementById("ansbox1").value;
if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
alert("Yaay!");
}
else {
alert("Nope, its wrong!");
}
}

Related

Tried to get data from a form and append it to a global array, but for some reason the data isn't being added

I am trying to get data from a form and append it to a global array but for some reason, the data isn't being added to the array. The code should basically accept the input from the form and store it into the global array. I updated the HTML so you can see the entire syntax. The value should basically be taken from the form and placed into the global array using the "addnew" function.
function addnew()
{
//calculateAge();
//Accept values entered in form
const fname = document.getElementById('fname').value;
const mname = document.getElementById('mname').value;
const lname= document.getElementById('lname').value;
const dob= document.getElementById('dob').value;
const genderM = document.getElementsByName('male').checked;
const genderF = document.getElementsByName('female').checked;
const age = calculateAge.bYear;
const bodyType = document.getElementById('Body Type').value;
const occu= document.getElementById('occu').value;
const height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert();
}
if(mname==null || mname=="")
{
alert();
}
if (lname==null || lname=="")
{
alert();
}
if(dob==null || dob=="")
{
alert();
}
if (genderM.checked == false || genderF.checked == false){
alert();
}
if (age <=18 || age >=75)
{
alert();
}
if(height>=170 || height<=200)
{
alert();
}
if(bodyType==null || bodyType==""){
alert();
}
if(oocu==null || oocu=="")
{
alert();
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(dob);
records.push(genderM);
records.push(genderF);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
//showAll();
//<h1 class="logo"><img src="New folder/logo.jpg" /></h1>
Information.addEventListener('submit', addnew);
}
</script>
```
first of all. name attribute has nothing to do with form element.
second. Information.addEventListener('submit', addnew); has no meaning because Information is not defined.
and to the core. when submiing a form, the page refreshes defaultly, so the addNew function is aborted like all the other variables. in order to prevent it you have to do as follows.
on submit button ad an id attribute:
<button id="submit" type="submit"> Submit </button>
then on top of your JS, get the button element and add an event listener to it:
let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );
and here is the final step. on the addNew function, add an event argument. and on the begining of the function's code, fire the preventDefault method:
function addnew(event) {
event.preventDefault();
// the rest of the code here
}
by the way. you have a typo here. it should be occu.
if (oocu == null || oocu == "") {
alert();
}
good luck!

Jquery Error validation insert div using after() but cannot remove

I want to show error validation messages next to the textbox. For that, I have used after() function and inserted a div. But the div gets appended again and again whenever the field is invalid. I just want it once. Can anybody help me with it?
Here's my code:
$(document).ready(function()
{
$("#name").blur(function()
{
var name = $("#name").val();
var txt= /^[A-Za-z\s]+$/i ;
if((txt.test(name) != true))
{
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
$("#one").empty();
}
else
{
$("#one").remove();
}
});
});
You could use HTML 5 field's validity which is the standard.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Your error message here')"
onchange="setCustomValidity('')" />
You should use additional variable to store your state. Try this logic.
$(document).ready(function() {
var flag = false;
$("#name").blur(function() {
var name = $("#name").val();
var txt = /^[A-Za-z\s]+$/i;
if (!txt.test(name) && !flag) {
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
flag = true;
}
else if (flag && txt.test(name)) {
flag = false
$("#one").remove();
}
});
});

Value is not assigned to the input element returned by document.getElementsByName

I can set the value easily, below is the code:
document.getElementById("set").onclick = function() {
var d = document.getElementById("text").value;
chrome.storage.sync.set({ "data" : d }, function() {
if (chrome.runtime.error) {
console.log("Runtime error.");
}
});
window.close();
}
sync.set is working fine. I want the sync.get function to work on a different domain whose input field is like this
<input class="valueinput" type="text" name="Text_Value" size="12" value="" onfocus="select()" maxlength="6">
As you can see there is no id assigned. I am not getting the stored value in the textbox above. Below is the get code I am using.
function get() {
chrome.storage.sync.get("data", function(items) {
if (!chrome.runtime.error) {
console.log(items);
var textarea = document.getElementsByName("Text_Value");
textarea.value = items.data;
}
});
}
get();
The input box does not have any id. Please help.
document.getElementsByName returns an array-like NodeList collection, not a single element as you can see for example when debugging the code step by step.
var textarea = document.getElementsByName("Text_Value")[0];
if (textarea) { // always check if the element exists!
textarea.value = items.data;
}

How do I stop server side event getting called

I have made a method for adding an image to the page for user feedback. I have tried the method on its own and now want to use it over and over again so it matches the validation on the site.
function ValidateFields(div, imgDiv) {
var validPass = true;
var elem = document.getElementById(div).value;
if (elem == "") {
var img = document.createElement("img");
img.src = "/assets/img/errorIcon.png";
var src = document.getElementById(imgDiv);
src.appendChild(img);
validPass = false;
//document.getElementById('lbl_pdf_title').innerText = ("Please enter a title for the PDF");
}
return (validPass);
}
When I used this method by passing in the correct values it works ok, but now I want to use the method like this:
function ValidatePdf() {
ValidateFields('txt_pdf_title', 'imgPdfError');
if (!ValidateFields()) {
// make it false
}
}
I want to use the method lots of times in the ValidatePdf() but it shows the symbol then carries on to run the serverside method.
This is my button click:
<button id="btn_submit_pdf"
runat="server"
class="btn btn-default"
title="Submit PDF"
onclick="if (!ValidatePdf()) return false;"
onserverclick="btn_submit_pdf_Click">
Submit
</button>
Do I need to pass another value to the ValidateFields()
I am at a loss as why it doesn't work.But does when you pass the original values in and call the method on the button click
For multiplie validation you just need to add another boolean value:
function ValidatePdf() {
var isValidate=true;
isValidate=isValidate && ValidateFields('txt_pdf_title', 'imgPdfError');
isValidate=isValidate && ValidateFields('txt_pdf_title1', 'imgPdfError1');
isValidate=isValidate && ValidateFields('txt_pdf_title2', 'imgPdfError2');
return(isValidate);
}
Or
function ValidatePdf() {
return(ValidateFields('txt_pdf_title', 'imgPdfError') && ValidateFields('txt_pdf_title1', 'imgPdfError1') && ValidateFields('txt_pdf_title2', 'imgPdfError2'));
}
Just return the result of ValidateFields:
function ValidatePdf() {
return ValidateFields('txt_pdf_title', 'imgPdfError');
}
You can also change your onclick to:
onclick="return ValidatePdf();"
so that it returns the result of ValidatePdf, which is now the result of ValidateFields.
Wrong way, should be:
function ValidatePdf() {
if (!ValidateFields('txt_pdf_title', 'imgPdfError')) {
// alert('not valid');
}
}

Call Custom Function on Form Submit

I have a function to swap data-attribute and action in a form:
$(function() {
function SwapAction() {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
});
I want to do this upon submission of the form if the form passes validation checks. The validation JS looks like so:
var submitcount7303 = 0;
function checkWholeForm7303(theForm) {
var why = "";
if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
if (why != "") {
alert(why);
return false;
}
if (submitcount7303 == 0) {
submitcount7303++;
SwapAction(); //Calling Function
theForm.submit();
return false;
} else {
alert("Form submission is in progress.");
return false;
}
}
The form doesn't submit and I receive an error:
Reference Error: SwapAction is not defined.
Here is the form HTML with the action:
<form action="" data-action="/FormProcessv2.aspx?WebFormID=89926&OID={module_oid}&OTYPE={module_otype}&EID={module_eid}&CID={module_cid}" enctype="multipart/form-data" onsubmit="return checkWholeForm7303(this)" method="post" name="catwebformform7303" class="review-form custom">
I assume I am overlooking something simple. If I remove SwapAction(); and remove the data-action and set the form back to default it works without a problem.
How do I fix the error and implement my script?
The function is not in scope, it's within the scope of the wrapping DOM ready function, so remove that :
function SwapAction() {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
You define SwapAction() in the callback function of document ready, that's a different scope, so you can't access it in global scope.
SwapAction() is out of scope here.
If you want to use your first approach:
$(function() {
SwapAction = function {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
});
And then you can call it as you are calling in your current code.

Categories