The following simple form with javascript with onclick button does not work in Firefox (I have version 7) but works fine in IE, Chrome, and Safari.
What am I missing?
<head>
<script type="text/javascript">
function result() {
alert(calc.input.value);
}
</script>
</head>
<body>
<form name="calc" action="">
<input class="cInput" type="text" name="input" size="16" /><br/>
<input type="button" class="cButton" name="seven" value="1" onclick="calc.input.value += '1'" />
<input type="button" class="cButton" name="equal" value="=" onclick="result()" /><br/>
</form>
</body>
<script type="text/javascript">
var calc;
function result() {
calc = document.forms['calc'];
alert(calc.input.value);
}
</script>
What am I missing?
You are missing that IE adds element names and ids as global variables. Some other browsers in certain conditions (sometimes requiring the document to be in quirks mode) will copy that habbit, some wont.
So in IE (and some others) the form name calc is a global variable referencing the form and in other browsers it isn't.
The method in Dunuyadnd's answer is a robust, cross-browser way to get a reference to the form. The formal access method is:
document.forms['calc'];
Named form controls can accessed similarly:
document.forms['calc'].elements['input'];
or
document.calc.input;
Be careful with giving controls names that are the same as tags, it is a bit confusing. Also, if there is more than one control with the same name, you will get an HTML collection rather than a single element.
You may want to read about HTMLForms and their related elements.
Related
I have a piece of code like this:
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"/><title>t</title></head>
<body>
<form id="F1">
<script>
function doit()
{
if(!F1.checkValidity())return;
alert("ID="+FName.value); //Do some processing
}
</script>
Enter your name: <input ID="FName" pattern="[a-zA-Z]+" required ><br />
<p><button OnClick="doit()"> DO IT</button></p>
</form>
</body>
</html>
It gets some input and validates it before processing data. According to https://validator.w3.org/check it does conform with HTML5. And It works fine in Firefox and Chrome, but not in IExplorer 11. It says ERROR SCRIPT 5009 "FName is undefined". However if I remove the form tag, FName becomes defined. But then I could not check the form validity.
I wonder if this is a IExplorer bug and how could I fix it. Thanks!
The input is a child of the form rather than the document.
I was able to duplicate the problem in IE. I solved it by referencing the element as F1.FName, i.e., as a child of the form element. And this worked in IE, Chrome, and Firefox. I suppose this is the expected behavior rather than a problem, but was unable to find a supporting reference.
if(!F1.checkValidity())return;
alert("ID="+F1.FName.value); //Do some processing
I have 2 questions:
How to check input better? I have idea:
First, make field near input.
<input type='text' name='firstname'><label id='firstnameError'></label>
Second, call js-function on input onBlur with id of input and id of this label.
<input type='text' name='firstname' id='firstname' onBlur='checkEmpty("firstname", "firstnameError");'><label id='firstnameError'></label>
And js-script:
function checkEmpty(fieldId, errorFieldId)
{
var data = document.getElementById(fieldId).value;
if (data == "")
{
document.getElementById(errorFieldId).innerHTML="Error, input something!...";
}
}
And I will just use this function on all inputs, right?
Is it correct?
How to check all inputs in form correctly?
Sure I can set type=button and onSubmit call some function, which will check all elements in this form. ~ Same function like in first question, but with 5-7 if-blocks for each input. And yes for 10 forms, I will have to write 10 functions, etc. How better do it? Seems to me, I can only send form Id/name and get childs of element. Am I correct?
Maybe another way? I use jquery on my site anyway (some ajax). Maybe it is easier to do what I want on jquery? The problem is I am not too good in js, to use jquery easily. What do you think?
If you just want to verify if some data is provided or not, you can use required attribute.
<input type="text" name="username" required>
if you are using XHTML it should be as shown below..
<input type="text" name="username" required="required">
The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome and is not supported in Internet Explorer 9 and earlier versions, or in Safari.
In case if you want to use JavaScript. You can create a javascript function which will be called on submit of the form.
<form name="search" onsubmit="return validate()" >
Name: <input type="text" name="name"/>
Age: <input type="gender" name="sex"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
function validate(){
// all the code for verification
return false; // if any of the step verification step fails. Otherwise return true.
}
Source: http://www.w3schools.com/tags/att_input_required.asp
To improve on your design, it's better to use non-inline JavaScript. Try using a design like this:
var fname = document.getElementById("firstname");
var other = document.getElementById("otherid");
fname.onblur = other.onblur = function() {
checkEmpty(this.id,this.id+"Error");
}
This will give all your desired elements the same onclick function and eliminate those pesky onblur attributes.
Edit: make sure your variables are declared before you chain assignments like this, or you will yield unwanted global variables.
I have an file upload box and a clear button on my page. When I press the clear button, I want the text in the file upload box to be cleared.
The following works in Firefox, but doesn't in IE (the text stays there). Is there a workaround for this?
$("#clear").click( function() {
$("#attachment").val("");
//document.myform.attachment.value = "";
})
HTML:
<form name="myform">
<input type="file" name="attachment" id="attachment" />
</form>
<br /><button id="clear">Clear Attachment</button>
jsFiddle
One solution I've found is simply doing:
document.getElementById('myUploadField').parentNode.innerHTML = document.getElementById('myUploadField').parentNode.innerHTML;
Seems like it shouldn't work, but it does.
This solution is more elegant than cloning the input element. You wrap a <form> around the element, call reset on the form, then remove the form using unwrap(). Unlike the clone() solutions above, you end up with the same element at the end (including custom properties that were set on it).
Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden".
http://jsfiddle.net/rPaZQ/
function reset(e) {
e.wrap('<form>').closest('form').get(0).reset();
e.unwrap();
}
It's readonly in IE8 onwards, so you can't clear it. The simplest way around this security feature is to replace the element with a copy.
Edit Found a previous answer to this that suggests the same approach! Clearing <input type='file' /> using jQuery
This worked for me:
$("input[type='file']").replaceWith($("input[type='file']").clone(true));
use simple javascript:
formname.reset();
See the Demo: http://jsfiddle.net/rathoreahsan/YEeGR/
Try to use the below method to clear the input file.
Include this script:
<script>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML =
document.getElementById(tagId).innerHTML;
}
</script>
Change HTML to this:
<div id="uploadFile_div">
<input type="file" class="fieldMoz" id="uploadFile" onkeydown="return false;" size="40" name="uploadFile"/>
</div>
<a onclick="clearFileInputField('uploadFile_div')" href="javascript:noAction();">Clear</a>`
Use the old-fashioned <input type="reset" value="clear this">
I have this basic example:
<!doctype HTML>
<html>
<head>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#showAction").click(function(){
alert($("#myForm").attr("action"));
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="action" value="myAction" />
</form>
<input type="button" value="click me" id="showAction" />
</body>
</html>
When you click 'click me' you can see the tag
$("#myForm").attr("action");
Doesn't actually return an attribute of the element. It returns the child of the form with the name "action".
Is this expected behavior? Is this a bug in jQuery?
It's a "bug" introduced by Netscape a long time ago (a boneheaded move, IMO), where form.action is a property because an element with that name is a child of the <form>. So no, it's not really a jQuery bug, but a JavaScript one, depending on your point of view...jQuery just doesn't have any additional checks for these cases.
To be safe, don't name your elements "action" or "submit", since it can mess with form.submit() as well.
Very odd indeed. I am going to quietly say - bug...
Form with an action attribute: http://jsfiddle.net/vMTYY/
Form without an action attribute: http://jsfiddle.net/ZWWTm/
Is there a workaround for Internet Explorer to implement the functionality offered by 'this' javascript keyword to get the dom element that triggered the event?
My problem scenario is :
I have a variable number of text fields in the html form, like
<input type="text" id="11"/>
<input type="text" id="12"/>
..
I need to handle the "onchange" event for each text field, and the handling is dependent on the 'id' of the field that triggered the event.
So far I understand that my options are:
1) attach a dedicated event handler for each text field. so if I have n fields, i have n different functions, something like:
<input type="text" id="11" onchange="function11();"/>
<input type="text" id="12" onchange="function12();"/>
but the text fields are added and removed dynamically, so a better way would be to have one generic function instead.
2) use the 'this' keyword like:
<input type="text" id="11" onchange="functionGeneric(this);"/>
<input type="text" id="12" onchange="functionGeneric(this);"/>
But this option does not work with Internet Explorer.
Can anyone suggest a work around for getting it work in IE or some other solution that can be applied here?
Thanks.
I can't reproduce your problem. Here's an SSCCE based on the latest information in comments:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2618458</title>
<script>
function functionGeneric(id) {
alert(id); // Shows either 11 or 12 correctly.
}
</script>
</head>
<body>
<input type="text" id="text_11" onchange="functionGeneric(this.id.split('_')[1]);"/>
<input type="text" id="text_12" onchange="functionGeneric(this.id.split('_')[1]);"/>
</body>
</html>
It works fine in all major browsers I have here. Your actual problem lies somewhere else. Until you come up with more detail, or better, an SSCCE, it's shooting in the dark to the root cause.
The second option probably does not work because element IDs must start with alphabet or the underscore character (at least, according to the spec).
I would opt for something like this:
// make the ids start with a word, like "foo", followed by "_", followed by a number
$("input[id^='foo_']").change(function() {
doSomething(this.id.split("_")[1]); // extract the number, pass to function
});
That will attach a change handler to all of your inputs with IDs starting with 'foo', and split the number out of the ID to pass to the generic function which works on the number.