how to use a function inside a function in javascript - javascript

<table>
<tbody id="add_weight" >
<tr></tr>
</tbody>
</table>
<a onClick="maira()" >+Add more Weights.</span></a>
here i am having a anchor tag..i have called a function when user clicks on anchor tag..that is
<script type="text/javascript">
var b=1;
function maira()
{
if(b==10)
{
alert("can't Add more than 10 Weight Rates");
return false;
}
var table=document.getElementById("add_weight")
var row=table.insertRow(b);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
cell1.innerHTML="<input type='text' id='rate"+b+"' name='rate"+b+"' onkeyup='alert(hi)'/>";
cell2.innerHTML="<input type='text' id='flat"+b+"' name='flat"+b+"' />";
b=b+1;
}
</script>
here when a user clicks a new row gets added with two fields namely rate and flat....this is working fine now the problem is that...i want when user enters anything in flat textbox than it should come simultaneously in rate textbox...probably using onkeyup even...can anyone help me with this??

You can use a class to attach event handler or attach handlers individually.
But you'll have to use data- attribute to store the index of the row, so that the handler can know the index and the "id" of the target element in which you want to copy the text

Attach event handler to your class/id. You can go with any libraries or below utility code would work fine. You are attaching the element to onkeyup event.
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
// example
addEvent(
document.getElementById('myElement'),
'keyup',
function () { alert('hi!'); } // update your other text field value.
);
Here is a working fiddle for you.
http://jsfiddle.net/bmArj/

Related

programatically changing value in input field perform some task

HTML
<input id="testinput" type="text"></input>
JS
$('#testinput').change(function (){
change();
});
function change(){
alert();
}
$('#testinput').val('new val');
Link
By typing in input and losing focus it works, but if a change of the input field is triggered by jquery, it does not work.
$('#testinput').val('new val').trigger('change'); not required.
From MDN (bolded by me):
The change event is fired for input, select, and textarea
elements when a change to the element's value is committed by the
user. Unlike the input event, the change event is not necessarily
fired for each change to an element's value.
You will need to manually trigger the change event if you are changing the value programmatically.
I suppose if you are hellbent on not manually firing the change event, you could override jQuery's val ($.fn.val) method to do it for you:
var originalVal = $.fn.val;
$.fn.val = function() {
if(arguments.length) {
originalVal.apply(this, arguments);
this.trigger('change');
return this;
}
return originalVal.call(this);
}
http://jsfiddle.net/ybj1zjhk/4/
will fire the alert whenever you type something
$('#testinput').keyup(function (){
change();
});
function change(){
alert();
}
$('#testinput').val('new val');
Or you can trigger the change event whenever you do something that requires you to have the change event fire https://jsfiddle.net/owoemcg2/
$('#testinput').change(function (){
change();
});
function change(){
alert();
}
$("#mybutton").click(function(){
$('#testinput').val('new val');
$("#testinput").trigger("change");
});

Bypass onclick event and after excuting some code resume onclick

I have the below html button which have onclick event
<button onclick="alert('button');" type="button">Button</button>
and the following js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler e.g: jquery alert first and than button alert.
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. but no luck.
is it possible via jQuery/javascript?
any suggestion much appreciated
Thanks
A little bit tricky. http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. You can use data attributes.
<button data-param="<%= paramValue %>"...
You can do it this way:
http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
Create a separate javascript function that contains what you want to do when the button is clicked (i.e. removing the onclick attribute and adding replacement code in its own function).
Then call that function at the end of
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>

Need to store input value to variable on change

I am trying to store the value of an input into a variable. For now, I want to just paste the input value into a span element so I can know that it works. However I cannot get it work in my JSFIDDLE. Any suggestions?
HTML:
<label>Advertising Budget:</label>
<input id="advertising" onchange="updateAdvertising(this.value)"> </input>
<span id="test">xxx</span>
Javascript:
function updateAdvertising(adv){
document.getElementById('test').innerText = adv;
}
JSFIDDLE: http://jsfiddle.net/6J4MN/
innerHTML is more compatible, also change fiddle to head instead of onload
Here is a neater solution
Live Demo
window.onload=function() {
document.getElementById("advertising").onchange=function(){
document.getElementById('test').innerHTML = this.value;
}
}
Since onchange needs a blur to trigger, use onkeyup for immediate change:
Live Demo
window.onload=function() {
document.getElementById("advertising").onkeyup=function(){
document.getElementById('test').innerHTML = this.value;
}
}
Note the "OnChange" event for the text box will fire once you hit enter or leave the text box. If you change the event to, say keyup, it will update the span after every letter you type.
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
};
addEvent(document.getElementById('advertising')
, 'change'
, function () { updateAdvertising(this.value); }
);
var updateAdvertising = function(adv){
document.getElementById('test').innerText = adv;
};
};
</script>

Prevent $('img').click triggered for several times

