To disable image - javascript

I have an html image. In its onClick event I have written code to show a calendar. I want to disable that image, which means I should not be able to click that image, but the image should be visible. I want to disable the onclick event of image. Can anybody help?

Or without making any changes to your calendar...
<div>Click the button because I am enabled... <img id="btnSubmit" src="submitbutton.gif" onclick="Foobar(this,event);" alt="submit button" /></div>
<p>
<span onclick="ToggleOnclick('btnSubmit');">Click here to disable/enable the image's onclick</span>
</p>
<script>
function ToggleOnclick(elID)
{
/// <summary>
///
/// </summary>
var el = document.getElementById(elID);
if (el.onclick)
{
// Disable the onclick
el._onclick = el.onclick;
el.onclick = null;
alert(el.id +'\'s .onclick has been disabled.');
}
else //if (!(button._onclick))
{
// Disable the onclick
el.onclick = el._onclick;
el._onclick = null;
alert(el.id +'\'s .onclick has been enabled.');
}
}
function Foobar(el, e)
{
alert('Submitting...');
}
</script>
The gold is in the ToggleOnclick. In fact you could generalise that any use it to disable/enable events on just about anything.

I assume you have something like:
...
<script>
var Calendar = function() {
var month = ...;
var updateDisplay = function() {
...
};
return {
prevMonth: function() {
month--;
updateDisplay();
}
};
};
var cal = new Calendar();
</script>
Calendar is a class with private members, cal is an instance of that class.
All you should have to do is add a new member to Calendar that tracks if your onclick should be disabled, e.g. isDisabled, and check for this in the function you call in your onclick, e.g.
prevMonth: function() {
if (isDisabled) {
return;
}
month--;
updateDisplay();
}

easiest method is to use some hidden field or javascript variable
HiddenField:
<asp:HiddenField id="hdnValue" runat="server" value="true"/>
<script type="text/javascript">
function ImageClickHandler(){
var i=document.getElementById(<%=hdnValue.ClientID%>).Value;
//don't know if .value works because I'm very much into jQuery
if(i=='true') //go ahead and show calendar
else //don't show !
}
</script>
Variable:
var showCal = "<%= VARIABLE_TO_SET_IF_CAL_ENABLED%>";
<script type="text/javascript">
function ImageClickHandler(){
if(showCal=='true') //go ahead and show calendar
else //don't show !
}
</script>

As has been said, just add a condition within the onclick handler.
<script type="text/javascript">
var _imageClickDisabled = false;
function disableImageClick()
{
_imageClickDisabled = true;
}
function onImageClick()
{
if (_imageClickDisabled)
{
return;
}
// show your calendar here
//
// : : :
}
</script>
<img ... onclick="onImageClick()" />
Just call the disableImageClick() function to stop the calendar showing.

Hi it is very very late,
But I too have got same requirement and I have fixed it by replacing the image tag with input element with type as image, the benefit of this element is it show the image as input element and disabled property will allow you disable click event. Below is the code I have used
<input type="image" src="<date icon>"
onclick="return showCalender('txtdate','dd\mm\y');" disabled="disabled"></input>
Keep in mind that, the disabled attribute will only work for form related elements
Thought might be helpful for other guys in future.

Related

Looking to disable a set of fields unless a radio button is marked

I have uploaded the HTML / CSS / JS at: http://jsfiddle.net/mbender/aH8Ax/
I know the problem probably lies within the JS, as i have almost no experience with it.
$(function () {
var $promised = $("input[name='RadioGroup1']");
$promised.each(function () {
$(this).on("click", function () {
$promised.each(function () {
var textField = $(this).nextAll("input").first();
if (textField) textField.prop("disabled", !this.checked);
});
});
});
});
There is also a conditionally hidden element to work around. You will see what i mean in the fiddle
The input field is disabled whenever the attribute 'disabled' is present in the tag, it doesn't matter what the value is set to. What you can do is loop through all the input elements inside of the USA section and call
.removeAttribute('disabled');
if the user selects the USA radio button.
EDIT: something like this should work (as long as you have JQuery)
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type=text/javascript>
$(function() {
var $promised = $("input[name='RadioGroup1']");
$promised.each(function() {
$(this).on("click",function() {
var USARadio = document.getElementById("RadioGroup1_0");
if(USARadio.checked == true){
toggleUSA(true);
}
else{
toggleUSA(false);
}
});
});
});
function toggleUSA(disable){
var USATable = document.getElementById("rowThree");
var USAInputs = USATable.getElementsByTagName("input");
for(var i=0;i<USAInputs.length;i++){
if(disable == true)
USAInputs[i].removeAttribute("disabled");
else
USAInputs[i].setAttribute("disabled", "true");
}
}
</script>

How can I figure out what button was clicked on last?

