I wrote a very quick javascript function to validate a very small form on an internal form used in our office. However, someoner today told me that it doesnt work in Edge, the code does not ever enable the submit button.
I console.log out the var values every time the function runs, and in edge, the vars are forever undefined. It seems like Edge does not respect "document.forms["abc"]["xyz"].value", but I cannot find any documentation or notes to support that.
I should clarify, I am not a javascript pro, I uyse it very sparingly, and in simple ways to get smal tasks done like this, so please dont judge my code too hard, haha.
Console Log:
q1=undefined
q2=undefined
q3=undefined
q4=undefined
My code is below, its pretty simple, nothing fancy..
function fieldcheck(){
var q1=document.forms["datacollect1"]["q1overall"].value;
var q2=document.forms["datacollect1"]["q2understand"].value;
var q3=document.forms["datacollect1"]["q3time"].value;
var q4=document.forms["datacollect1"]["q4recommend"].value;
console.log("q1="+q1+"\n"+"q2="+q2+"\n"+"q3="+q3+"\n"+"q4="+q4);
document.getElementById("datacollectsubmit1").disabled = true;
if (q1 && q2 && q3 && q4){
console.log("q1234 set");
document.getElementById("datacollectsubmit1").disabled = false;
}
}
I call the above on every click with:
document.onclick = function(){
fieldcheck();
}
Anyone have any clue as to why Edge is playing games? Or what I can substiture for document.forms.value that will work across other browsers and Edge too? Thanks.
Your above code is working in MS Edge. Possible that some other code caused this issue. I suggest you to take the code below and run it in MS Edge.
Code:
<!doctype html>
<head>
<script>
function fieldcheck(){
var q1=document.forms["datacollect1"]["q1overall"].value;
var q2=document.forms["datacollect1"]["q2understand"].value;
var q3=document.forms["datacollect1"]["q3time"].value;
var q4=document.forms["datacollect1"]["q4recommend"].value;
console.log("q1="+q1+"\n"+"q2="+q2+"\n"+"q3="+q3+"\n"+"q4="+q4);
document.getElementById("datacollectsubmit1").disabled = true;
if (q1 && q2 && q3 && q4){
console.log("q1234 set");
document.getElementById("datacollectsubmit1").disabled = false;
}
}
document.onclick = function(){
fieldcheck();
}
</script>
</head>
<body>
<form name="datacollect1" onsubmit="return fieldcheck()" method="post">
Name: <input type="text" name="q1overall"><br>
Name1: <input type="text" name="q2understand"><br>
Name2: <input type="text" name="q3time"><br>
Name3: <input type="text" name="q4recommend"><br><br>
<input type="submit" id="datacollectsubmit1" value="Submit">
</form>
</body>
</html>
Output in MS Edge browser:
Related
Firstly, I am sorry to anyone that finds this post more than a little trivial, but I am currently sratching my hair out on, at first sight, is a form posting matter.
I am developing an ASP.NET MVC 6 application which is running perfectly in Chrome and Edge, but recently, I was informed that it would also need to be able to run on IE11.
My issue is when a submit the form.
$("#js-form").on("submit", function (e) {
document.getElementById("DefinitionID-error").style.visibility = "hidden";
document.getElementById("DefinitionID-error").textContent = "<some text>";
document.getElementById("DefinitionID-error").style.visibility = "visible";
}
The code appears to execute in the IE11 debugger, with no error messages, but on screen the original text held in #DefinitionID-error does not change.
The version of IE11 I am using, is the super special version that ships with Windows 10.
Other code I have tried include:
$("#js-form").on("submit", function (e) {
$("#DefinitionID-error").hide();
$("#DefinitionID-error").text("<some text>");
$("#DefinitionID-error").show();
}
$("#js-form").on("submit", function (e) {
$("#DefinitionID-error").html("<span id='DefinitionID-error'>Some text</span>");
}
$("#js-form").on("submit", function (e) {
document.querySelector("#DefinitionID-error").textContent = "<some text>";
}
$("#js-form").on("submit", function (e) {
document.querySelector("#DefinitionID-error").innerHTML = "<span id='DefinitionID-error'>some text</span>";
}
All of these work in Chrome and funnily enough Edge, but not in IE11.
NEW Example that also does not work
$("#js-form").on("submit", function (e) {
$("#DefinitionID-error").hide();
$("#DefinitionID-error").text("Some text");
$("#DefinitionID-error").show();
}
UPDATE
If I take the jQuery code, or the javascript code and run it in the debugger in IE11. it works, so it must have something to do with the submission, maybe.
I made a test with code below on windows 10, Internet Explorer 11. It is working fine on Ie 11.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#clk").click(function(){
$("#js-form").submit();
console.log(222);
});
$("#js-form").on("submit", function (e) {
console.log("start");
$("#DefinitionID-error").hide();
$("#DefinitionID-error").val("Some text");
$("#DefinitionID-error").show();
alert("Form submitted");
});
});
</script>
</head>
<body>
<button id="clk">Click me to submit form</button>
<form id="js-form">
First name:<br>
<input type="text" id="DefinitionID-error" name="DefinitionID-error" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output in IE 11:
I have this pesky problem with my code that I think is a runtime error because it shows up when I run the program and actually stops it. I used an error console to show me where the error is, but I can't make sense of it. If anybody can point me in the right directions without giving me the answer I'd appreciate it. Here is the code:
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function changeQuote() {
quotes = new Array;
quotes[0] = "Laughter is the best medicine.";
quotes[1] = "Never look a gift horse in the mouth.";
quotes[2] = "One good turn deserves another.";
quotes[3] = "The early bird catches the worm.";
quotes[4] = "Two is company, three is a crowd.";
var newQuote = quotes[Math.round(Math.random()+quotes.length)];
document.quoteform.quote.value = newQuote;
}
var tick = setInterval("changeQuote()");
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<form action=""name="">
<input type="text" size="50" name="quote" /><br />
</form>
</body>
</html>
I also have two image of the error console message:
I have PHP form validation rules working but I also don't want valid but nonsense real human-being spams. Currently, the JavaScript code below gets the timestamp of the page loaded time and the timestamp of the form submission. If the difference is below 18 seconds it asks 'are you superman?' in an alert box and doesn't allow the user to submit until time arrives.
Q1 ) Date.now() is supported by ie9+. Which alternative function achieves the same work in ie7+ ? (reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Browser_compatibility)
Q2 ) Does this function itself has security gap? I ask because I suspect of document.getElementById('PageLoadTime').innerHTML = pageloaded code if variable pageloaded could be edited from outside!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>trial</title>
</head>
<body>
<div>user page loading timestamp: <span id="PageLoadTime"></span></div>
<div>form submission timestamp: <span id="submitTime"></span></div>
<div>time difference: <span id="difference"></span></div>
<script>
var pageloaded = Date.now();
document.getElementById('PageLoadTime').innerHTML = pageloaded;
function GetSubmitTime(pageloaded) {
document.getElementById('submitTime').innerHTML = Date.now();
document.getElementById('difference').innerHTML = Math.floor((Date.now() - pageloaded)/1000);
if ( Math.floor((Date.now() - pageloaded)/1000) < 18 )
{
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false; // for IE as dont support preventDefault;
}
alert("are you superman?");
}
}
</script>
<form method="post" action="my home page" onsubmit="GetSubmitTime(pageloaded)">
<input type="text" id="e1" name="n1">
<input type="submit" value="send" >
</form>
</body>
</html>
Date.now() returns what new Date().getTime() returns, and the latter has been supported essentially forever.
Setting the innerHTML of an element to a system timestamp is not a security risk.
Nothing in the client is safe from user tampering. Anybody using your form can force the form to be submitted without any regard to your time check.
Answer to your first question. Put the following at the top of your JavaScript and you can use Date.now() even on IE < IE9.
Date.now = Date.now || function() { return +new Date; };
console.log(Date.now()); // 1406206659562
Furthermore, your code in general is fine, though the security on the client side is always relative.
So I have been working on this for a couple of days and as a newbie, I think the answer will really help my understanding of JavaScript.
I have a page that contains a form -- when a user submits the form a new window opens with form variables embedded within text in new window. It works fine.
The problem I am having is I want to add an alert to the new window if the user onClick types in NY || New York || NJ || New Jersey. I tested my if function (I left out the else after doing some research since else is really do nothing.
The way I want it to work is if someone types one of those four variables, a new window opens with the alert. If they don't type in one of those variables, only the new window opens.
I prepared a truncated test code which I'll put below. I know there are better ways to do this then the code I have written, and I bet there are probably easier ways with libraries, jquery, etc., but I would love for someone to show me how to add the askForHelp function so it will open the alert in the new window with code I have written. Again, that's b/c this is my knowledge base at this point, and it would help me see how to really write a statement. Thanks in advance for any help offered.
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="utf-8">
<script type="text/javascript">
function newWindow() {
allInfo= open("", "displayWindow");
allInfo.document.open();
allInfo.document.write('<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body>');
allInfo.document.write(document.getElementById ('state').value);
allInfo.document.write('<p>' + document.getElementById ('zip').value);
allInfo.document.write('</section></body></html>');
allInfo.document.close();
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if (volunteer == "New York" || "NY" || "New Jersey" || "NJ") {
allInfo.document.open.alert("test test test"); //Do I put the statement here?
} // else do nothing
}
</script>
</head>
<body>
<script type="text/javascript">
</script>
<form id="infoForm" method="post" name="infoForm">
<p>State: </p>
<p><input type="text" id="state" placeholder="State or Region"></p>
<p>Zip: </p>
<p><input type="text" id="zip" placeholder="Zip code" required /></p>
<p><input type="button" value="Submit Information" onClick="newWindow(), askForHelp()" ></p> <!-- Should askForHelp() be here? -->
</form>
</body>
</html>
You have 3 problems in your code:
1- You are trying to get a value for element with id=country and you don't have any element with id=country
allInfo.document.write('<p>' + document.getElementById ('country').value);
2- alert() function is attached to the window object not to the document object. So when you want to call the alert in the new window, you should call it like this:
allInfo.alert("blah blah");
3- The If condition in your code will always return true it should modified and be like this:
if((volunteer == "New York") || (volunteer =="NY") || (volunteer =="New Jersey") || (volunteer =="NJ"))
I have made the above modifications in this jsFiddle. Please check it.
Since I'm using JSFiddle, it won't let me put document.write but you can still how it works.. Check out this Fiddle, below are the changes that I made..
HTML:
<p><input type="button" id="submit-btn" value="Submit Information" ></p>
JS:
function newWindow() {
alert("New Window");
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if (volunteer == "New York" || volunteer == "NY" || volunteer == "New Jersey" || volunteer == "NJ") {
alert("test test test");
}
}
document.getElementById('submit-btn').addEventListener("click", function(){
newWindow();
askForHelp();
});
Most my work is done running on Webkit stuff and using Chrome's dev tools. But this code doesn't run in Firefox; it doesn't even throw a console error so I have no idea what's wrong. Any ideas. I'm sure its terribly easy. My code is designed to look throw a div for a specific syntax "t_" "r_" which are references to an external document; I'm trying to find all said references and replace them with hyperlink. I"m a novice JS coder so sorry for the naiveness you'll undoubtedly see in here.
(I'm using FF 22.0)
<!DOCTYPE html>
<html>
<head>
<script>
function pre_forwarder(){ //First Step
patt_1=/\[r_/g;
patt_2=/\[t_/g;
patt_S_and_R_1 = "[r_";
patt_S_and_R_2 = "[t_";
forwarder(patt_1,patt_S_and_R_1);
forwarder(patt_2,patt_S_and_R_2);
}
function forwarder(Pattern,Pre_SearchReplace){
rule_string = document.getElementById("divid");
rule_string = rule_string.innerText;
var patt1 = Pattern;
while (patt1.test(rule_string)==true)
{
begin_string = patt1.lastIndex;
fullpar_string = patt1.lastIndex + 5;
partial_string = rule_string.slice(begin_string,fullpar_string); //5 characters
//alert("partial_string-"+partial_string);
refined_string_end = partial_string.indexOf("]");
refined_str = partial_string.slice(0,refined_string_end); //raw number
full_str = Pre_SearchReplace+refined_str+"]"; //restructured
SectionNum = refined_str;
SearchReplace = full_str; //Variable to pass to parse()
//alert("S&R="+SearchReplace+" >> full_string-"+full_str);
//alert("S&R"+SearchReplace+">>SecNum-"+SectionNum+">>Pre-Search-"+Pre_SearchReplace);
Parse(SearchReplace,SectionNum,Pre_SearchReplace);
}
//var patt_end=/\[t_/g;
}
function Parse(SearchReplace,SectionNum,Pre_SearchReplace){
if (Pre_SearchReplace == patt_S_and_R_1){
ref_URL = "UEB_Ref.html#";
}else if (Pre_SearchReplace == patt_S_and_R_2){
ref_URL = "UEB_Tech.html#";
}
linkCreate = 'Link to ch-'+SectionNum+' ';
document.getElementById("divid").innerHTML = document.getElementById("divid").innerHTML.replace(SearchReplace, linkCreate);
}
function Dude(SectionNum){
alert(SectionNum);
}
</script>
</head>
<body onload="pre_forwarder();">
<button onclick="pre_forwarder();">
New Tool</button>
<div id="divid">
hello [dude] ok the end [r_12.1][r_7] [r_22]
<br>bro try this [t_15.3][t_6] [t_5.5]
</div>
<div id="hyperlink">
</div>
</body>
</html>
You've rule_string = rule_string.innerText; at line 15. FF doesn't know innerText, you need to use textContent, or a fix like:
rule_string = rule_string.innerText || rule_string.textContent;
A live demo at jsFiddle.
As a side note: Looks like your app is based on global variables. Please don't use this kind of programming technique. It'll do the job, as long as there's not much of code, but when your apps are getting larger, you'll lose control over a ton of global variables.
For starters, you can read JavaScript Guide at MDN, especially chapters 4, 8 and 9.