jJavascript select box hanging on second select in IE7 - javascript

I have a drop down select box inside a div. When the user clicks on change, a dropdown box appears next to the change/submit button and the user makes a selection which then updates the database and the selection appears instead of the dropdown. All works fine in IE8 and Firefox but in IE7 it allows one selection (there are several identical dropdowns) but the second time a selection is made it hangs on "please wait". This is the relevant code:
<td width=200>
<input type="button" onclick="startChanging(this)" value="Change" /></td>
<script type="text/javascript">
var selectBox, isEditing = false;
var recordvalue;
if( window.XMLHttpRequest ) {
recordvalue = new XMLHttpRequest();
} else if( window.ActiveXObject ) {
try {
recordvalue = new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {}
}
window.onload = function () {
selectBox = document.getElementById('changer');
selectBox.id = '';
selectBox.parentNode.removeChild(selectBox);
};
function startChanging(whatButton) {
if( isEditing && isEditing != whatButton ) { return; } //no editing of other entries
if( isEditing == whatButton ) { changeSelect(whatButton); return; } //this time, act as "submit"
isEditing = whatButton;
whatButton.value = 'Submit';
var theRow = whatButton.parentNode.parentNode;
var stateCell = theRow.cells[3]; //the cell that says "present"
stateCell.className = 'editing'; //so you can use CSS to remove the background colour
stateCell.replaceChild(selectBox,stateCell.firstChild); //PRESENT is replaced with the select input
selectBox.selectedIndex = 0;
}
function changeSelect(whatButton) {
isEditing = true; //don't allow it to be clicked until submission is complete
whatButton.value = 'Change';
var stateCell = selectBox.parentNode;
var theRow = stateCell.parentNode;
var editid = theRow.cells[0].firstChild.firstChild.nodeValue; //text inside the first cell
var value = selectBox.firstChild.options[selectBox.firstChild.selectedIndex].value; //the option they chose
selectBox.parentNode.replaceChild(document.createTextNode('Please wait...'),selectBox);
if( !recordvalue ) {
//allow fallback to basic HTTP
location.href = 'getupdate.php?id='+editid+'&newvalue='+value;
} else {
recordvalue.onreadystatechange = function () {
if( recordvalue.readyState != 4 ) { return; }
if( recordvalue.status >= 300 ) { alert('An error occurred when trying to update'); }
isEditing = false;
newState = recordvalue.responseText.split("|");
stateCell.className = newState[0];
stateCell.firstChild.nodeValue = newState[1] || 'Server response was not correct';
};
recordvalue.open('GET', "getupdate.php?id="+editid+"&newvalue="+value, true);
recordvalue.send(null);
}
}
</script>
If anyone has any idea why this is happening I'd be very grateful

ok managed to solve it. I moved the recordvalue.open line near the bottom inside te last else loop and it works perfectly in all browsers just don't ask me why

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

Can't make TAB change the editor on dgrid

I'm trying to make the TAB key navigate on my dGrid. I have used as a base the solution found at Dgrid set focus on cell, but there are a couple of issues I'm running into which I couldn't solve so far.
Below you can find the block I'm using now; Not all columns have editors, so for I added a var do the element definition to select the next column instead of doing a right. I also added support for SHIFT+TAB to make backwards navigation possible. MT4.prje.grids[gridId]is the dGrid instance. There might be various on the page.
The grid is created with
MT4.prje.grids[gridId] = new (declare([OnDemandGrid, Keyboard, Selection, CellSelection]))(gridInfo, gridId);
where gridInfo has the column definitions and the store. The store is created as:
new Observable(new Memory({'data': {}, 'idProperty': 'id'}));
The editors are usually TextBox, NumberTextBox and Select dijit widgets, all set to autoSave.
aspect.after(MT4.prje.grids[gridId], "edit", function (promise, cellNode) {
if (promise === null) return;
promise.then(function (widget) {
if (!widget._editorKeypressHandle) {
widget._editorKeypressHandle = on(widget, "keypress", function (e) {
for (var rowId in MT4.prje.grids[gridId].selection) {
break;
}
for (var columnId in MT4.prje.grids[gridId].selection[rowId]) {
break;
}
if (e.charOrCode == keys.TAB) {
e.preventDefault();
var cellToEdit = null,
cellEdited = MT4.prje.grids[gridId].cell(rowId, columnId);
if (e.shiftKey) {
if (cellEdited.column.previousEditor === undefined) {
rowId = parseInt(rowId) - 1;
if (MT4.prje.grids[gridId].row(rowId).element !== null) {
for (var lastColumnId in MT4.prje.grids[gridId].columns) {}
cellToEdit = MT4.prje.grids[gridId].cell(rowId, lastColumnId);
}
} else {
cellToEdit = MT4.prje.grids[gridId].cell(rowId, cellEdited.column.previousEditor);
}
} else {
if (cellEdited.column.nextEditor === undefined) {
var firstColumnId = null;
rowId = parseInt(rowId) + 1;
if (MT4.prje.grids[gridId].row(rowId).element === null) {
var fields = {};
for (var cId in MT4.prje.grids[gridId].columns) {
if ((cId != 'excluir') && (firstColumnId === null)) {
firstColumnId = cId;
}
fields[cId] = '';
}
MT4.prje.addRowToGrid(gridId, fields);
} else {
for (var cId in MT4.prje.grids[gridId].columns) {
if (cId != 'excluir') {
firstColumnId = cId;
break;
}
}
}
cellToEdit = MT4.prje.grids[gridId].cell(rowId, firstColumnId);
} else {
cellToEdit = MT4.prje.grids[gridId].cell(rowId, cellEdited.column.nextEditor);
}
}
if (cellToEdit) {
MT4.prje.grids[gridId].deselect(cellEdited);
MT4.prje.grids[gridId].select(cellToEdit);
MT4.prje.grids[gridId].edit(cellToEdit);
}
}
});
}
});
});
Even ignoring the new line part, there are a couple of errors that happen. First of all, the editor barely pops into existence and them disappears, together with the selection. Sometimes when tabbing to an empty column, the editor will be filled with the values of the previous editor. Is there a way to do it more consistently?
What I'm figuring is that there is a race condition happening on the sharedEditor (they are set to editOn: focus). I tried wrapping the deselect/select on a dojo.on('blur') and emit it. But that doesn't get consistently correct with the dijit/form/Select widgets. Is there a better event that I can call for it?
I also tried changing the final block to:
if (cellToEdit) {
on(cellToEdit.element, 'focus', function(){
MT4.prje.grids[gridId].select(cellToEdit);
});
on(cellEdited.element, 'blur', function(){
MT4.prje.grids[gridId].deselect(cellEdited);
on.emit(cellToEdit.element, 'focus', {'bubble': true, 'cancelable': false});
});
on.emit(cellEdited.element, 'blur', {'bubble': true, 'cancelable': false});
}
But that gives two errors:
If I do make changes to a cell it does not go to the next editor. Does not even select it.
The first time I move from an empty cell to another empty cell it doesn't work either.
Anyone got any ideas?
This fix works on dgrid 0.3.11.
Add to your dgrid's postCreate.
postCreate: function() {
var that = this;
this.inherited(arguments);
this.on('dgrid-datachange', function(evt) {
that._selectedCell = that.cell(evt);
});
aspect.after(this, 'save', function(dfd) {
dfd.then(function() {
var nextCell = that.right(that.cell(that._selectedCell.row.id, that._selectedCell.column.id));
that.edit(nextCell);
// Bonus Fix. Workaround dgrid bug that blocks field text to be selected on focus.
nextCell.element.widget && nextCell.element.widget.textbox && nextCell.element.widget.textbox.select();
});
});
}

Javascript seems not working to load image when page loads

I'm using Javascript to make my checkboxes larger. Doing this I use image one for black checkbox and another one with the checked checkbox. It works like the real checkbox. However, when the page loads, the black checkboxes are not successfully loaded unless I click somewhere in the page to invoke them. Please check here to the page.
Belowing is my js code which I think it will impact this:
var Custom = {
init: function() {
var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
for(a = 0; a < inputs.length; a++) {
if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
span[a] = document.createElement("span");
span[a].className = inputs[a].type;
if(inputs[a].checked == true) {
if(inputs[a].type == "checkbox") {
span[a].style.background = unchecked;
} else {
span[a].style.background = unchecked;
}
}
inputs[a].parentNode.insertBefore(span[a], inputs[a]);
inputs[a].onchange = Custom.clear;
if(!inputs[a].getAttribute("disabled")) {
span[a].onmousedown = Custom.pushed;
span[a].onmouseup = Custom.check;
} else {
span[a].className = span[a].className += " disabled";
}
}
}
}
Below is my image on form load:
And this is my page when clicking on anywhere:
Which other functions and variables are already defined. Thus could anyone help me to enable them to display whenever the form loads?
I don't known why you use that
if(inputs[a].checked == true) {
if(inputs[a].type == "checkbox") {
span[a].style.background = unchecked;
} else {
span[a].style.background = unchecked;
}
}
But when I open your script in http://checkintonight.freeiz.com/js/custom-form-elements.js
Try to call function clear() in end of Custom.init(), it works
init: function() {
//
...
//
this.clear();
}
Sorry for my bad English
Eventually, I found a bug in my Javascript code. I add the else statement in the init() function to test if the checkbox is also not checked. So the code becomes like below:
if(inputs[a].checked == true) {
if(inputs[a].type == "checkbox") {
span[a].style.background = unchecked;
}
} else {
span[a].style.background = unchecked;
}
Then it works! Thanks everyone that reviewed and answered to my question.

How to send Gmail talk messages using Gmails built it method

I want to create a Google Chrome extension that, among other things, will modify the chat text based on what is inputed. I will add a button next to the video, call, and add people buttons below the name, and when clicked will activate the modifications. I don't want to have to put any more scripts on the page than I have to, so I would like to be able to send the messages the way Gmail would be pressing "return" in the chat box. Also I want to to be able to show that both of the people chatting are using my extension by displaying text in the chat box just like the "This chat is off the record" text is, and possibly if both are using it add extra stuff to the chat. What I tried to do was make an imitation textarea and when the user 'sends' it, grab it and modify it, then insert it into the real one and send the new text. I can change the text but can't seem to send it...
Heres what I have so far, I enclosed everything in a setInterval to check if chat box exists and add appropriate stuff to it:
var chatBtnClone = setInterval(function() {
if ($("body").find(".nH .NG").length > 0) { //if chat is active
var clone = $("body").find(".nH .NG .NJ").first();
if (clone.children()[0].className.indexOf("chat") < 0) { //if already added my class
var clonned = clone.clone();
var clonnedChd = clonned.children().first();
clonnedChd.attr("title", "Start encrypted chat");
clonnedChd.on('click', function() {
console.log("clicked chatBtn!"); //make sure it works
var self = $(this);
if (self[0].className.indexOf("chatEncX") >= 0) { //toggle button pic
self.removeClass('chatEncX').addClass('chatEnc');
self.attr("title", "Stop encrypted chat");
} else {
self.removeClass('chatEnc').addClass('chatEncX');
self.attr("title", "Start encrypted chat");
}
});
clone.parent().prepend(clonned);
clonned.find('.NK').removeClass("NK-Y8").addClass("chatEncX");
}
var chatBoxs = $('body').find(".nn .AD");
var chatArea = chatBoxs.first().find(".nH textarea"); //get chat textareas
if (chatArea.length === 1) {
var clonChatArea = chatArea.first().clone();
clonChatArea.removeAttr("id");
chatArea.first().parent().append(clonChatArea);
// chatArea.first().hide();
var chatTextDiv = chatBoxs.first().find(".jp .nH .nH").first();
clonChatArea.focusin(function() {
chatTextDiv.removeClass("gv").addClass("f7");
});
clonChatArea.focusout(function() {
chatTextDiv.removeClass("f7").addClass("gv");
});
clonChatArea.on('keyup', function(event) {
var self = this;
//console.log(this.style.height); //make sure height it working
if (self.scrollHeight === 38) {
self.style.overflowY = "hidden";
self.style.height = "36px";
} else if (self.scrollHeight === 47) {
self.style.height = "54px";
} else if (self.scrollHeight === 62) {
self.style.height = "72px";
} else if (self.scrollHeight >= 77) {
self.style.height = "80px";
self.style.overflowY = "scroll";
}
if( event.keyCode === 13 && event.shiftKey ){
//regular, just insert a newline
} else if (event.keyCode === 13) {
//grab text and modify then reinsert into real textarea
var chatTxt = $(this).val();
var chatHidden = chatBoxs.first().find(".nH textarea").first();
var chatEncTxt = Crypto.AES.encrypt(chatTxt, "pass"); //modify text
//console.log(chatEncTxt);
chatHidden.val(chatEncTxt);
chatHidden.focus();
chatHidden.trigger({ type : 'keypress', which : 13 }); //try to imitate the return key and send (NOT WORKING!!!)
// $(this).focus();
}
});
}
}
},150);
This might be a bit late, but if anyone else is interested then I managed this by doing the following:
var e = new Event("keypress");
e.keyCode = e.which = 13;
// :mc is an example textarea id, but the OP has the code for finding that already
document.getElementById(':mc').dispatchEvent(e);

Javascript: How to make this function working for click effects

I am designing a page where it displays the staff details in following structure :
user can click anywhere in the details box and the checkbox will get selected along with the change in the className of the details <div> box.
The problem i m facing is when i click anywhere in the details box it works fine.. but when i click on checkbox it only changes the className but doesnt make any changes to checkbox.
Also there is one condition, few users are allowed to selected limited staff at a time and few are allowed to select all of them..
I have assigned a myClick() function to the outer <div> box (one with red border)
and the function is :
var selectedCount = 0;
myClick = function(myObj,event)
{
var trgt =(event.srcElement) ? event.srcElement : event.target;
tgName = trgt.tagName;
//following statement gives me correct details element event though i clicked on any child tags
theElem = (tgName == 'DIV') ? trgt : ( (tgName == 'B') ? trgt.parentNode.parentNode : trgt.parentNode);
if(allowed_selection == 'unlimited')
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
}
else if(theElem.className == 'details_hover')
{
theElem.className = 'details_clicked';
if(tgName != 'INPUT') theElem.getElementsByTagName('input')[0].checked = true;
}
}
else
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
selectedCount--;
}
else if(theElem.className == 'details_hover')
{
if(selectedCount == allowed_selection ) return false;
theElem.className = 'details_clicked';
//i think, this is the suspicious area for errors
theElem.getElementsByTagName('input')[0].checked = true;
selectedCount++;
}
}
return false;
};
The problem is these return lines in your function:
return false;
When you connect an event to a form element that performs an action, such as a checkbox or button, returning false will prevent that default action. It stops the event from taking place as it regularly would.
You could try something like this at the top of your function:
var returnValue = (tgName == 'INPUT' && trgt.type == "checkbox") ? true : false;
And then when calling 'return ', use:
return returnValue;
If you return true you allow the checkbox to act as normal and check / uncheck itself.

Categories