Logic is missing in javascript - javascript

Hi,
A button which is adjacent to an input. The button is hidden by default and will be visible when the input gets focus and it will be hidden again if the input loses focus.
I wrote a code to achieve that. But the problem is button's event is not being triggered since it is hidden the moment the input loses focus.
I am not getting any idea to achieve that.Can somebody help me.
Here is the code
<html>
<head>
<style>
.icon{
visibility:hidden;
}
</style>
</head>
<body>
<input type="text" onFocus="onOver('f4_1')" onBlur="onOut('f4_1')"/>
<input type="button" class="icon" value="?" id="f4_1" onClick="alert('hi..')"/>
<script>
function onOver(f4Id){
document.getElementById(f4Id).style.visibility = "visible";
}
function onOut(f4Id){
document.getElementById(f4Id).style.visibility="hidden";
}
</script>
</body>
</html>
Note: Use pure javascript to achieve. Don't use any jQuery.
Thanks.

Actually, the order of these events varies between browsers. If I remember correctly, Internet Explorer will trigger the button if you click on it, whereas Firefox will not.
Anyway, the problem can be fixed by adding a small delay. Change your onOut function to:
function onOut(f41d) {
setTimeout(function(){document.getElementById(f41d).style.visibllity="hidden";},25);
}
Now the button will hide almost instantly. It should be unnoticeable to the human eye, but the computer can tell the difference and allow you to click the button.

Event handling is very important and understanding when they are fired is utmost important
onmousedown event will override onBlur effect of textbox ,which is what is required.
check working Example Here
<input type="text" onFocus="onOver('f4_1')" onBlur="onOut('f4_1')"/>
<input type="button" class="icon" value="?" id="f4_1" onmousedown="alert('M Kicked')"/>
<html>
<head>
<style>
.icon{
visibility:hidden;
}
</style>
</head>
<body>
<input type="text" onFocus="onOver('f4_1')" onBlur="onOut('f4_1')"/>
<input type="button" class="icon" value="?" id="f4_1" onmousedown="alert('M Kicked')"/>
<script>
function onOver(f4Id){
document.getElementById(f4Id).style.visibility = "visible";
}
function onOut(f4Id){
document.getElementById(f4Id).style.visibility="hidden";
}
</script>
</body>
</html>

Related

Problems with focus() in an input radio in Firefox

I have discovered a problem in Firefox when you try to make focus in an input radio. It doesn't make focus in the input, unless you previously use tab to focus on the input before. After that it works correctly. Does anyone know how to solve it? Thank in advance!
<!DOCTYPE html>
<html>
<body>
Radio Button: <input type="radio" id="myRadio">
<p>Click the buttons below to give focus and/or remove focus from the radio button.</p>
<button type="button" onclick="getFocus()">Get focus</button>
<button type="button" onclick="loseFocus()">Lose focus</button>
<script>
function getFocus() {
document.getElementById("myRadio").focus();
}
function loseFocus() {
document.getElementById("myRadio").blur();
}
</script>
</body>
</html>
It is working for me in Firefox (v47.0 and v47.0.1). The only thing is not highlighting it... But if you add some CSS like the following, you will see how it is working fine:
input#myRadio:focus {
outline: 7px solid yellow;
}

HTML/JS Execution Order

