How can I parse a HTML attribute value out of XMLHttpRequest.responseText? - javascript

The below JS function does Ajax request and retrieves HTML in obj.responseText. My issue is that I need to extract the value of id inside the span into notify_id var. I just don't know how to get that done.
This is the HTML to lookup:
HTML:
<span id="1034"></span><img src="./images/icons/post_icon.png">
JS:
function func()
{
obj = new XMLHttpRequest();
obj.onreadystatechange = function() {
if(obj.readyState == 4)
jQuery.jGrowl(obj.responseText, {
sticky:true,
close: function(e,m) {
notifyClosed(notify_id);
}
});
}
obj.open("GET", "notifications.php?n=1", true);
obj.send(null);
}

Since you're already using jQuery:
var responseText = '<span id="1034"></span><img src="./images/icons/post_icon.png">';
var spanId = $('<div>').html(responseText).find('span').attr('id');
alert(spanId); // 1034
The whole function in turn can also be rewritten as follows:
$.get('notifications.php?n=1', function(responseText) {
// Your code here.
});
See also the jQuery tutorials.

Related

html() function with variables

I'm attempting to inject some html code with variables in it into a JQM UL Listview. The problem I am running into is it seems the variables are throwing off the code because when I remove them, it injects the HTML perfectly.
Here is the snippet:
$(document).on("pageinit", "#vendorMessages", function() {
var listView = "";
pubnub.subscribe(
{
channelGroup: getChannelGroup()
},
function (status, response) {
alert("test");
console.log(status, response);
}
);
pubnub.channelGroups.listChannels(
{
channelGroup: getChannelGroup()
},
function (status, response) {
response.channels.forEach( function (channel) {
var channelFormatted = String(channel).split("_");
var channelMember = channelFormatted[1];
var temp = "<li onClick='loadChannel("+channel+")'>"+channelMember+"</li>";
var temp = String(temp);
listView = listView.concat(temp);
})
alert(listView);
}
)
var elem = $("#channels");
elem.html(elem.text(listView));
$("#channels").listview("refresh");
})
The alert(listView) returns the correct string format but the code still will not get added to the <ul>. I've tried a few suggested things, even switching back to javascript innerHTML but no avail. Any thoughts?
Change
elem.html(elem.text(listView));
to
elem.html(listView);
elem.text cannot handle html..

Generating JQuery from C# (MVC 5 - Razor)

