Javascript Debugging in Chrome Console - javascript

I have below piece of code.
<div id="start_3333" onclick="doCalc(3333, this)"></div>
function doCalc(this)
{
var id = $(this).attr(id);
Console.log(id);
}
This div gets inserted for every row in data tables. I would like to test this function doCalc in console window of Chrome by typing doCalc(3333) but getting undefined error. how do I pass "this" object in Chrome's console window so that I can debug and check what value is getting transferred to "id" variable within the function.

I would suggest a different implementation:
<div id="start_3333"></div>
$("#start_3333").click(function(event) {
console.log($(event.target).attr("id"));
});

Get a reference to your div:
var $myRef = $('start_3333');
Run your function:
doCalc($myRef);
and of course as I commented above, make the 'c' in 'console' lowercase because JavaScript is case sensitive.

To answer the general question.
Go into the Elements tab of the debugger, and find the element you want to use. If you click on it, it will display == $0 next to the element. This means that you can use the variable $0 in the console to refer to that element. Also, the previous item that you clicked on becomes $1, the one before that is $2, and so on. So you can then type
doCalc(3333, $0)
in the console to run your function with that element as the argument.
This won't work for your function, since it's not declared to take two arguments. Your function should be something like:
function doCalc(num, element) {
var id = element.id;
console.log(id);
}

Related

Why the execution does not get into the $('input[type="checkbox"]').each?