I was wondering how to prevent the confirm message being prompted for several times, thanks in advance!
javascript
$('img.delete').click(function () {
if(confirm("This selected record will be deleted. Are you sure?")){
//Do something...
}
});
html
<tbody>
<tr>
<td><img class="delete" src="/images/delete.gif"><input value="708" type="hidden"></td>
<td>aaa</td>
</tr>
<tr>
<td><img class="delete" src="/images/delete.gif"><input value="595" type="hidden"></td>
<td>bbb</td>
</tr>
<tr>
<td><img class="delete" src="/images/delete.gif"><input value="19" type="hidden"></td>
<td>ccc</td>
</tr>
</tbody>
The problem in your code is that you apply the click handler multiple times; this is not visible from the code that you have posted, but it's definitely the cause.
If you run $('img.delete').click(fn) multiple times, it doesn't overwrite the previous click handler; rather, it adds another handler. Afterwards, when img.delete is clicked, ALL registered handlers get called in succession, resulting in one popup window followed by another.
It should be remedied by calling .unbind() first; doing so will effectively replace the previous click handler(s) by a new one.
$('img.delete')
.unbind('click')
.click(function () {
if(confirm("This selected record will be deleted. Are you sure?")){
//Do something...
// remove the image here I guess?
}
});
But it would be better if you could hunt the root cause down as well.
you can do this by unbinding in jquery
$(function(){
$('img.delete').click(function () {
if(confirm("This selected record will be deleted. Are you sure?")){
//Do something...
}
$('img.delete').unbind('click');
});
});
If you worry about this, you can be sure to not have event handler after click:
var confirm_me=function () {
if(confirm("This selected record will be deleted. Are you sure?")){
//Do something...
}
//restore event handler
$(this).one('click',confirm_me);
//prevent event propagation
return false;
}
//BE sure that you not do that in loop. if possible do - see second code
$('img.delete').one('click',confirm_me);
other case:
var confirm_me=function () {
var t=$(this);
//check processing flag
if (t.data('processing')) return false;
//Set processing flag
t.data('processing',1);
if(confirm("This selected record will be deleted. Are you sure?")){
//Do something...
}
//restore event handler
t.one('click',confirm_me);
//remove processing flag
t.data('processing',0);
//prevent event propagation
return false;
}
$('img.delete').one('click',confirm_me);
Use it , it is verified by me.
<script type="text/javascript">
var check = false;
$(document).ready(function () {
$('img.delete').click(function () {
if (check != true) {
if (confirm("This selected record will be deleted. Are you sure?"))
check = true;
}
else {
alert('you have deleted one');
}
});
});
</script>
Use Jquery .one() method, that's pretty much what that was made for.
$('img.delete'.one('click',function () {
if(confirm("This selected record will be deleted. Are you sure?")){
//Do something...
}
});

JavaScript click has different behavior than manual one

With prototype I'm listening for a click event on several checkboxes. On checkbox click I want to disable all <select> elements. I'm using prototype. So, I have this code:
$$('.silhouette-items input[type="checkbox"]').invoke('observe', 'click', function(event) {
var liItem = this.up('li.item');
if(this.checked) {
alert('checked');
liItem.removeClassName('inactive');
var selectItem = liItem.select('select');
for(i=0;i<selectItem.length;i++) {
selectItem[i].disabled=false;
if (selectItem[i].hasClassName('super-attribute-select')) {
selectItem[i].addClassName('required-entry');
}
}
} else {
alert('unchecked');
liItem.addClassName('inactive');
var selectItem = liItem.select('select');
for(i=0;i<selectItem.length;i++){
selectItem[i].disabled=true;
if (selectItem[i].hasClassName('super-attribute-select')) {
selectItem[i].removeClassName('required-entry');
}
}
}
calculatePrice();
});
When I manually click on the checkbox, everything seems to be fine. All elements are disabled as wanted.
However, I have also this button which on click event it fires one function which fires click event on that checkbox.
In Opera browser it works. In others, not. It's like Opera first (un)check and then executes event. Firefox first fires event, then (un)check element.
I don't know how to fix it.
The HTML:
<ul class="silhouette-items">
<li>
<input type="checkbox" checked="checked" id="include-item-17" class="include-item"/>
<select name="super_attribute[17][147]">(...)</select>
<select name="super_group[17]">(...)</select>
<button type="button" title="button" onclick="addToCart(this, 17)">Add to cart</button>
</li>
<!-- Repeat li few time with another id -->
</ul>
Another JS:
addToCart = function(button, productId) {
inactivateItems(productId);
productAddToCartForm.submit(button);
}
inactivateItems = function(productId) {
$$('.include-item').each(function(element) {
var itemId = element.id.replace(/[a-z-]*/, '');
if (itemId != productId && element.checked) {
simulateClickOnElement(element);
}
if (itemId == productId && !element.checked) {
simulateClickOnElement(element);
}
});
}
simulateClickOnElement = function(linkElement) {
fireEvent(linkElement, 'click');
}
Where fireEvent is a Magento function that triggers an event
Don't bother simulating a onclick if you can get away with not doing so. Having a separate function that can be called from within the event handler and from outside should work in your case.
var handler = function(){
//...
}
var nodeW = $('#node');
handler.call(nodeW);
Of course, this doesn't trigger all onclick handlers there might be but it is simpler so it should work all right. Points to note for when you use .call to call a function:
Whatever you pass as the first parameter is used as the this inside the call. I don't recall exactly what JQuery sets the this too but you should try passing the same thing for consistency.
The other parameters become the actual parameters of the function. In my example I don't pass any since we don't actually use the event object and also since I don't know how to emulate how JQuery creates that object as well.
replacing
fireEvent(linkElement, 'click');
with
linkElement.click();
works in firefox 5 and safari 5.1, so maybe the problem lies in the fireEvent() method.

Categories

Resources