Here's the fiddle. I'm trying to make it so when you press the button, it adds 1 to #num.
JS:
$(document).ready(function () {
$('#b').button({
icons: {
secondary: '.ui-icon-triangle-1-n'
}
});
$('#b').click(function () {
var x = '#num'.value;
var u = x + 1;
document.getElementById('#num').innerHTML = u;
});
});
Try this .It should work
$(document).ready(function () {
$('#b').button({
icons: {
secondary: '.ui-icon-triangle-1-n'
}
});
$("#b").click(function () {
var x = parseInt($('#num').html());
var u = x + 1;
$('#num').html(u);
});
});
Assuming the first part is working somehow (not sure what "button" is), try this:
$('#b').click(function () {
var x = $('#num').text();
var u = parseInt(x) + 1;
$('#num').html(u);
});
var x = Number($('#num').text());
You are not retrieving the value the correct way. Try the above
$(document).ready(function () {
$('#b').button({
icons: {
secondary: '.ui-icon-triangle-1-n'
}
});
$(this).click(function () {
// var x = '#num'.value;
var x = $('#num').html();
var u = parseInt(x) + 1;
document.getElementById('#num').innerHTML = u;//why not use $('#num').html(u);
});
});
you can try this .
Here's a fiddle using jQuery's data function to store and increment the value:
http://jsfiddle.net/nyhpt/3/
There are several mistakes:
'#num'.value is not valid. You should use $('#num') to get the jQuery nodes
if you'd like to use document.getElementById, that should be document.getElementById('num'). Note there's no leading '#'
to get or set HTML content in tags like p, div, span, use .innerHTML (for DOM nodes) or .html() (for jQuery nodes); to get input value from input, textarea, use .value (for DOM nodes) or .val() (for jQuery nodes)
any value or HTML content in a node is a string, so you'd better change it into a number via parseInt (Javascript allows you add a string to an integer, but that's actually a string concatenate)
I'd like to change your codes in this way:
$(this).click(function () {
var x = parseInt($('#num').html());
var u = x + 1;
document.getElementById('num').innerHTML = u;
});
Related
I have the following jQuery which adds checkbox/radio value to a textbox, however, when the radio value is clicked it seems to be replacing the current value rather than adding to it. It also seems to be adding an extra 1, as 0.07 will appear as 1.07 (for example). What's going on here?
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
$('input[type=radio]').click(function() {
let sum = 0;
$('input[type=radio]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
As I am not having idea about your HTML structure, but I think you are making mistake here.
// var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
var pc = parseFloat($('input[name="percentdiscount"]').val());
Am getting key Combination from the server. Based on that am assigning key Combination to function dynamically. The below code is working for last iteration in loop. how below code is work for all iterations.
In my page i have two buttons save and cancel the below code is working for last iteration in for loop, It means btnCanel button triggers if i press key for save function.Any suggestions. hope understand my question.
$(document).ready(function fn() {
var keyCombination = new Object();
keyCombination['btnAdd'] = "Alt+S";
keyCombination['btnCancel'] = "Alt+C";
for (var k in keyCombination) {
if (keyCombination.hasOwnProperty(k)) {
shortcut.add(String(keyCombination[k]), function () {
var btnAdd = document.getElementById(String(k));
btnAdd.focus();
btnAdd.click();
});
}
}
});
if i give like this means it is working
shortcut.add("Alt+S", function () {
var btnAdd = document.getElementById('btnAdd ');
btnAdd .focus();
btnAdd .click();
});
shortcut.add("Alt+C", function () {
var btnCancel = document.getElementById('btnCancel');
btnCancel.focus();
btnCancel.click();
});
but if i try to add dynamically its overriding help me this issue.
Thanks in Advance.
I created a separate function outside the document.ready function like this now its working fine.
$(document).ready(function fn() {
var keyCombination = new Object();
keyCombination['btnAdd'] = "Alt+S";
keyCombination['btnCancel'] = "Alt+C";
for (var k in keyCombination) {
if (keyCombination.hasOwnProperty(k)) {
Set_KeyCombinations(k, keyCombination);
}
}
});
function Set_KeyCombinations(k, keyCombination) {
shortcut.add(String(keyCombination[k]), function () {
var eleId = document.getElementById(String(k));
if (eleId) {
if ($('#' + String(k).trim()).css('display') !== 'none' && eleId.getAttribute("disabled") !== "disabled") {
eleId.click();
eleId.focus();
}
}
});
}
Try this:
var keyCombinations = [ "Ctrl+Shift+X" , "Ctrl+Shift+Y" ];
for(var i=0; i<keyCombinations.length; i++){
(function(shorcutCombination){
shortcut.add(shorcutCombination,function() {
alert("i am " + shorcutCombination);
});
})(keyCombinations[i]);
}
The idea is that you need to preserve the value of keyCombinations[i]
as i increases in the loop. Tested this here: Openjs
At the moment i have a list of elements and when clicked on one of them
it will get the number accordingly. However i need a different approach
that won't count the number of elements but returns the id number of that
specific element.
http://jsfiddle.net/FN4fy/
$('#outputData').on('click', 'li.element', function() {
var num = $('#outputData li.element').index(this);
alert(num);
var loc = window.location + "";
var pos = loc.indexOf('#');
if (pos > -1) {
loc = loc.substring(0, pos);
};
loc = loc + '#ti' + num;
window.location = loc;
});
try this
$('#outputData li').click(function() {
var idOfLi = $(this).attr('id');
alert(idOfLi);
// rest of your code
});
and this is jsfiddle
$(this).attr("id") will give the current element id, because event binded to li.
$('#outputData').on('click', 'li.element', function() {
window.location += $(this).attr("id") ;
});
Javascript:
JSFiddle with ti
JSFiddle without ti
jQuery
JSFiddle With ti
JSFiddle - Without ti
Answer
You can use this.id if you want ti#, or this.id.substring(2) if you just want the number.
You can also use
window.location += "#"+this.id.substring(2);
If you want to go to the location on the current page.
Here is the jsFiddle
$('#outputData').on('click', 'li.element', function() {
var num = $(this).attr('id');
alert(num); // returns id
});
In case you want to fetch the number alone, then
$('#outputData').on('click', 'li.element', function() {
var num = parseInt($(this).attr('id').match(/\d+$/),10);
alert(num); // returns number
});
I have some jQuery plugin that changes some elements, i need some event or jQuery plugin that trigger an event when some text input value changed.
I've downloaded jquery.textchange plugin, it is a good plugin but doesn't detect changes via external source.
#MSS -- Alright, this is a kludge but it works:
When I call boxWatcher() I set the value to 3,000 but you'd need to do it much more often, like maybe 100 or 300.
http://jsfiddle.net/N9zBA/8/
var theOldContent = $('#theID').val().trim();
var theNewContent = "";
function boxWatcher(milSecondsBetweenChecks) {
var theLoop = setInterval(function() {
theNewContent = $('#theID').val().trim();
if (theOldContent == theNewContent) {
return; //no change
}
clearInterval(theLoop);//stop looping
handleContentChange();
}, milSecondsBetweenChecks);
};
function handleContentChange() {
alert('content has changed');
//restart boxWatcher
theOldContent = theNewContent;//reset theOldContent
boxWatcher(3000);//3000 is about 3 seconds
}
function buttonClick() {
$('#theID').value = 'asd;lfikjasd;fkj';
}
$(document).ready(function() {
boxWatcher(3000);
})
try to set the old value into a global variable then fire onkeypress event on your text input and compare between old and new values of it. some thing like that
var oldvlaue = $('#myInput').val();
$('#myInput').keyup(function(){
if(oldvlaue!=$('#myInput').val().trim())
{
alert('text has been changed');
}
});
you test this example here
Edit
try to add an EventListner to your text input, I don't know more about it but you can check this Post it may help
Thanks to #Darin because of his/her solution I've marked as the answer, but i have made some small jQuery plugin to achieve the same work named 'txtChgMon'.
(function ($) {
$.fn.txtChgMon = function (func) {
var res = this.each(function () {
txts[0] = { t: this, f: func, oldT: $(this).val(), newT: '' };
});
if (!watchStarted) {
boxWatcher(200);
}
return res;
};
})(jQuery);
var txts = [];
var watchStarted = false;
function boxWatcher(milSecondsBetweenChecks) {
watchStarted = true;
var theLoop = setInterval(function () {
for (var i = 0; i < txts.length; i++) {
txts[i].newT = $(txts[i].t).val();
if (txts[i].newT == txts[i].oldT) {
return; //no change
}
clearInterval(theLoop); //stop looping
txts[i].f(txts[i], txts[i].oldT, txts[i].newT);
txts[i].oldT = $(txts[i].t).val();
boxWatcher(milSecondsBetweenChecks);
return;
}
}, milSecondsBetweenChecks);
}
I have built a dropdown menu system, everything works when tested independently, the problem I have is in the code below. I use the jQuery ready function to build the menu bar from an external array (menubar[]). Here I am trying to get the mouseover event to call the dropdown() function, but using a different argument for each anchor tag.
So rolling over the first should call dropdown(0), the second dropdown(1) and so on.
$(document).ready(function () {
for (i in menubar) {
var declaration = '<a href="' + baseurl + '/' + menubar[i].url +
'" class="menutitle">' + menubar[i].name + '</a>';
var a = $(declaration).mouseover(function () {
dropdown(i);
}).mouseout(function () {
activeTimer = setTimeout("removedropdowns()", 100);
});
$("#menu").append(a);
}
});
The code is calling dropdown(6); on each rollover. How can I pass the loop variable (i) into the mouseover function as a literal/static value!
I got this working fine in FF by using
.attr('onMouseOver','javascript:dropdown('+i+');')
but that wasn't firing for some versions of IE, so I switched to the jQuery mouseover, which fires, but I have the issue above :(
Your actual problem is that each of your mouseover callbacks uses the same i you increase i all the way up to 6, the callbacks still point to the same i and therefore all use 6 as the value.
You need to make a copy of the value of i, you can do this by using an anonymous function.
$(document).ready(function () {
// you should use (for(var i = 0, l = menubar.length; i < l; i++) here in case menubar is an array
for (var i in menubar) {
var declaration = '<a href="' + baseurl + '/' + menubar[i].url +
'" class="menutitle">' + menubar[i].name + '</a>';
(function(e) { // e is a new local variable for each callback
var a = $(declaration).mouseover(function () {
dropdown(e);
}).mouseout(function () {
activeTimer = setTimeout(removedropdowns, 100); // don't use strings for setTimeout, since that calls eval
});
$("#menu").append(a);
})(i); // pass in the value of i
}
});
$(function() {
$(menubar).each(function(i){
$("#menu").append('' + menubar[i].name + '');
});
$("#menu a").hover(
function(){
dropdown($(this).index());
},
function(){
activeTimer = setTimeout("removedropdowns()", 100);
}
);
});
First, don't use for..in but rather ordinary loop.
Second, I would just append the links first then apply the events later:
$(document).ready(function() {
for (var i = 0; i < menubar.length; i++) {
$("#menu").append('' + menubar[i].name + '');
}
$("#menu a").each(function(index) {
$(this).mouseover(function() { dropdown(index); }).mouseout(function() { activeTimer = setTimeout("removedropdowns()", 100); });
});
});
Have a look here and here.
To capture the current value of i, you need to pass it as a parameter to another function where it can be captured as a local variable:
Try using jQuery's each() function:
jQuery(function() {
jQuery.each(menubar, function(index, element) {
var declaration = '' + element.name + '';
var a = $(declaration).mouseover(function() { dropdown(index); }).mouseout(function() { activeTimer = setTimeout("removedropdowns()", 100); });
$("#menu").append(a);
});
});
In JavaScript, if you don't declare your variable, it is defined globally. To fix this, add "var" in front of your i looping variable like this. UPDATE: As Sime noticed (see comment), you also need to pass the variable into the function, otherwise you form a closure on the i.
$(document).ready(function() {
for(var i in menubar) {
var declaration = '' + menubar[i].name + '';
var a = $(declaration).mouseover(function(i) { dropdown(i); }).mouseout(function() { activeTimer = setTimeout("removedropdowns()", 100); });
$("#menu").append(a);
}
});