Generating JQuery from C# (MVC 5 - Razor) - javascript

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

Related

Call function is not a function

$(function() {
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
$.club_settings();
$.club_settings = function() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
})(jQuery);
I got an error that is $.club_settings is not a function. How can i call $.club_settings in a if condition ?
You're defining the function after you call it. Switch around the code like so:
$(function() {
$.club_settings = function() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
$.club_settings();
})(jQuery);
JavaScript only hoists declarations, not initializations.
The reference above displays how variables are hoisted but it works for functions too.
$(function() {
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
club_settings();
function club_settings() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
})(jQuery);
The drawback would be is that it would be found in your $ variable which may lead to codes elsewhere breaking. But that could be another question.
Trying to resolve this by doing $.club_settings() = function club_settings() { ... will not work unless you reorder your codes as suggested by Mike

First jquery plugin

Im trying to make my first jquery plugin.. but actually i dont know what im doing wrong here.
$(document.ready(function()
{
var plugin = (function()
{
//this function is not accessible from the outside
function privateFunction()
{
}
//these functions are
return
{
alert1: function()
{
alert('Hallo');
},
alert2: function()
{
alert("hi");
}
}
})()
//but it is not working :/
plugin.alert1();
});
it is not executing one of the alerts. Am i putting some semicolons wrong?
i checked if all were closed
Javascript's automatic semicolon insertion will add a semicolon after return and undefined is returned.
Your code will look like
return;
{...
Replace
return
{
Should be
return {
You're also missing the ) after document in the first line of code.
Demo
$(document).ready(function() {
var plugin = (function() {
//this function is not accessible from the outside
function privateFunction() {
// Code Here
}
//these functions are
return {
alert1: function() {
alert('Hallo');
},
alert2: function() {
alert("hi");
}
};
}());
//but it is not working :/
plugin.alert1();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

repeating jquery function many times

I need to improve my jquery code where I repeat my function 6 times!!!
is there away to do a loop to shorten the code ?
(function( jQuery ){
jQuery.fn.vesta = function(imgN){
var imgPath = "http://localhost:8080/mhost/media/magentohost/vesta/vesta"
var currImg = imgPath + imgN + ".png";
var targetImg = jQuery('.img-browser img');
jQuery('.img-browser img').attr('src', currImg);
}
})( jQuery );
jQuery('.vesta1').on('click', function (e) {
jQuery('.vesta1').vesta(1);
});
jQuery('.vesta2').on('click', function (e) {
jQuery('.vesta2').vesta(2);
});
jQuery('.vesta3').on('click', function (e) {
jQuery('.vesta3').vesta(3);
});
jQuery('.vesta4').on('click', function (e) {
jQuery('.vesta4').vesta(4);
});
jQuery('.vesta5').on('click', function (e) {
jQuery('.vesta5').vesta(5);
});
jQuery('.vesta6').on('click', function (e) {
jQuery('.vesta6').vesta(6);
});
You can DRY this up by using a common class, and a data attribute to specify the parameter to send to your vesta function:
<div class="vesta" data-vesta="1">1</div>
<div class="vesta" data-vesta="2">2</div>
<div class="vesta" data-vesta="3">2</div>
Then there is no need to loop at all:
$('.vesta').on('click', function (e) {
$(this).vesta($(this).data('vesta'));
});
Use a common class and a data attribute
jQuery('.vesta').on('click', function (e) {
var elem = $(this);
elem.vesta(elem.data("ind"));
});
and the HTML
<div class="vesta vesta1" data-ind="1">
Just put it into a for loop, and take advantage of the dynamic nature of JavaScript:
for (var i = 1; i <= 6; i++) {
$('.vesta' + i).on('click', (function (index) {
return function (e) {
$('.vesta' + index).vesta(index);
};
})(i));
}
I suppose you need the this reference along with some hack kind of thing
$('[class*=vespa]').on('click', function(e){
$(this).vesta(+(this.className.match(/vespa(\d+)/)[1]))
});
Here, we capture elements which have a class that matches at least vespa and then we use some bit of regex to match the digits after vespa and + unary operator changes the String version of numbers into actual numbers.
It would be quite easy if you can alter the structure of the HTML.
You would give all elements the same class, say vesta. But you also give them an attribute, say data-number. For example, like this:
<div class="vesta" data-number="4"></div>
Then, your jQuery code would be as simple as:
$(document).on({
click: function() {
var $this = $(this),
number = +$this.data('number');
$this.vesta(number);
}
}, '.vesta');
Edit:
I was a bit lazy with explaining the code snippet that I have provided an hour ago, but I am modifying my post now in response to the comments.
This code snippet will allow you to apply listeners from '.vesta1' elements to '.vestaN'
[#Variable]
NumberOfClasses - is the positive integer after 'vesta'. Eg: vesta1 ,vesta2, vesta100 ... etc
var NumberOfClasses=6;
for(var i=1;i<=NumberOfClasses;i++){
var className = '.vesta'+(i+1);
jQuery(className ).on('click', function (e) {
$(this).vesta(i);
});
}

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);
});

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

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.

Categories

Resources