I'm having a problem trying to make this code work. The purpose is simply to enable a textbox when the option "Bus" is selected from a DropList.
At the moment I have a for loop running through and disabling all the necessary boxes (there are 15 identical rows). At the same time it is enabling a different function which is based on changing the selection in the same box, which works. Whereas the function in question doesn't work.
Here is the function:
$(function () {
for(var i=0;i<15;i++){ //loop through each of the rows
$("#Select" + i + "Box_C").change(callbackFactory(i)); //This is a working function
$("#Select" + i + "Box_C").change(toBus(i)); //This one isn't working
$("#Text" + i + "Box_Q1").prop('disabled', true); //this one is working
};
function busEnabler(num){
$("#Text" + num + "Box_Q1").prop('disabled', false);
};
function toBus(numm){
var jk = numm //Closures confuse me
if ($("#Select" + numm + "Box").val() === "Bus"){
$("#Text" + numm + "Box_Q1").prop('disabled', false);
console.log(jk);
busEnabler(jk);
}
else {
$("#Text" + numm + "Box_Q1").prop('disabled', true);
console.log($("#Select" + numm + "Box_C") + "=" + $("#Select" + numm + "Box_C").val());
}
};
});
The ID's are made up (the real ones are horribly named - not my choosing) so if there is a typo in the ID's it's irrelevant.
Also as a side note I can't seem to log anything to the console after the page has loaded (using FireBug).
callbackFactory:
function callbackFactory(i){
console.log('changing');
return function(){
transportChange($("#_Q0_Q"+ i +"_Q3_C").val(), i);
};
The problem is in the way you are attaching the onchange events.
The following statement (that you have used) does not attach any method.
$("#Select" + i + "Box_C").change(toBus(i));
So whenever the value of the select box changes, the 'toBus' method is never called.
I have created a Fiddle. Please refer that.
JSFiddle
Use the following code for your purpose and please show the function callbackFactory also, so that I can resolve your complete problem.
$(doucment).on('change', 'select[id^=Select]',function() {
$('input[id^=Text]').prop({disabled:true});
var id = $(this).attr('id');
var txtId = id.replace('Select','Text').replace('Box','Box_Q1');
if($(this).val() == 'Bus') {
$('#'+txtId).prop({disabled:false});
}
});
Related
i am in trouble with javascript‘s callback,my code seems simple:
var i =0;
for (; i < listSize+1; i++) {
var content = "content"+i;
$("#" + content).focus(function () {
$("#" + content).keydown(check(new Number(i)));
$("#" + content).keyup(check(new Number(i)));
});
}
where lisetSize=3 in my test case and content is the html element's id
and the callback function check(my_num) is:
function check(my_num) {
var content = "content"+my_num;
}
then i try to trigger this function through keyboard input.
however,i got the result that content=content4 all the time via my broswer's debugger,even though the listening element is content0
i have try anyway such as $.extend({},i) $.extend(true,{},i)
it make no difference
now i have no idea about this problem,how can i just pass a value but no reference to the callback function's parameter?
You're not declaring the handlers correctly.
Replace:
$("#" + content).keydown(check(new Number(i)));
$("#" + content).keyup(check(new Number(i)));
With:
$("#" + content).keydown(function(){check(new Number(i));});
$("#" + content).keyup(function(){check(new Number(i));});
What you need to pass to keyup and keydown, are functions that need to be called when keyboard events happen.
What you were passing to keyup and keydown, were the results of calling check(new Number(i)).
Also, since you're declaring these in a loop, you'll want to copy the number to a new variable, in order to reference the current loop iteration's value:
$("#" + content).focus(function () {
var currentNumber = i;
$("#" + content).keydown(function(){check(currentNumber);});
$("#" + content).keyup(function(){check(currentNumber);});
});
Thanks for Cerbrus,even though there is still problem.
Now I realize that the problem was caused by misunderstanding the real running order.
Even after the loop ends up, $("#" + content).focus will still be called once user click the element.And then,the program starts the code
function () {
$("#" + content).keydown(function(){check(currentNum);});
$("#" + content).keyup(function(){check(currentNum);});
}
As the loop has ended,currentNum=4,so everything got an error.
Here is my solution:
for (var i = 0; i < listSize + 1; i++) {
var content = "content" + i;
$("#" + content).focus(function () {
$(this).keydown(function () {
check($(this));
});
$(this).keyup(function () {
check($(this));
});
});
}
function check(trigger) {
var my_num = getContentNum(trigger);
}
function getContentNum(content) {
return (content.attr("id").charCodeAt(7))-48;
}
Not elegant but useful.
Hi guys this might be a really stupid error but im using jquery to add a formset to a page it also does other things such as updating the number of forms but that does not seem to be a issue.
http://jsfiddle.net/b5Y8f/
$(document).ready(function () {
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '_set-\\d+-)');
var replacement = prefix + '_set-' + ndx + '-';
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function changeDeleteForms(el, prefix, formid) {
var idstring = 'id_' + prefix + '_set-' + formid + '-DELETE';
//$('<input>').attr({type: 'hidden', id: 'id_' + idstring, name: idstring}).appendTo('.command-delete');
$('#' + idstring).prop('checked', true);
}
function deleteForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '_set-TOTAL_FORMS').val());
if (formCount > 1) {
// Delete the item/form
$(btn).parents('.command').hide();
$(btn).parents('.command').attr('class', 'command-delete');
var dc = $(".command-delete");
$(dc).children().children().children().each(function () {
var formid = this.id.match(/\d+/g);
changeDeleteForms(this, prefix, formid);
//$(this).val("");
});
var forms = $('.command'); // Get all the forms
var formsdelete = $('.command-delete'); // Get all the forms
var fl = parseInt(forms.length);
var fdl = parseInt(formsdelete.length);
var finalcount = fl + fdl
// Update the total number of forms (1 less than before)
//$('#id_' + prefix + '_set-TOTAL_FORMS').val(forms.length);
var i = 0;
} // End if
else {
alert("Please enter atleast 1 command for this item.");
}
return false;
}
function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '_set-TOTAL_FORMS').val());
var maxCount = parseInt($('#id_' + prefix + '_set-MAX_NUM_FORMS').val());
var forms = parseInt($('.command-delete').length); // Get all the forms
var newcount = formCount + forms;
// You can only submit a maximum of 10 todo items
if (newcount < maxCount) {
// Clone a form (without event handlers) from the first form
var row = $(".command:first").clone(false).get(0);
// Insert it after the last form
$(row).removeAttr('id').hide().insertAfter(".command:last").slideDown(300);
// Remove the bits we don't want in the new row/form
// e.g. error messages
$(".errorlist", row).remove();
$(row).children().removeClass("error");
// Relabel or rename all the relevant bits
$(row).children().children().children().children().each(function () {
updateElementIndex(this, prefix, newcount);
$(this).val("");
});
// Add an event handler for the delete item/form link
$(row).find(".delete").click(function () {
return deleteForm(this, prefix);
});
// Update the total form count
$("#id_" + prefix + "_set-TOTAL_FORMS").val(newcount + 1);
} // End if
else {
alert("Sorry, you can only enter a maximum of 1000 items.");
}
return false;
}
// Register the click event handlers
$("#add").click(function () {
return addForm(this, "itemcommands");
});
$(".delete").click(function () {
return deleteForm(this, "itemcommands");
});
$('.command input:checkbox').hide();
});
If you go to the link above you can see the code works perfectly fine it update the form count and add the new form with the new number in the id and everything however in production when you click the add command button for the first 3 times it does not show however the code has been enter into the page and the form is technically there but not shown.
on the fourth time you press the button it works and the row has been added after the last ('.command') in the element.
What could be causing it to work on JSFiddle but not on production?
-------------------UPDATE--------------------------
It seems if i remove the overflow hidden from the 3 that dont show when you press the button the first 3 times it will show them in the correct place.
Why would overflow no be removed from the first 3 form rows but the rest after fine?
----------------------UPDATE--------------------------
Think i have found the issue and its nothing to do with the JQUERY at all it seems to be bootstraps responsive layout hiding the forms i think if i add them specifically to their own rows i can fix this.
Thanks for the help though guys.
I don't see a src="*jQuery source*" in your file. Since JSFiddle already adds the source to the file, you may have forgotten to put it in.
I have dynamic textareas in the web page that are added by jQuery and I have to detect the blur event for them.
JSFIDDLE;
The following code work fine until the entire page is blured (move to another tab, alt-tab press etc) when the blur event is called two times.
// I've already tried with another selector, parent of the textareas
// instead of document, but it's the same result.
$(document).on("blur", "textarea", function () {
$("body").append("<br />Blured the " + (($(this).index() / 2) + 1) + " textarea.");
});
I am looking for a solution using only on function this way and not like bellow (in this case the issue exists too):
var element = $("<textarea></textarea><br />");
element.on("blur", function () {
$("body").append("<br />Blured the " + (($(this).index() / 2) + 1) + " textarea.");
});
...
JSFIDDLE;
So the issue is that when the textarea is focused and the page is blured the blur event is fired twice.
Which is the solution for this?
Is this a browser issue? How to prevent it?
Update: It seems that it is present only in Google Chrome.
OS: Ubuntu 13.04
I've reported the issue here: http://code.google.com/p/chromium/issues/detail?id=253253
An other possible workaround:
http://jsfiddle.net/tpRgf/4/
(function () {
var lastActive;
$(document).on("blur", "textarea", function () {
if (lastActive === this) { return; }
lastActive = this;
$("body").append("<br />Blured the " + (($(this).index() / 2) + 1) + " textarea.");
}).on('focus', "textarea", function () {
lastActive = null;
});
})();
It's a bit of a hack, but you can use a timeout to make sure the event isn't fired twice :
$("button").on("click", function () {
$("#test").append("<textarea></textarea><br />");
});
$(document).on("blur", "textarea", function () {
var self = $(this);
if (! self.data('fired')) {
$("body").append("<br />Blured the " + (($(this).index() / 2) + 1) + " textarea.");
}
self.data('fired', true);
setTimeout(function() {
self.data('fired', false);
},0);
});
FIDDLE
I have a page which is dynamically generated and uses slideToggle to open and close the hierarchical divs etc no problem. The only problem is, everytime I postback I have to generate the divs again and they lose their opened/closed state. They are always generated with the same unique ids.
I would like to use the cookie plugin to remember the states when I call my sltoggle function and then when the page reloads expand all the same divs. Heres what i've got so far...
$(document).ready(function ()
{
$(".toggle-hide").hide();
//something in here about opening the divs in the cookie
});
function sltoggle(eID)
{
$("div[id$='" + eID + "']").slideToggle(600);
//I think the below code is okay - I copied it from a working example ^^
var divState = ($("div[id$='" + eID + "']").css('display') == 'block') ? 1 : 0;
$.cookie("divState", state)
}
Comment explanations inline.
function slToggle(eID) {
var $div = $("div[id$='" + eDI + "']");
//Get value of cookie or empty string
//Cookie is list of eIDs that should be visible
var cooks = $.cookie("divState") || '';
//Determine whether eID is already in the cookie
var isin = $.inArray(eID, cooks.split(','));
//TODO verify that .is("visible") check works during
//toggle animation. Otherwise, this code goes in the
//toggle animation callback function
if ($div.slideToggle(600).is(":visible")) {
//Div is visible, but not in cookie
if (!isin) {
$.cookie("divState", cooks + (cooks ? ',' : '') + eID);
}
}
else if (isin) {
//Div not visible, but in cookie
$.cookie("divState", cooks.replace(/(^|,)eID(,|$)/, ''));
}
}
Is there a way to add the select-result on the url when the pop up window appears? The select-result gives the value of the boxes selected and i want to pass the values selected gto a form but i am not ussing a form. can i pass the values ussing the url?
i want to add the selected values like form.php?id=2882,222,22412,23
$(function() {
$(".selectable").selectable({
filter: "td.cs",
stop: function() {
var result = $("#select-result").empty();
var result2 = $("#result2");
$('.ui-selecting:gt(31)').removeClass("ui-selecting");
confirmation($(".ui-selected").length + " box selected. " + ($(".ui-selected").length));
function confirmation() {
var answer = confirm($(".ui-selected").length + " box selected. " + ($(".ui-selected").length));
if (answer) {
window.open("form.php", "mywindow", "menubar=no,resizable=no,width=650,height=700");
}
else {}
}
$('#divmsg').html($(".ui-selected").length + " box selected")
$('#divmsg2').html($(".ui-selected").length)
if ($(".ui-selected").length > 90) {
alert("Selection of only 90 boxes allowed");
$('#divmsg').html($('#divmsg').html() + ",<br><b>Message: Selection of only 90 pixels allowed!!</b>");
$(".ui-selected").each(function(i, e) {
if (i > 3) {
$(this).removeClass("ui-selected");
}
});
return;
}
$(".ui-selected", this).each(function() {
var cabbage = this.id + ', ';
result.append(cabbage);
});
var newInputResult = $('#select-result').text();
newInputResult = newInputResult.substring(0, newInputResult.length - 1);
result2.val(newInputResult);
}
});
});
this is the fiddle http://jsfiddle.net/dw6Hf/57/
i have tried
window.open ("form.php?id="+ select-result, "mywindow",....
but it won't work!! any idea???
Thanks in advance
If you're asking what I think you're asking, and selectable does what I think it does, then try this:
window.open("form.php?id=" + $('#select-result').text(), "mywindow", "menubar=no,resizable=no,width=650,height=700");
If that doesn't work, then I've obviously misunderstood your answer. I'd suggest clearing it up, and maybe getting a working example up and running for us to see.
Firstly the fiddle you have posted is broken. But no worries i have fixed it along with the solution at http://jsfiddle.net/paragnair/dw6Hf/61/
I have added the following line:
var selectedIds = $.map($('.ui-selected'),function(a){ return $(a).attr('id');}).join(',');
The above line gets the list of ids for all the elements which have the class ui-selected. Then you can append the variable selectedIds to window.open like so:
window.open("form.php?id=" + selectedIds, "mywindow", "menubar=no,resizable=no,width=650,height=700");