First time using $('input[type="checkbox"].each function. This is a snapshot taken from firefox debugger.
At the left, the code. At right, the watch window with the value of the array of input-checkbox elements. Execution jumps from line 4th to 7th, what would be ok if the array was empty.
Can anybody tell me why the execution does not get into the loop?
The loop has been executed. You can see in the tooltip that the array has 140 entities within it. The problem is because they are all undefined.
This is because jQuery objects don't have an id property. You need to get that from the Element instead, using either prop() or this.id:
if (this.value)
ids.push(this.id);
That being said you can make the code more succinct by using map() to build the array instead of each():
$('#seguent').on('click', function() {
var ids = $(':checkbox').map((i, el) => el.value ? el.id : null);
$.post('llista_cursos', { ids: ids });
});
Final note, this retrieves all checkboxes regardless of whether they were checked or not. You may want to include :checked in the selector.

Google Chrome not letting me use setAttribute for ID's

I've got some JS code here. Basically, I am trying to change the ID of an element to some value from a previous variable.
Here's what I got so far;
function() {
var colorarray = [ "RANDOMCOLOR_0", "RANDOMCOLOR_1", "RANDOMCOLOR_2" ];
var RANcolorarray = colorarray[Math.rsound(Math.random() * (colorarray.length - 1))];
document.getElementsByClassName('RANDOMCOLOR').setAttribute('id', RANcolorarray);
}
This code throws an error in Chrome for line 4: Uncaught TypeError: undefined is not a function which is weird because JsLint finds no errors.
I also tried using the other way to setting id's;
document.getElementsByClassName('RANDOMCOLOR').id = RANcolorarray;
However, although this method does not throw an error on chrome or jslint - it does not work at all after inspecting the element.. :/
Any ideas?
document.getElementsByClassName('RANDOMCOLOR') returns a list of DOM nodes (even if there's only one match) so you can't just call .setAttribute() on the list as the list doesn't have that method.
You can either get the first item out of the list and call .setAttribute() on that one or use a for loop to iterate through the list and call it on all of them. Of course, since you're setting the id, you should not be setting multiple elements to the same id, so I'll assume you just want one element:
document.getElementsByClassName('RANDOMCOLOR')[0].id = RANcolorarray;
Or, a little more safe:
var elems = document.getElementsByClassName('RANDOMCOLOR');
if (elems && elems.length) {
elems[0].id = RANcolorarray;
}

How do I display the value of a jQuery variable for testing?

I am working on a slider that uses jQuery. Some elements of the slider are working correctly, but there is a problem that I am trying to troubleshoot with some of the code. To test it I would like to be able to display the values of the variables in the statement.
Here is the code block I am working with:
$('.marquee_nav a.marquee_nav_item').click(function(){
$('.marquee_nav a.marquee_nav_item').removeClass('selected');
$(this).addClass('selected');
var navClicked = $(this).index();
var marqueeWidth = $('.marquee_container').width();
var distanceToMove = marqueeWidth * (-1);
var newPhotoPosition = (navClicked * distanceToMove) + 'px';
var newCaption = $('.marquee_panel_caption').get(navClicked);
$(' .marquee_photos').animate({left: newPhotoPosition}, 1000);
});
I added a div called 'test' where I would like to display the values of the variables to make sure they are returning expected results:
<div class="test"><p>The value is: <span></span></p></div>
For example, to test the values, I inserted this into the statement above:
$('.test span').append(marqueeWidth);
However, I don't get any results. What is the correct way to include a test inside that code block to make sure I am getting the expected results?
Thanks.
Just use JavaScript's console functions to log your variables within your browser's console.
var myVar = 123;
console.log(myVar, "Hello, world!");
If you're unsure how to open the console within your browser, see: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
append is used to append either an HTML string, a DOM element, an array of DOM elements, or a jQuery element. Since you are just trying to show a number (marqueeWidth), you probably want to set the text of the span instead:
$('.test span').text(marqueeWidth);
Also, is there a particular reason why you don't just use the console? It may be worth reading over a Debugging JavaScript walkthrough.
you can use the following.
$('.test span').html(marqueeWidth);
However doing a console.log(yourvariable); or alert(yourvariable); is better.

Moving inline code into function, with object name generation

I am customizing Denis Gritcyuk's Popup date picker.
This pop-up script uses inline Javascript in a href link, to set the selected date into the input field, in the parent window, that is was called for. An example URL looks like:
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.close();">3</a>
The input field name, (e.g. document.formname.field), is passed to the script as a string parameter.
I would like to add things done when that link is clicked (e.g. change background color of field, set flag, etc.). So while this DOES work, it's getting ugly fast.
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.opener.document.formname.field.style.backgroundColor='#FFB6C1';
window.close();">3</a>
How would I move these inline commands into a JS function? This would give me much cleaner URLs and code. The URL would now look something like
3
with a function like (this example obviously does NOT work):
function updateField (str_target, str_datetime) {
var fieldName = "window.opener" + str_target;
[fieldName].value = str_datetime;
[fieldName].style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
So any suggestions on how this can be done, please?
I'd prefer to hide the dom path tracing back from the current window back to the opener. It's appropriate to bake that into the function since the function will always be used in the context of that child popup. Then your function call is cleaner and more readable. Obviously, replace "myField" with the ID of the field you're intending to update.
3
function updateField ( str_date, str_fieldname ) {
var fieldToUpdate = document.getElementById( str_fieldname );
fieldToUpdate.value = str_date;
fieldToUpdate.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
You're acessing the property incorrectly. Try:
function updateField (str_target, str_datetime) {
var fieldName = window.opener;
str_target = str_target.split('.');
for (var i = 0; i < str_target.length; i++)
fieldName = fieldName[str_target[i]];
fieldName.value = str_datetime;
fieldName.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
The bracket notation ([]) is only used for properties of objects, not objects themselves. If you found my post helpful, please vote for it.
You can build a string and evaluate it as code using the eval function, but I would recommend against it.
There are a couple of things wrong with your code:
You cannot use the [] operator in a global context, you have to suffix it on an object, so you can say window["opener"] and this will be equivalent to window.opener, but there is no such thing as simply ["window"]
When navigating nested properties, as in window.opener.document you cannot navigate multiple levels using the [] operator. I.e. window["opener.document"] is not allowed. You must use window["opener"]["document"] instead.

Jquery global variable assignment and using in javascript function

I have a global variable listId(refer the below code) declared with a default value and then I am assigning it inside the jq("#nav1 li a").click(function() But once any of the other javascript function call takes place after this one, the listId does not reflect the changed value, instead its just the default value assigned during declaration. How can I make it reflect the changed values?
thanks
listId = 'x';
var jq=jQuery.noConflict();// for avoiding conflict
jq("#nav1").click(function(){
alert(this.id);
listId = this.id; //this.id is displayed in alert message
});
function pageSwitch(){
alert('on change id : '+listId);
//when called after the click function, this does not reflect changed values
}
The code you supplied worked for me. The listId variable was successfully changed to "nav1". I've written up a little test script, which changes listId to the div's id onClick, and then uses a function to change it back to "x". It works every time. Click here to test it.
Thanks guyz for the help..actually the function was invoked on click of an h:commandLink..so each time the page got reloaded and so did the js functions...I just used the a4j:commandLink and it worked fine...I should have presented the full picture..Sorry for that..will take care next time.

Categories

Resources