I am trying to understand the Execution Order of HTML and JS functions.
Code:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x=document.getElementsByName("check1");
x[0].disabled=true;
x[0].checked=true;
x[0].value="Y";
}
function myFunction1()
{
var x=document.getElementsByName("check1");
alert(x[0].value);
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
<form>
<input type="checkbox" name="check1" unchecked enabled value="N"/>
<input type="button" value="Button" onclick="myFunction1()"/>
</form>
</body>
</html>
Finally the element "check1" value is =Y.
finally checkbox is checked and disabled.
Can anyone explain about this.
I have already gone through this link which is very useful:
Load and execution sequence of a web page?
Still the above example will help bit more .Thanks
first you change the name of functions.. it must be different. then the execuation order is
first onbody load function is called then input button function called.
you can even check it by alert that.
The "myFunction()" method called in on load event so that it executed immediately after a page is loaded. and the function "myFunction1()" called on button click event .And you are initializing check box value with "N" value thats why it displaying n after every page load function
If I understood your question you mean why your checkbox value is 'Y' despite you disabled the checkbox.
disabling checkbox only make it inactive as far as User Interface is concerned but through script you can still change the value.

Internet Explorer doesn't execute onChange function

I have this code which is supposed to hide and show a DIV by checking and unchecking a form checkbox using the control onChange event. It works in Chrome, Firefox, Safari and Opera but IE 8 and 9 refuse to cooperate... There are no error messages in the console. Anything I'm missing?
Thanks for any help!
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Demo</title>
<script type="text/javascript">
var divVisible = true;
function Passport() {
if (divVisible) {
document.getElementById('mydiv').style.visibility="hidden";
divVisible = false;
}
else {
document.getElementById('mydiv').style.visibility="visible";
divVisible = true;
}
}
</script>
</head>
<body>
<form>
<input type="checkbox" onchange="Passport();" value="Passport">Passport
</form>
<div style="height: 100px; width: 100px; background-color: #ff0;" id="mydiv"></div>
</body>
</html>
According to this answer
onchange in IE only fires when the checkbox loses focus. So if you tab to it, hit space a few times, tab out, you'll only get one onchange event, but several onclick events.
You should change your code to use the onclick event instead:
<input type="checkbox" onclick="Passport();" value="Passport">Passport</input>
A checkbox input will not fire any change events until the focus is lost. The input value changes everytime it's clicked.
Change onchange="Passport();" for onclick="Passport();"
Change the onchange to onclick since IE8 fires onchange when focus is lost
And adjust it based on the state of the checkbox
<input type="checkbox" onchange="Passport(this.checked);" id="passportCB" value="Passport"><label for="passportCB">Passport</label>
and the function
function Passport(state) {
document.getElementById('mydiv').style.visibility= state ? "hidden" : "visible";
}
I also added a label, so the user can click the text and toggle the checkbox state.

Problem using click() on input[type=file]

I'm having a problem with the click() functon. It does not work in Opera.
I am trying to make a input type=file clicked on onclick event of another element. I need to style my input type=file element so I made it invisible and replaced it with simple styled button. Now I want file element to be clicked when button is clicked.
I can't use jQuery because I am using the MooTools library for a calendar in my page and it makes conflict when I try to use jQuery. I also tried to avoid the conflict using jQuery.noConflict(); but I could not do it because I am new to jQuery. Here is my html code:
<input name="myfile" id="uploadme" type="file" style="visibility:hidden; width:1px;" onchange="this.form.submit()"/>
<input type="button" id="clickme" onclick="show_upload()"/>
And here is my JavaScript code:
function show_upload()
{
document.getElementById('uploadme').click();
}
I also tried this jQuery code but I could not make it work without conflict with the MooTools library:
jQuery.noConflict();
(function($){
$('#clickme').click(function($){
$('#uploadme').click();
})(jQuery);
});
input[type=file] is very peculiar input type, you can't really do a whole lot with it, primarily for security reasons.
I'm guessing here, but do you perhaps want you own styled upload button? In that case I must disappoint you, you can't do it with HTML. You'll either have to use HTML5 or Flash (like SWFUpload)
It's an Opera bug, but there is possibility to get the result by a different way, using <label> tag:
<input type="file" id="file" style="position: absolute; visibility: hidden;">
<label for="file" id="file-label"></label>
<a onclick="$('#file-label').click()">Browse..</a>
I'm not sure for the input click (it might just be impossible due to security reasons), but your jQuery code is not completely correct.
jQuery.noConflict();
(function($){
$('#clickme').click(function(){ // The $ is not necessary - you already have it
$('#uploadme').click();
}); // You should remove (jQuery) because you don't want to call the function here
})(jQuery); // you need (jQuery) to actually call the function - you only defined the function
Anyway, this answer says you cannot do what you want in Opera: In JavaScript can I make a "click" event fire programmatically for a file input element?
it's not impossible:
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);
But somehow it works only if this is in a function which was called via a click-event.
So you might have following setup:
html:
<div onclick="openFileChooser()" class="some_fancy_stuff">Click here to open image chooser</div>
<input type="file" id="input_img">
JavaScript:
function openFileChooser() {
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function()
{
document.getElementById('input_img').dispatchEvent(evObj);
},100);
}
Hmm...this works for me. In Chrome.
<input type='file' id='csvfile' onclick='reset_upload()' />
where reset_upload() is a jQuery function.
It's impossible to click that button using JavaScript (like friends have said) but see this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lorem ipsum</title>
</head>
<body>
<input type="file" id="first" style="width:200px; background-color:red">
<input type="file" id="second" style="width:200px; background-color:green; position:relative; left:-100px; opacity:0">
<script>
document.getElementById("first").onchange = function(){alert("first")}
document.getElementById("second").onchange = function(){alert("second")}
</script>
</body>
</html>
You can do something like that.
Only problem is that you have to know dimensions of these inputs. Hm... Maybe it's not problem. You can set dimensions. :>

