I amm develloping an web form with multiple text box with same css class.
and i want to bind a specific method to all these textboxes who use that class.
belows are my codes
window.onload = function ()
{
var tObj = document.getElementsByClassName('exa');
for (var i = 0; i < tObj.length; i++) {
tObj[i].onblur(convertAmount(event,this));
}
}
the another function 'convertAmount()' is below
function convertAmount(evt, obj) {
if (obj.value != "") {
var num = parseFloat(obj.value);
num = Math.round((num + 0.00001) * 100) / 100;
obj.value = num.toFixed(2);
}
else {
obj.value = "0.00";
}
}
html codes
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
when browser load first time only '0.00' values are coming on those text boxes. but when i type some values on those text boxes and press tab its not working! please help what is wrong here
As commented before, you should assign a eventHandler and not pass it as callback.
So you code would be:
tObj[i].onblur = convertAmount.bind(this, event, this);
Also, event is default argument for any eventListener and current object/element is automatically binded to it, so above code can be simplified to
tObj[i].onblur = convertAmount;
This will bind the context and you will get all properties in this.
Sample Fiddle
Note: you should use addEventListener instead. onBlur = will replace all previous events. addEventListener will add another one.
Sample Fiddle
I hope this link helpful to you.
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
$(document).ready(function(){
$('.exa').each(function(index,value){
$(this).attr('onblur',convertAmount(event,$(this)))
})
})
function convertAmount(evt, obj) {
if (obj != "") {
$(obj).val('0.00')
}
else {
$(obj).val('0.00')
}
}
Related
I'm trying just to understand an error completely because sometimes I can get around it and other times I can't. I've tried just writing a function:
function toggleButton() {
}
But I get the same error. This is the .js sample.
var checkBox = document.getElementById("chkMyBox");
checkBox.onclick = function toggleButton(e, obj1)
{
var btnElement = document.getElementById("btnMyButton");
if(btnElement != null) {
alert("Element not null");
if(e.target.checked && obj1 != null) {
alert("Checking check " + obj1.checked);
if(obj1.checked == true && btnElement.getAttribute('disabled') == false){
btnElement.getAttribute('disabled') = false;
} else {
btnElement.getAttribute('disabled') = true;
}
}
}
}
Here's the html:
<form id="frmCheckBox">
<input type="checkbox" id="chkMyBox" />
<button id="btnMyButton" disabled>I'm a Button</button>
</form>
http://jsfiddle.net/Arandolph0/h8Re6/3/
Change this line which uses name:
<input type="checkbox" name="chkMyBox" />
into using id instead:
<input type="checkbox" id="chkMyBox" />
Alternatively you could use:
var elements = document.getElementsByName('chkMyBox');
var element = elements[0]; //first element with that name in the array
or
var element = document.getElementsByName('chkMyBox')[0];
Update (as OP changed the code from the original question):
function toggleButton(e, obj1)
This won't work as there is only a single argument given to the callback function (e).
Use e.target to get the element.
You're trying to get an element by its name. You'd have to do:
var checkBox = document.getElementsByName('chkMyBox')[0];
Or, if you prefer by id. Just add id="chkMyBox" to your checkbox input.
You have several problems here.
1) You try to get the button by using getElementById but your element has no id. The easiest fix is to fix your markup.
<input type="checkbox" name="chkMyBox" id="chkMyBox" />
2) Your event handler takes two parameters. When attaching the handler via the DOM, only the event gets passed to your handler. Therefore obj1 will always be undefined. You need to get the checkbox element from the e parameter.
checkBox.onclick = function(e) {
var obj1 = e.target;
// rest of handler
}
3) You shouldn't use getAttribute to check for the element being disabled/enabled. It will give you the text value of the attribute which is an empty string. Instead, use the boolean property that the DOM gives you:
// toggle the disabled attribute
obj1.disabled = !obj1.disabled;
I have put together this piece of JavaScript, but I am struggling with the code as I'm a newbie. What I want to do is when a button is clicked it will change the background color opacity. The code below does this, but now I want the button to be reverted to the normal state when I click it again.
How can I do this? Thanks..
Normal state: background="rgba(255,0,0,0.8)"; Pressed state:
background="rgba(255,0,0,0.6)";
function highlight(id) {
document.getElementById(id).style.background="rgba(255,0,0,0.6)";
}
I would use a CSS class:
.opacityClicked{
background:rgba(255,0,0,0.8);
}
.opacityDefault{
background:rgba(255,0,0,0.6);
}
And change your function to:
function highlight(id) {
var element = document.getElementById(id);
element.class = (element.class == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Or if you want to use only JavaScript
var isClicked = false;
function highlight(id) {
isClicked = !isClicked;
var element = document.getElementById(id);
element.style.background = (isClicked == true) ? "rgba(255,0,0,0.6)" : "rgba(255,0,0,0.8)";
}
Update(See comments: if you use 2 buttons):
var buttonClicked = null;
function highlight(id) {
if(buttonClicked != null)
{
buttonClicked.style.background = "rgba(255,0,0,0.8)";
}
buttonClicked = document.getElementById(id);
buttonClicked.style.background = "rgba(255,0,0,0.6)";
}
You could do something really quick like this:
First, add a hidden input element to your page like so:
<input type="button" id="foobar" value="FooBar!" onclick="highlight('foobar')" style="background-color:rgba(255,0,0,0.8);" />
<input type="hidden" id="one_neg_one" value="1" /> <= hidden element
Next, put this in your highlight function:
function highlight(id) {
var a = 7;
var o = document.getElementById("one_neg_one");
var newa = (a + (parseInt(o.value) * -1)) * 0.1;
document.getElementById(id).style.background="rgba(255,0,0," + newa + ")";
o.value = o.value * -1;
}
That should work, although I agree with a previous answer that you should use a css class for this.
#Ruben-J answer works fine. There is a syntax error though - you should instead use element.className rather than element.class.
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
Below is an updated answer using the correct syntax:
function highlight(id) {
var element = document.getElementById(id);
element.className = (element.className == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Also noticed that this answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.
I have aI need to validate the input by .onblur such that whenever a text input loses focus it gets validated by the same JS function.
My problem is with the JS function. I want to grab the value of the item that loses focus.
function valid(){
if (isNaN("this should be the value of the text item??")){
}
Thankss..
To grab the value of an item as you blur, you should add the onBlur trigger to the DOM element as follows:
<input type="text" name="validate_me" onBlur="valid(this);" />
That way you have access to the DOM element that triggered the onBlur event and can access its properties (such as value or innerHTML in the case of textarea elements.
Your valid function can then be something like:
function valid(element) {
if (element.value != '' && isNaN(element.value))
alert('This field is not valid!');
};
This javascript should do what you are asking for:
(function(){
var after = function(existing,after) {
if ( existing == null || typeof existing !== 'function' ) {
return after;
}
else {
return function() { existing(arguments); after(arguments); }
}
}
var validate = function(input) {
alert('validating ' + input.name);
}
window.onload = after(window.onload, function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if ( inputs[i].type === 'text' ) {
inputs[i].onblur = after(inputs[i].onblur, function() {
validate(this);
});
}
}
});
}());
Clearly you will have to replace the alert in the validate function with your validation logic, but this should do what you ask.
A couple notes, the immediately invoked function is to ensure you don't clobber any globals, and the after function is to ensure that if you there is already an attached listener that your new validate listener will be called after the existing one.
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(){ ... }
}
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