Getting 'this' object in javascript without using the word 'this' - javascript

What I am trying to do is getting the same result as clicking on this following submit button.
<input id="submit_http:" class="add_submit" type="button" onclick="return dex.forms.form_ajax_submit(this,function(res) { alert('posting failed'); },function(res) { alert('posting success'); });" value="Next" name="submit_http:">
I was trying to do it like that:
$('.NextButton').click(function () {
dex.forms.form_ajax_submit(document.getElementsByName('submit_http:'),
function(res) {
alert('posting failed');
},
function(res) {
alert('posting success');
});
});
But looks like document.getElementsByName is not returning the same result
as the submit button 'this'
How can I solve this issue?

The only actual mistake you made was using the function document.getElementsByName, because it returns an array of elements (as indicated by the plural). What you need is a single element.
Either access the first element of the array by using:
document.getElementsByName('submit_http:')[0]
or use the already recommended and more precise function:
document.getElementById('submit_http:')

document.getElementsByName('submit_http:') will return an array of elements that have that name. If you want to get your submit button, you want to use document.getElementsByName('submit_http:')[0].

While Anthony Grist is correct, in your case, since you already have an id for your input, you could do document.getElementById('submit_http:') (which returns a single element).

generally, we use a "self" variable for this. Before the submit, do that :
var self = this;
then use "self" into your callback

Related

PhantomJS: Cannot get Element

I have a PhantomJS script based on this one: http://code-epicenter.com/how-to-login-amazon-using-phantomjs-working-example/
It works very well, I can, for example, populate the login page and click on the "submit" button with code that looks like this:
function(){
console.log('Step 3');
page.evaluate(function() {
document.getElementById("username-pulldown").value="username";
document.getElementById("password-pulldown").value="password";
document.getElementById("login-pulldown" ).click();
});
},
Later-on, however, I try to execute this:
function(){
console.log('Step 7');
page.evaluate(function(){
document.getElementById("content_text").value += "SomeTextIWannaAdd";
//console.log(document.documentElement.innerHTML);
document.getElementByName("button");
});
},
I get this error message:
Step 7
ERROR: TypeError: undefined is not a function (evaluating
'document.getElementByName("button")')
TRACE:
-> undefined: 3
-> : 8
phantomjs://code/EditWiki.js:48 in onError
The html element i want to get looks as follows:
<button name="button" type="submit" class="button -highlight -with-icon icon-checkmark">Save</button>
The rest of the innerHTML: https://pastebin.com/j5cCDxEU
The document object doesn't have a getElementByName method, only has getElementsByName method (plural).
Use querySelector instead to query by attribute name:
document.querySelector('[name="button"]')
To query all button tags you can use getElementsByTagName:
document.getElementsByTagName('button')
To query all buttons with a class name use getElementsByClassName:
document.getElementsByClassName('.button')
To emit a click event you can do:
document.querySelector('[name="button"]').click()
If using selectors that return an array such as getElementsByTagName or getElementsByClassName then you can grab the first one and then click:
document.getElementsByClassName('.button')[0].click()
Getting element by name is much error prone as there may be multiple 'buttons' try selecting the element by either xpath or id/class name.

Javascript: Run a global function in the scope of a ajax response only