Automatically making a div appear based on status of radio button with JavaScript

I have a form which posts data to the same page. Based on the user's radio button selection I am inserting checked="checked" into the radio button form element to redisplay the correct selection. This works fine, however when the form is redisplayed (in case of bad input etc), I need a div to be revealed (containing the relevant fields from the form).
I have an onclick event that reveals the div in the first place (before the user has posted the form), and this works fine, but when I redisplay the form I don't want the user to have to manually reveal the form again by clicking.
Therefore I've been trying something along the following lines (heavily cut down for the purposes of this post)...
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
... but it returns an Object Required javascript error (as it does in the 'real' page):
Message: Object required
Line: 3
Char: 1
Code: 0
URI: http://localhost/repair_system/javascript_test.php
Why is this? Am I not correctly referencing the form element? Apologies if I'm being a "div" (deliberate bad pun intended!), I'm yet to learn about the fun and games of javascript!
Because your javascript is not wrapped inside a function, the browser is executing it as soon as it "gets to it". In this case, the JS is being executed before the browser has reached the html declaring your form.
The simplest fix therefore is to move the Javascript to after your form. A more robust solution would be to wrap you code in a function, and have that triggered somehow - from what you appear to be trying to do, in this case it'll be the onLoad event of the body tag:
<head>
<script language="JavaScript">
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
</head>
<body onload="showHelpDiv()">
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
Your code is being executed as the document is being loaded, and the DOM tree isn't ready yet. So it is trying to access an element that doesn't exist yet.
You probably want to instead write an event handler that toggles the div whenever the checkbox is checked.
I prefer jQuery, which abstracts away things like cross-browser event handling, provides lots of nice helpers and generally makes code look cleaner (when written properly). Something like this should work:
$(document).ready(function() {
$('#repair_complete').toggle($('#complete_yes').is(':checked'));
}
The above can be roughly translated as:
When the document loads, perform the following:
Add an event handler for the 'change' event to any elements of type 'input' with a name of 'complete'
When the event handler fires, toggle the visibility of the element with ID 'repair_complete' where it should be visible if the element with ID 'complete_yes' is checked
Update: The JS above now actually does what you want, originally I had it written as an onclick
This is because Javascript is executed just before rest of the objects are created.
Place your javascript code into the function body, and add this function into onclick event for whatever you need.
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
function test() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true" onClick="javascript: test();"/>Yes
<input id="complete_no" type="radio" name="complete" value="false" onClick="javascript: test();"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
</form>
It looks to me as though your script is firing before the form is drawn, you may want to move your script block to after the form element. Basically I think that the document.getElementById('complete_yes').checked is looking at null.checked, which would trigger the object required error.
You should make the action of the radio button be to change the visibility of the div (that is, "push" the status to it), rather than to "pull" the div status via the radio button status at render time (which as Andrejs said, will be unset).
Sounds like the problem is in your initialization code. The javascript is being called before the page is finished rendering. It's one annoying aspect of the "onload" event that in my opinion simply doesn't work as it should in every browser.
There's a cross-browser technique to call initialization code once and only once after the DOM is fully loaded.
Try this code in the HEAD of your HTML:
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
function InitOnce()
{
if (arguments.callee.done) return;
arguments.callee.done = true;
showHelpDiv();
}
/* for Mozilla */
if (document.addEventListener)
{
document.addEventListener("DOMContentLoaded", InitOnce, null);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script defer src=ie_onload.js><"+"/script>");
/*#end #*/
/* for other browsers */
window.onload = InitOnce;
And then you need to create an ie_onload.js file that contains this line for IE compatibility:
InitOnce();
I've tried other techniques but none work as perfectly as this. I believe I originally found this solution here:
http://dean.edwards.name/weblog/2005/09/busted/
I use it in an online application that receives 500 unique visits a day or so and this has been reliable for us.

Categories

Resources