I have generated some jQuery from C#/Razor. Before writing the code to generate the jQuery I wrote a static version of the jQuery that I needed to mimic with the code I would be generating from the Razor (C#) syntax.
Mission accomplished. After writing the Razor code using C# code blacks I was able to generate a block of jQuery that was verbatim exactly the same as the working static version of the jQuery.
PROBLEM: WHen I load the page the jQUery doesn't work, but when I view source. the jQuery is perfect???
Is there a reason that jQuery generated by Razor would not work even though the JS in generates is perfectly formatted jQuery?
I can provide code samples but the reality is that my HTML page that is generated is perfect. But only the jQuery in the block I generated from Razor is not working???
static jQuery:
<script>
$('#centerview').on('click', function () {
var $$ = $(this)
if (!$$.is('.imageChecked')) {
$$.addClass('imageChecked');
$('#2').prop('checked', true);
} else {
$$.removeClass('imageChecked');
$('#2').prop('checked', false);
}
});
$('#balconyview').on('click', function () {
var $$ = $(this)
if (!$$.is('.imageChecked')) {
$$.addClass('imageChecked');
$('#3').prop('checked', true);
} else {
$$.removeClass('imageChecked');
$('#3').prop('checked', false);
}
});
</script>
Razor code that generates jQuery
#{
var jqCounter = 1;
}
#foreach (var img in Model.Render.Images)
{
var imgName = img.Name.Replace(" ", string.Empty);
#:$('##imgName').on('click', function () {
#:var $$ = $(this)
#:if (!$$.is('.imageChecked')) {
#:$$.addClass('imageChecked');
#:$('##jqCounter').prop('checked', true);
#:} else {
#:$$.removeClass('imageChecked');
#:$('##jqCounter').prop('checked', false);
#:});
jqCounter++;
}
HTML Copied directly from pages final output
<script>
$('#straightonviewz').on('click', function () {
var $$ = $(this)
if (!$$.is('.imageChecked')) {
$$.addClass('imageChecked');
$('#1').prop('checked', true);
} else {
$$.removeClass('imageChecked');
$('#1').prop('checked', false);
});
$('#centerview').on('click', function () {
var $$ = $(this)
if (!$$.is('.imageChecked')) {
$$.addClass('imageChecked');
$('#2').prop('checked', true);
} else {
$$.removeClass('imageChecked');
$('#2').prop('checked', false);
});
$('#balconyview').on('click', function () {
var $$ = $(this)
if (!$$.is('.imageChecked')) {
$$.addClass('imageChecked');
$('#3').prop('checked', true);
} else {
$$.removeClass('imageChecked');
$('#3').prop('checked', false);
});
</script>
It's perfect? is there a reason why code generated from C# would not work? Is it a server/Compile time thing? I have never tried to generate JavaScript from C#/Razor code before??
I do get an error on the HTML page right before the line
$('#balconyview').on('click', function () {
There's no reason why javascript defined through razor should not work on a browser. The only reason is syntax errors which exactly your case...
First, You've got a low unclosed parenthesis and curly brackets
Then, You've got undefined tokens here...
else {
$$.removeClass('imageChecked');
$('#1').prop('checked', false);
});
$$ is not defined in the else block...it is rather defined in the if block and it goes out of scope as soon as it hits the else block
Solution
To fix the sytanx errors you have introduced, close the parenthesis and curly brackets and make the $$ variable accessible to the else block...
#{
var jqCounter = 1;
}
#foreach (var img in Model.Render.Images)
{
var imgName = img.Name.Replace(" ", string.Empty);
#:$('##imgName').on('click', function () {
#:var $$ = $(this);
#:if (!$$.is('.imageChecked')) {
#:$$.addClass('imageChecked');
#:$('##jqCounter').prop('checked', true);
#:} else {
#:$$.removeClass('imageChecked');
#:$('##jqCounter').prop('checked', false);
#:}});
jqCounter++;
}
Update
Actually, I think I got a bit dizzy reading the code, the $$ variable is perfectly in scope....just close the else block

Passing parameters to a event listener function in javascript

Hello I have some code in which I take user input through in html and assign it to,two global variables
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
Which next show up in this addeventlistener function as parameters of the whowon function
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
The click event is meant to trigger the whowon function and pass in the parameters
function whowon(FirstScore, SecondScore, FirstTeam, SecondTeam) {
if (FirstScore > SecondScore) {
FirstTeam.win();
SecondTeam.lose();
} else if (FirstScore < SecondScore) {
SecondTeam.win();
} else {
FirstTeam.draw();
SecondTeam.draw();
}
}
However the values are null,as I get a cannot read properties of null error on this line
var spursscoref = document.getElementById("spursscore").value;
I am pretty sure the problem is coming from the addlistener function,any help would be appreciated
Well you could do something like this -
$( document ).ready(function() {
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
});
Wrap your code in $(document).ready(function(){}). This will ensure that all of your DOM elements are loaded prior to executing your Javascript code.
Try putting all of your code inside this
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
My guess is that your code is executed before the html actually finished loading, causing it to return null.

jquery.each not working after jquery.load

I use jQuery.load to load the HTML template. After this I'm trying to get HTML content from each loaded HTML element. The HTML is loading but I can't get the HTML content.
Here is the code:
var _InterfaceBuilder = function() {
var k45 = new _K45Kit;
var _this = this;
this.build = function(element) {
var error = false;
switch(element) {
case 'loginPanel':
$('#content').load('template/loginPanel.html', _this.localize(element));
break;
//sth else
}
// sth else
};
this.localize = function(section) {
$(".loginPanel.localString").each(function(index) {
console.log($(this).html());
});
//sth else
});
When I put
$(".loginPanel.localString").each(function(index) {
console.log($(this).html());
});
into the firebug console it works correctly. Can someone help me?
The 2nd parameter for $.load() must be a function that will be called once completion. You are not providing a function, but the result of calling _this.localize(element). So basically, the localize function is called before adding the listener, and since it returns undefined you have no handler.
Try with:
$('#content').load('template/loginPanel.html',
function(){
_this.localize(element);
});

Define a javascript variable under conditions with jquery

Like the title says, I would like to fill a variable up under some conditions
I thought I could do like that but no :
var content = $(function() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
});
So I thought that the javascript variable 'content' would be one of the jquery object representing an element in the dom. But it seems that 'content' is the function.
I guess you imagine what i want to do.. What is the syntax with JQuery ?
Thank you
$(function() { }) is short-code for the DOMReady event. You need to explicitly define a function, and then assign the return value to your variable.
For example:
function getObj()
{
if($('#content').length)
{
return $('#content');
}
if($('#content_no_decoration').length)
{
return $('#contenu_no_decoration');
}
if($('#full_content').length)
{
return $('#full_content');
}
if($('#full_content_no_decoration').length)
{
return $('#full_content_no_decoration');
}
}
You can then assign the value as :
var content = getObj();
You will need to call the assignment when the DOM is ready though, otherwise the selectors will not trigger as expected. For example:
$(function() {
var content = getObj();
});
You are only declaring the function, so content contains a pointer to the function.
Execute it and you are fine:
var content = function() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
}();
But you don't really need a function here. If the script tag is at the bottom of the page (right before the closing </body>-tag), or the assignment is within a load handler you could use:
var content = $('#content').length
? $('#content')
: $('#content_no_decoration').length
? $('#content_no_decoration')
: $('#full_content').length
? $('#full_content')
: $('#full_content_no_decoration').length
? $('#full_content_no_decoration')
: undefined;
Or use jQuery to your advantage and keep things really short:
var content =
$('#content,#content_no_decoration,#full_content,#full_content_no_decoration')
.get(0);
// if none of the elements exist, content will be undefined, otherwise
// it will contain [a JQuery Object of] the first existing element
why you don't do like that ?
function thatsAGoodName() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
}
var content = thatsAGoodName();
The function
$(function() {
// DOM safe to use do stuff
})
Is shorthand for the document ready event. This tells you the coder that the dom is safe to use.
You would not really return anything from this event.
content is an object because you're setting it to a object here:
var content = $(function() {
What you probably intended was:
var content;
if ($('#content').length) {
content = $('#content');
}
if ($('#content_no_decoration').length) {
content = $('#contenu_no_decoration'); // Is #contenu a typo???
}
if ($('#full_content').length) {
content = $('#full_content');
}
if ($('#full_content_no_decoration').length) {
content = $('#full_content_no_decoration');
}
Note, that this will have a reference to an element now. If you want the actual content you'll need to pull it out with something like html() or val().
You are using the shorthand for the jQuery ready event ($(function() {. What I believe you want is a self invoking function:
// remove the call to jQuery
var content = (function() {
if ($('#content').length) {
return $('#content');
}
// ... more
})(); // invoke the function, which should return a jQuery object
You may need to wrap this in a document.ready, depending on where your script is executed.
Rearrange it a little bit and it should work:
$(function () {
var content = (function() {
var regularContent = $('#content');
if (regularContent.length !== 0) {
return regularContent;
}
var contentNoDecoration = $('#content_no_decoration');
if (contentNoDecoration.length !== 0) {
return contentNoDecoration;
}
var fullContent = $('#full_content');
if (fullContent.length !== 0) {
return fullContent;
}
var fullContentNoDecoration = $('#full_content_no_decoration');
if (fullContentNoDecoration.length !== 0) {
return fullContentNoDecoration;
}
}());
});
This code is basically saying once the DOM is ready (the $(function () { ... }); part), run this anonymous function (the (function () { ... }()); part) and assign its return value to content.
Edit: Also, you're losing efficiency by running each of your selectors twice instead of just once.
It's true that content is the function, but you can use that function. Like:
var result = content();
Edit:
Remove the $() around var content = $({/* code */}) and it works.

Categories

Resources