IE8 error when using dyanamic form actions - javascript

Please go here to see an iframe based web app.
Click on the map of Australia, choose a city, then buy some tickets.
Now you will see the cart form located on the lower right corner.
The problem is in IE8, I cannot delete checked rows from the table;
whereas in other browsers such as FireFox3.6, Opera10, Safari4 and Chrome4, this
action is all right.
Below is the related javascript. It doesn't use jQuery, as part of the requirement
is no framework allowed! And iframes are the my best bet, ajax will simply kill me under this restriction.
/* cartForm.js */
function toDeleteRoutes() //this function is executed before form is to be submitted.
{
if(document.getElementsByClassName('delete_box').length > 0) //there're rows to delete
{
document.getElementById('cartForm').action ="./deleteRoutes.php";
document.getElementById('cartForm').target ="section4";
return true; //this enables the form to be submitted as usual.
}
else return false; //there is no more row in table to delete!
}
function toSendEmail() //this function is executed before form is to be submitted.
{
document.getElementById('cartForm').action ="./sendEmail.php";
document.getElementById('cartForm').target ="section3";
document.getElementById('delete_btn').disabled = true; //disable delete button now
return true; //this enables the form to be submitted as usual.
}
function toCancelPurchase()
{
document.getElementById('cartForm').action ="./cancelPurchase.php";
document.getElementById('cartForm').target ="section4";
return true; //this enables the form to be submitted as usual.
}
I don't know which part is wrong, or this is just because IE8 screws all?

