I'm trying to generate html on the fly with javascript. I'm binding on the click of buttons on my page. There are multiple buttons on my page which are causing my elements to be bound multiple times which produces the desired results to appear in the amount of times the button has been clicked.
My question is there something that can check if a element is already bound in jquery? If so, how do I incorporate that with the .live() function in jquery.
Here is my code:
$(document).ready(
function () {
$(':button').live("click", ".textbox, :button", function () {
alert("binding");
$(".textbox").click(function () {
defaultVal = this.defaultValue;
if (this.defaultValue) {
this.value = "";
}
});
$(".textbox").blur(function () {
if (this.value == "") {
this.value = defaultVal;
}
});
$('[name="numsets"]').blur(function () {
if (!parseInt(this.value)) {
$(this).val("you need to enter a number");
}
});
$('[name="weightrepbutton"]').click(function () {
var $numsets = $(this).parent().children('[name="numsets"]');
if ($numsets.val() != "you need to enter a number" && $numsets.val() != "Number of Sets") {
var numbersets = parseInt($numsets.val())
repandweight.call(this, numbersets)
$(this).hide();
$numsets.hide();
}
})
});
});
The problem is line 4, every time a button is clicked, all functions that were previous bound seem to be bound to the same function twice, which is a problem.
Thanks for the help!
You are doing it twice ! One inside another. Take out the outer binding and it should work
$(document).ready(function () {
$(document).on("click",".textbox",function () {
defaultVal = this.defaultValue;
if (this.defaultValue) {
this.value = "";
}
});
$(document).on("blur",".textbox",function () {
var item=$(this);
if (item.val() == "") {
item.val(defaultVal);
}
});
$(document).on("blur","input[name='numsets']",function () {
var item=$(this);
if (!parseInt(item.val())) {
item.val("you need to enter a number");
}
});
$(document).on("click","input[name='weightrepbutton']",function () {
var $numsets = $(this).parent().children('[name="numsets"]');
if ($numsets.val() != "you need to enter a number" && $numsets.val() != "Number of Sets") {
var numbersets = parseInt($numsets.val())
repandweight.call(this, numbersets)
$(this).hide();
$numsets.hide();
}
})
});
if you are using jQuery 1.7+ version, consider switching to jQuery on instead of live.
EDIT: Updated live to on as OP mentioned it in the comment.
Related
I have a piece of javascript code which initiates mobile menu dropdown. But while I was working on this, I wasn't paying attention and stupidly copied a code from another source and now I can't click on parent items on mobile menu.
When I remove e.preventDefault();, I'm getting an error in console and menu is not working. Here is the full code. What can I do with my code to make the parent items clickable?
var $dropdownOpener = $('.mobile-header-navigation .menu-item-has-children > a');
if ($dropdownOpener.length) {
$dropdownOpener.each(function () {
var $thisItem = $(this);
$thisItem.on('tap click', function (e) {
e.preventDefault();
var $thisItemParent = $thisItem.parent(),
$thisItemParentSiblingsWithDrop = $thisItemParent.siblings('.menu-item-has-children');
if ($thisItemParent.hasClass('menu-item-has-children')) {
var $submenu = $thisItemParent.find('ul.sub-menu').first();
if ($submenu.is(':visible')) {
$submenu.slideUp(450);
$thisItemParent.removeClass('qodef--opened');
} else {
$thisItemParent.addClass('qodef--opened');
if ($thisItemParentSiblingsWithDrop.length === 0) {
$thisItemParent.find('.sub-menu').slideUp(400, function () {
$submenu.slideDown(400);
});
} else {
$thisItemParent.siblings().removeClass('qodef--opened').find('.sub-menu').slideUp(400, function () {
$submenu.slideDown(400);
});
}
}
}
});
});
}
}
Maybe try to call e.originalEvent.preventDefault() with null checks like :
e && e.originalEvent && e.originalEvent.preventDefault()
I have the following JS function:
const bindSwitches = function() {
$(document).on("click", ".lever", function() {
var checkbox = $(this).siblings("input[type=checkbox]");
var hiddenField = $(this).siblings("input[type=hidden]");
if (checkbox.prop("checked") === true) {
checkbox.prop("value", 0);
hiddenField.prop("value", 0);
} else if (checkbox.prop("checked") === false) {
checkbox.prop("value", 1);
hiddenField.prop("value", 1);
}
$(checkbox).trigger("change");
});
};
It interacts with a switch component provided by the Materialize library. I have just added the final line, as there is some behaviour that needs to occur whenever a checkbox is triggered. But that change event never fires. I also have this function in my app:
const bindAllChecks = function() {
$(document).on("change", ".select-all-check", function() {
var checks = $(this).closest(".table, table").find(".multiple-check:visible");
if (this.checked) {
$.each( checks, function( index, checkbox ){
if ($(checkbox).prop("checked") === false) {
$(checkbox).prop("checked", true);
$(checkbox).trigger("change");
}
});
} else {
$.each( checks, function( index, checkbox ){
if ($(checkbox).prop("checked") === true) {
$(checkbox).prop("checked", false);
$(checkbox).trigger("change");
}
});
}
});
};
Notice how I use the exact same $(checkbox).trigger("change"). In this function it works perfectly.
I've tried changing the order in which I bind the events, to make sure the change event is definitely defined beforehand. I've made sure that the rest of the function is being triggered correctly and that there are no issues in that regard. I've also tried different variations of alternative syntax, nothing has worked.
Here is the code it is supposed to trigger:
const bindCheckboxOverride = function() {
$(document).on("change", ".checkbox-collection input[type=checkbox]:not(.select-all-check)", function() {
var hiddenField = $(this).prev();
if(hiddenField.attr("disabled") === "disabled") {
hiddenField.removeAttr("disabled");
} else {
hiddenField.attr("disabled", "disabled");
}
});
};
I still don't have an exact solution to the question I asked, but I have come up with an alternate method. Instead of trying the trigger a change, I have pulled out the functionality I want from the change even into its own function:
const bindCheckboxOverride = function() {
$(document).on("change", ".checkbox-collection input[type=checkbox]:not(.select-all-check)", function() {
handleCheckboxDisable(this);
});
};
const handleCheckboxDisable = function(checkbox) {
var hiddenField = $(checkbox).prev();
if(hiddenField.attr("disabled") === "disabled") {
hiddenField.removeAttr("disabled");
} else {
hiddenField.attr("disabled", "disabled");
}
};
So now I'm able to call this function directly from my other function:
const bindSwitches = function() {
$(document).on("click", ".lever", function() {
var checkbox = $(this).siblings("input[type=checkbox]");
var hiddenField = $(this).siblings("input[type=hidden]");
if (checkbox.prop("checked") === true) {
checkbox.prop("value", 0);
hiddenField.prop("value", 0);
} else if (checkbox.prop("checked") === false) {
checkbox.prop("value", 1);
hiddenField.prop("value", 1);
}
handleCheckboxDisable(checkbox);
});
};
It doesn't answer the question but I thought that may be of help to somebody. Would still like to know why the original code doesn't work if anybody has any insights.
can we stop prevent blur or tabbing for 5 second in input field.then after 5 second user can tab from one field to another.I use off and on function but it is not working .here is my code
http://jsfiddle.net/GV3YY/99/
$("input").off("blur");
setTimeout(function(){
$("input").on("blur");
},5000)
You need to "lock" the inputs when they is focused and use setTimeout to "unlock" it after 5 seconds. A naive implementation could look something like this: https://jsfiddle.net/my7wk6gj/2/
Update: Now pseudo prevents bluring by click. The blur still happens, but focus is returned to the original input until the 5 seconds have passed. I couldn't get event.stopImmediatePropagation to work for blur, so this is the next best thing...
var lockInput = false;
var focusTarget = null;
var lockTimeout = null;
$('input').on('focus', function (e) {
if (lockTimeout) {
return;
}
lockInput = true;
lockTimeout = setTimeout(function () { lockInput = false; lockTimeout = null }, 5000)
}).on('keydown', function (e) {
if (e.keyCode === 9 && lockInput) {
e.preventDefault();
return false;
}
}).on('blur', function (e) {
console.log('blur')
if (lockInput && focusTarget === null) {
focusTarget = e.target;
setTimeout(function () {
focusTarget.focus();
focusTarget = null;
});
}
});
The global variables are used only for the example, i'd advice against that.
Also, if you have a large number of inputs, i'd suggest using event delegation, instead of adding a listener to every one of them.
I have a form with a few input fields, I only want to show a div when all the input fields got content, when one of the input fields has no content the div should disappear again.
I made it work with one input field, but how do I get it to work when all the input fields are filled in (don't know if its a good clean way?):
$(function () {
$('input').change(function() {
$('.next').toggle($(this).val().length !== 0);
}); });
Fiddle:
http://jsfiddle.net/uQyH9/19/
Try this : http://jsfiddle.net/uQyH9/21/
$(function () {
var _cached=$('input');
_cached.change(function() {
if (_cached.filter(function (){return $(this).val().length }).length==_cached.length)
$('.next').show();
else
$('.next').hide();
});
});
You can use a filter function to check that all the input are filled.
Code:
$(function () {
$('input').change(function () {
$('.next').toggle($("input").filter(function () {
return this.value === "";
}).length === 0)
});
});
Demo: http://jsfiddle.net/IrvinDominin/DwF2P/
UPDATE
You can check the value of the elements by type by cheking type attribute.
Code:
$(function () {
$('input').change(function () {
$('.next').toggle($("input").filter(function () {
var myType=$(this).attr("type");
if (myType === "checkbox") return !$(this).is(":checked");
if (myType==="radio"){
var myName = $(this).attr("name");
if (myName==="") return !$(this).is(":checked");
return $('input[name='+ myName +']:checked').length===0
}
return this.value === "";
}).length === 0)
});
});
Demo: http://jsfiddle.net/IrvinDominin/pqJhg/
Loop over the inputs. If you find one that isn't filled in, then hide the DIV. If you don't, show the DIV.
$('input').change(function() {
var allFilled = true;
$('input').each(function() {
if (this.value === '') {
allFilled = false;
return false; // Terminate the loop
}
}
$('.next').toggle(allFilled);
});
I have this two HTML Form buttons with an onclick action associated to each one.
<input type=button name=sel value="Select all" onclick="alert('Error!');">
<input type=button name=desel value="Deselect all" onclick="alert('Error!');">
Unfortunately this action changes from time to time. It can be
onclick="";>
or
onclick="alert('Error!');"
or
onclick="checkAll('stato_nave');"
I'm trying to write some javascript code that verifies what is the function invoked and change it if needed:
var button=document.getElementsByName('sel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
if( button.getAttribute("onclick") != "checkAll('stato_nave');" &&
button.getAttribute("onclick") != ""){
//modify button
document.getElementsByName('sel')[0].setAttribute("onclick","set(1)");
document.getElementsByName('desel')[0].setAttribute("onclick","set(0)");
} //set(1) and set(0) being two irrelevant function
Unfortunately none of this work.
Going back some steps I noticed that
alert( document.getElementsByName('sel')[0].onclick);
does not output the onclick content, as I expected, but outputs:
function onclick(event) {
alert("Error!");
}
So i guess that the comparisons fails for this reason, I cannot compare a function with a string.
Does anyone has a guess on how to distinguish which function is associated to the onclick attribute?
This works
http://jsfiddle.net/mplungjan/HzvEh/
var button=document.getElementsByName('desel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
var click = button.getAttribute("onclick");
if (click.indexOf('error') ) {
document.getElementsByName('sel')[0].onclick=function() {setIt(1)};
document.getElementsByName('desel')[0].onclick=function() {setIt(0)};
}
function setIt(num) { alert(num)}
But why not move the onclick to a script
window.onload=function() {
var button1 = document.getElementsByName('sel')[0];
var button2 = document.getElementsByName('desel')[0];
if (somereason && someotherreason) {
button1.onclick=function() {
sel(1);
}
button2.onclick=function() {
sel(0);
}
}
else if (somereason) {
button1.onclick=function() {
alert("Error");
}
}
else if (someotherreason) {
button1.onclick=function() {
checkAll('stato_nave')
}
}
}
Try casting the onclick attribute to a string. Then you can at least check the index of checkAll and whether it is empty. After that you can bind those input elements to the new onclick functions easily.
var sel = document.getElementsByName('sel')[0];
var desel = document.getElementsByName('desel')[0];
var onclick = sel.getAttribute("onclick").toString();
if (onclick.indexOf("checkAll") == -1 && onclick != "") {
sel.onclick = function() { set(1) };
desel.onclick = function() { set(0) };
}
function set(number)
{
alert("worked! : " + number);
}
working example: http://jsfiddle.net/fAJ6v/1/
working example when there is a checkAll method: http://jsfiddle.net/fAJ6v/3/