I´d like to run a global defined js function in the scope of the return from a ajax request. I try to simplify my code, imagine a page with:
<div id="1" class="a">
and a function called on doc ready
function doStuff() {
$('.a').each(...whatever..)
}
and an AJAX call on doc ready returning again an element
<div id="2" class="a">
In the case of success i´d like to run the function "doStuff", but i only want the element from the ajax response to be affected.
I expected that $.proxy would do the job but i don´t get it working (in the case of success from $.ajax):
success: function(data)
{
var context = jQuery(data);
$(jQuery.proxy(function() {
doStuff();
}, context));
}
But the element with id 1 is always affected, too.
Update:
The id´s are just for exsample. I do not have no valid unique id, that is why i want to narrow the scope. It loke setting the second context parameter globally (http://api.jquery.com/jQuery/#jQuery-selector-context) and no need to touch very js function using a selector..
If it is not possible, it would help me , too.
It's affecting both the div's as you are selecting the element using the "class" selector.
you should be selecting the element using the id like below.
function doStuff() {
$('#2').each(...whatever..)
}
This should work
You can mark new elements with a data attribute like <div id="1" class="a" data-isNew="true">, and tell the function to only to affect the ones with the desired attribute. For example:
function doStuff() {
$('.a[isNew=true]').each(function() {
var elem = $(this);
elem.removeData('isNew');
...
});
}

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

I'm teaching myself AJAX to AJAXify my site. In my template, I have the following JS code to get some JSON data from a view then append the data to a div.
function filter(type) {
$.getJSON(
'/activity_stream/global-activity-stream/',
{xhr: "true", filter: type},
function(data) {
$('.mainContent').children().remove();
$(data).appendTo('.mainContent');
});
}
$(".btn").click(function () {
filter("recent");
});
}
I think my view is returning proper JSON but now data is not being added to the .mainContent div.
It gives this error:
Uncaught TypeError: Cannot read property 'ownerDocument' of undefined.
Make sure you're passing a selector to jQuery, not some form of data:
$( '.my-selector' )
not:
$( [ 'my-data' ] )
I had a similar issue.
I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.
The same issue came up for me inside of $elms.each().
Because:
the function you pass to .each(Function) exposes (at least) two arguments; the first being the index and the second being the element in the current element in the list, and
because other similar looping methods give current the element in the array before the index
you may be tempted to do this:
$elms.each((item) => $(item).addClass('wrong'));
When this is what you need:
$elms.each((index, item) => $(item).addClass('wrong'));
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
If you use ES6 anon functions, it will conflict with $(this)
This works:
$('.dna-list').on('click', '.card', function(e) {
console.log($(this));
});
This doesn't work:
$('.dna-list').on('click', '.card', (e) => {
console.log($(this));
});
In my case, this error happened because my HTML had a trailing linebreak.
var myHtml = '<p>\
This should work.\
But does not.\
</p>\
';
jQuery('.something').append(myHtml); // this causes the error
To avoid the error, you just need to trim the HTML.
jQuery('.something').append(jQuery.trim(myHtml)); // this works

Cannot access variable inside jQuery.each

Here is a function that is in one of my objects:
updatePorts: function(nodeKey, portOptions, portArrays) {
var showing_ports = false;
$('#ports li').removeClass('active').hide();
$('#ports .tab-pane').removeClass('active in');
$.each(portOptions, function(side, options) {
if (options.editable) {
$('#ports [href="#'+side+'"]').closest('li').show();
if (!showing_ports) {
$('#ports [href="#'+side+'"]').closest('li').addClass('active');
$('#ports #'+side).addClass('active in');
}
$.each(portArrays[side], function(i,port) {
//do stuff
}
showing_ports = true;
}
})
}
My problem is that outside of the $.each loop I can access the portArrays variable that is passed as an argument into the function. However, I cannot access that same variable inside of the $.each loop.
Am I doing something wrong? How can I gain access to that variable inside the loop?
UPDATE: Added code where portArrays is actually being accessed
portArrays is defined where you're using it, but you're using the wrong index. The side variable is an index into portOptions, not portArrays.
What index should it have? If these two arrays run in parallel with the same index values, that's generally a bad idea - it's better to use a single array of objects - and at least needs to be documented in your code.
BTW, what is the exact error message in the JS console? If my guess isn't right, the error message would give a clue.
I had the problem described in the subject, however it seems the asker had a problem elsewhere in his code. My code is similar to the below and I could not access what I wanted from this. The first log would work, but the log inside the each loop was undefined. I realise now that this is reassigned when using jquery each - http://api.jquery.com/each/
List.prototype.updateList = function(search) {
console.log(this.id);
$.each(this.data, function(item, tags) {
console.log(this.id); //undefined
};
}
I've changed to using for .. in to iterate my this.data object and it's working. Hope this may help someone.
List.prototype.updateList = function(search) {
console.log(this.id);
for(var key in this.data){
console.log(this.id); //hooray
}
}

JQuery - Javascript - .hasData() not working for me

I am trying to check if an object with class sourceFocus has data in it. However when I check it, it does not have data when it should. What am I doing wrong here?
$('.source').click(function() {
$('.source').removeClass('sourceFocus');
$(this).addClass('sourceFocus');
$(this).data('source_selected', true);
console.log($.hasData(this));
console.log(this);
});
$('.target').click(function() {
$('.target').removeClass('targetFocus');
$(this).addClass('targetFocus');
$(this).data('target_used', true);
//$('.sourceFocus').data('source_used', true);
console.log($.hasData('.sourceFocus'));
if($.hasData('.sourceFocus')){
console.log("has data worked");
check_for_duplicates();
}
I don't think the .hasData() method accepts selectors in your case .sourceFocus, try selecting .sourcefocus as an element and then passing that to the .hasData() function.
try something like...
console.log($.hasData($('.sourceFocus:first')));
$.hasData() checks against a DOM Element
you have to get it out of the jQuery object, either using array notation or the .get() method (not to be confused with the $.get() ajax method)
console.log($.hasData($('.sourceFocus')[0]));
If you trying to read the HTML between the tags for which you are using .sourceFocus class then do this in your if statement:
$.hasData($('.sourceFocus').html())

Categories