You are using the document.getElementsByClassName method, and it is not available on IE.
You should include a custom function to have this functionality.
Personally I like a slightly modified version of the Dustin Diaz implementation:
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) { // use native implementation if available!
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
Check the following article, there are plenty implementations that you can use:
getElementsByClassName Speed Comparison

Related

Disabling Form fields the use the SelectStatic widget in netbox v3 with javascript

I have a problem where i am trying to disable certain forms fields which use the SelectStatic Widget based on a tick box, i have included the javascript below.
const vlan = document.querySelector('#id_vlan');
const physical_facing = document.querySelector('#id_physical_facing');
const service_type = document.querySelector('#id_service_type');
const bd_function = document.querySelector('#id_function');
function vlan_enable(){
vlan.disabled = false;
};
function vlan_disable(){
vlan.disabled = true;
};
function service_function_enable() {
service_type.disabled = false;
bd_function.disabled = false;
};
function service_function_disable() {
service_type.disabled = true;
bd_function.disabled = true;
};
(function() {
service_function_enable();
vlan_enable();
if(physical_facing.checked){
service_function_disable();
} else {
vlan_disable();
}
})();
function pf_event() {
if(physical_facing.checked) {
vlan_enable();
service_function_disable();
} else {
vlan_disable();
service_function_enable();
}
};
physical_facing.addEventListener('change', pf_event)
When on the Page, the VLAN field is a DynamicModelFormField and will never disable, but when toggling the switch on and off the fields do not re-enable, i know the event is getting fired because i can see it in the developer tools, the disabled tag gets applied and removed with no change on the page, This may be a simple mistake but would like if someone can point me in the right direction.
below is what the page looks like
Netbox Page
Has anybody had any success doing this with the new version of netbox as it worked fine in V2 with the SelectStatic2 widget.

Google Analytics client id is not going into hidden field of my form

I am trying to capture Google client id from the cookie to hidden field of my form. I have been trying several solutions but none of them is working for me. Here is my landing page https://explore.labelbox.com/training-data-platforms-101
Solution 1:
<script>
function getClientId (uaid) {
try {
var trackers = ga.getAll();
var i, len;
for (i = 0, len = trackers.length; i < len; i += 1) {
if (trackers[i].get('trackingId') === uaid) {
return trackers[i].get('clientId');
}
}
} catch (e) {}
return 'false';
}
// By waiting for "onload", we give GA enough time to load up before trying to get the Client ID.
window.onload = function () {
// Once the page has completely loaded, this next line finds the hidden field <input id="cid"> and sets its value to the CID.
document.getElementById("cid").value = getClientId('UA-XXXXX-X');
}
</script>
Solution 2:
<script>
function getClientId (uaid) {
try {
var trackers = ga.getAll();
var i, len;
for (i = 0, len = trackers.length; i < len; i += 1) {
if (trackers[i].get('trackingId') === uaid) {
return trackers[i].get('clientId');
}
}
} catch (e) {}
return 'false';
}
// By waiting for "onload", we give GA enough time to load up before trying to get the Client ID.
window.onload = function () {
// Once the page has completely loaded, this next line finds the hidden field <input id="cid"> and sets its value to the CID.
document.getElementById("field-bfbc358e48e39a641df949bd3532ac90-8").value = getClientId('UA-XXXX-X');
}
</script>
Neither case is populating the value to the hidden field. Any thoughts?
I take a quick look at your website, the reason you not getting anything is because ga object is undefined
So it never go to your for loop and it will return false. I think you didn't load the google analytics properly, you can follow the official instruction how to load it, your script should run only after ga is loaded.

Why multiple files selected doesn't work on chrome browser?

Following js code is for html5 multiple files selected [duplicate] that doesn't work for chrome browser, after selecting a file homonymous several times.
For EX: selecting file admin.png for 2 or up times tandem. It only alert for first times.
DEMO (This doesn't work only in chrome browser ): http://jsfiddle.net/s9mt4/
function doClick() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
}
function handleFiles(files) {
var d = document.getElementById("fileList");
var elementArray = document.getElementsByClassName("ImgNameUp");
var ReValue = true;
for (var i = 0; i < elementArray.length; ++i){
if(elementArray[i].innerHTML == files[0].name){
ReValue = false;
}
}
$('.ImgNameUp2').append('<div class="ImgNameUp">'+files[0].name+'</div>')
if (ReValue) {
alert('true');
} else {
alert('false');
}
}
what do i do,change in code that it working right?
Your input fields are listening to the onchange event to fire the javascript.
According to W3C's document:
onchange event occurs when a control loses the input focus and its
value has been modified since gaining focus
if you try to upload the same file, the value of file input does not change so does not fire the function. I think Chrome is the only browser to implement this "correctly".
If you want to upload twice, clear file input value:
function doClick() {
var el = document.getElementById("fileElem");
$(el).val(null); // <-- this line
if (el) {
el.click();
}
}
http://jsfiddle.net/s9mt4/2/

Why is wrong with this JS function? Firefox does work but Chrome doesn't

Hi, I have been coding a little Js function that manipulates certains divs and elements. On firefox it works great, but it does not work in Chrome and halts all the Javascript. I simply don't find what is wrong. Could you be kind enough to let me know? Cookies were tested and work fine. Using Jquery. Thanks!
function RememberMe(addr, bycookie = false)
{
// Cookie name
cookiename = "LBETS";
// Should we reset?
reset = false;
changed = false;
// See if button pressed
if($(".star_"+ addr).hasClass("active"))
{
$('#recent_tx').addClass("table-striped");
$(".star_"+ addr).removeClass("active");
reset = true;
} else {
$(".favstar").removeClass("active");
}
// Iterate rows
$('#recent_tx tr').each(function(){
if($(this).hasClass(addr))
{
if(reset)
{
$(this).removeClass('warning');
} else {
$(this).addClass('warning');
changed = true;
}
} else {
$(this).removeClass('warning');
}
})
// Change class
if(changed)
{
$('#recent_tx').removeClass("table-striped");
$(".star_"+ addr).addClass("active");
setCookie(cookiename, addr, 20*365);
}
// Reset
if(reset)
{
delCookie(cookiename);
}
}
Invalid syntax:
function RememberMe(addr, bycookie = false)
You can't do assignment of defaults in the function signature.
Firefox's JS engine allows this syntax, and it is likely coming in some form to ECMAScript 6.

How to smooth a jQuery script that takes time to execute?

I have a jQuery script that searches in the DOM and shows the results in a list.
There is a simplified version of the script here: http://jsfiddle.net/FuJta/1/
There is usually a large number of results, so the script can take a while to execute. (In the example above, this is simulated with a function that delays the script). So if you type too fast in the searchbox, the script prevents you from typing, and it feels bad.
How could I change my script so that you can type freely, and the results show up when they are ready. I want something like the facebook search : if you type too fast, the results are just delayed, but you can still type.
Html
<p>Type in foo, bar or baz for searching. It works, but it is quite slow.</p><br/>
<input type="text" id="search"/>
<div id="container" style="display:none">
<div class="element">foo</div>
<div class="element">bar</div>
<div class="element">baz</div>
</div>
<div id="results">
</div>​
Javascript
$(function() {
function refreshResults() {
var search = $('#search').val();
var $filtered = $('#container .element').clone().filter(function() {
var info = $(this).text();
return info.toLowerCase().indexOf(search) >= 0;
});
$('#results').empty();
$filtered.each(function() {
$('#results').append($(this));
});
}
// simulating script delay
function pausecomp(millis) {
var date = new Date();
var curDate = null;
do {
curDate = new Date();
}
while (curDate - date < millis);
}
$('#search').keyup(function() {
pausecomp(700);
refreshResults();
});
});​
One solution could to refresh the results only when pressing enter. This way, the delay for searching the results feels ok. But I would prefer if I just delay the results and let the user freely type.
You should perform a search like this using asynchronous techniques. No doubt Facebook uses some sort of AJAX to request search results - which means getting the results from the server. This will help prevent the UI 'freeze' that you are currently experiencing.
Here is a very simple example of what you can try (it uses JQuery for the AJAX requests):
var searchInProgress = false;//used to work out if a search is in progress
var searchInQueue = false;//used to flag if the input data has changed
function getSearchResults(searchText){
if (searchInProgress ) {
searchInQueue = true;
return;
}
searchInProgress = true;
searchInQueue = false;
$.getJSON("URL",//URL to handle AJAX query
{ searchText: searchText},//URL parameters can go here
function (data) {
//handle your returned data here
searchInProgress = false;
if (searchInQueue){//text has changed, so search again
getSearchResults();
}
});
}
$('#search').keyup(function() {
getSearchResults($(this).val());
});
A few things to note: It is probably a good idea to handle failed AJAX requests to ensure you can reset the searchInProgress flag as needed. Also, you can add delays after the keyup as desired, but this all depends on how you want it too work.
From How to delay KeyPress function when user is typing, so it doesn't fire a request for each keystroke? :
var timeoutId = 0;
$('#search').keyup(function () {
clearTimeout(timeoutId); // doesn't matter if it's 0
timeoutId = setTimeout(refreshResults, 100);
});
It does what I want indeed.
Here's a solution that divides the search process into steps, returning flow to the browser during the process to allow the UI to respond.
$(function() {
function searchFunc($element,search) {
var info = $element.text();
return info.toLowerCase().indexOf(search) >= 0;
}
var searchProcessor = null;
function restartSearch() {
console.log('Restarting...');
// Clear previous
if (searchProcessor != null) {
clearInterval(searchProcessor);
}
$('#results').empty();
// Values for the processor
var search = $('#search').val();
var elements = $('#container .element').get();
console.log('l:',elements,elements.length);
// Start processing
searchProcessor = setInterval(function() {
if (elements.length == 0) {
// Finished searching all elements
clearInterval(searchProcessor);
searchProcessor = null;
console.log('Finished.');
} else {
console.log('Checking element...');
var $checkElement = $(elements.shift());
if (searchFunc($checkElement, search)) {
$('#results').append($checkElement.clone());
}
}
}, 10);
}
$('#search').keyup(function() {
restartSearch()
});
});
It only processes one element each time. That should probably be increased so it handles perhaps 10 or 100 each time around, but the important point is that the work is divided into chunks.
This solution should also be faster than the original because it doesn't clone() everything, only the elements that were matched.

Categories

Resources