How can I figure out what button was clicked on last? For example I have:
<input type="button" name= "zoomer" value="State View" id= 'States View' onclick="zoomout()"/>
<input type="button" name= "zoomer" value="County View" id= 'Counties View' onclick="countyView()"/>
But whenever I change a RADIO button, I want it to take into account which button was clicked last (County View or State View). Is it possible to do this?
You could keep a global JavaScript variable var last_clicked which is updated in the functions zoomout() and countyView(), and then check the value of last_clicked when you change the radio button. Alternatively, you can terminate the calls to the functions within the onclick event with a semicolon, then assign the value to last_clicked inside the onclick event string (although I wouldn't recommend it as it can make your code messy).
var lastClicked = "none";
function zoomout()
{
// your code
lastClicked = "states";
}
function countyView()
{
//your code
lastClicked = "county";
}
if(lastClicked == "county")
{
}
else if(lastClicked == "states")
{
}
it's possible by using an external variable such as
var clickedLast = "";
function zoomout() {
clickedLast = "stateview";
... your code ...
}
function countyView() {
clickedLast = "countyview";
... your code ...
}

How to tell if a button is clicked

I have this code:
<script type="text/javascript">
function changestate()
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(document.getElementById("Play").onclick == true)
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick="changestate();"/>
I'm trying to know when the button is clicked, and have that if button is clicked in the if statement. I want to know this so I can change the value that is inside the text box. The problem is, I do not know how to tell when the button is clicked. If you could help me out that would be great.
The onclick attribute identifies what should happen when the user clicks this particular element. In your case, you're asking that a function be ran; when the function runs, you can rest assured that the button was clicked - that is after all how the function itself got put into motion (unless you invoked it some other way).
Your code is a bit confusing, but suppose you had two buttons and you wanted to know which one was clicked, informing the user via the stateTextBox value:
(function () {
// Enables stricter rules for JavaScript
"use strict";
// Reference two buttons, and a textbox
var playButton = document.getElementById("play"),
stateTextBox = document.getElementById("state"),
ignoreButton = document.getElementById("ignore");
// Function that changes the value of our stateTextBox
function changeState(event) {
stateTextBox.value = event.target.id + " was clicked";
}
// Event handlers for when we click on a button
playButton.addEventListener("click", changeState, false);
ignoreButton.addEventListener("click", changeState, false);
}());
You can test this code live at http://jsfiddle.net/Y53LA/.
Note how we add event-listeners on our playButton and ignoreButton. This permits us to keep our HTML clean (no need for an onclick attribute). Both of these will fire off the changeState function anytime the user clicks on them.
Within the changeState function we have access to an event object. This gives us some details about the particular event that took place (in this case, the click event). Part of this object is the target, which is the element that was clicked. We can grab the id property from that element, and place it into the value of the stateTextBox.
Here is the adjusted HTML:
<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />​
You can know if button clicked by using a flag (true or false).
var flag = false;
window.addEventListener("load", changestate, false);
function changestate() {
var StateTextBox = document.getElementById("State");
var PlayButton = document.getElementById("Play");
PlayButton.addEventListener("click", function () {
flag = true;
})
PlayButton.addEventListener("click", change)
function change() {
if (flag) {
StateTextBox.value = "Happy";
}
}
}
Looking back on this, many years later, you could simply do:
<script type="text/javascript">
function changestate(action)
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(action == "Play")
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick='changestate("Play");'/>

How to disable a Javascript Function when a different one is Enabled?

I have this function:
$(document).ready(function(){
function Fos(buttonSel, inputSel, someValue, cssProperty) {
$(buttonSel).click(function(){
var value = $(inputSel).attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, someValue, this.id)
var css_obj={};
css_obj[cssProperty]=value;
$(this).css(css_obj);
});
});
}
Here are three places where function is written:
Fos('#border_button', '#border-radius', 2, '-webkit-border-radius');
Fos('#background_color_button', '#background-color', 1, 'background-color');
Fos('#opacity_button', '#opacity', 3, 'opacity');
<input type="text" id="border-radius" value="20px">
<div id="border_button">BORDER RADIUS</div>
<input type="text" id="background-color" value="red">
<div id="background_color_button">Background</div>
<input type="text" id="opacity" value=".5">
<div id="opacity_button">Opacity</div>
<div id="2" class="defaultclass editable" style="<?php getStyle('2') ?>">
something
</div>
When you click the DIV with the ID= "border_button", or "background_color_button", or "opacity_button"
it waits for you to click any DIV with class="editable", ...$("div.editable").click(function (e) {... it executes the function with those parameters.
I just need a fix that will only allow ONE function with the parameters to be enabled at one time.
Currently, when you click on all three divs with ID = "border_button", or "background_color_button", or "opacity_button" AND THEN on a div with class="editable", it executes the function with ALL THREE sets of parameters.
This is bad. I can't figure it out.
You can't "disable" a function, but you can set a variable that will force it to exit right away:
var stopMe = true
function myFunction() {
if(stopMe) {
return;
}
...
}
You seem to be binding and rebinding the same functions over and over, which is probably why you have that e.stopEventPropagation in there. Try assigning the events once and then managing the current state (which button is active) and going from there:
var $currentInput = null;
$("#border_button,#background_color_button,#opacity_button").click(function() {
if ($currentInput == null) {
$currentInput = $(this).prev();
}
});
$("div.editable").click(function(e) {
if ($currentInput == null)
return;
$(this).css(GetCssProperties());
showUser($currentInput.val(), /* where does someValue come from? */, this.id)
$currentInput = null;
});
function GetCssProperties() {
if ($currentInput == null) return null;
var value = $currentInput.val();
if ($currentInput.attr("id") == "border-radius") return {
"-webkit-border-radius": value
}
if ($currentInput.attr("id") == "background-color") return {
"background-color": value
}
if ($currentInput.attr("id") == "opacity") return {
"opacity": value
}
}
working example here: http://jsfiddle.net/HUJ5A/
Run the function for tag with a specific class. And a the end of the function remove this class from the tag.
jQuery(".myclass").click(function(){
/* do something */
jQuery(this).removeClass('myclass');
});
Can't tell everything from your question. But this part $("div.editable").click(function (e) { will bind multiple click events to div.editable each time the user clicks Foo arugments[0] or buttonSel.
This could be a pssible solution:
Have a global variable (or HTML hidden input) say, lastDivClicked, to store the id of the recently clicked div
Update lastDivClicked everytime one of those three divs are clicked upon
Change your function to this:
function Fos(inputSel, someValue, cssProperty) {
var buttonSel = $('#lastDivClicked').val();
$(buttonSel).click(function(){ ... }
}

Detect programmatical changes on a html select box

Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>
Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}
The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.
ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},
With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed

Categories