How to toggleClass with SignalR hub.server? - javascript

I am currently learning SignalR with .Net MVC and following a tutorial to work on a simple app. Right now it is working alright, but I am having trouble understanding some part and also if possible, want to sort of enhance it.
Plane Seats Tutorial link
Right now the app is working as when a user clicks on a seat, it reserves it. And there is no going back. I want to implement like a toggle, where if the user wants to change seat, he gets to unreserve his selected seat, and then be free to reserve another one. I am not being able to do it with myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));. Whenever I click on a seat, it gives me this error in the Dev tools
Uncaught: Converting circular structure to JSON
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
$(function() {
//// Start the hub
window.hubReady = $.connection.hub.start();
});
$.connection.hub.start().done(function() {
// Call the server side function AFTER the connection has been started
myHub.server.createUser();
//invoke for the user data
myHub.server.populateSeatData();
});
// Seat selection
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('Sorry, this seat has been already reserved');
} else {
//$(this).toggleClass(settings.selectingSeatCss);
//myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));
myHub.server.selectSeat(userId, $(this)[0].innerText);
}
});
// Client method to broadcast the message
myHub.client.createUser = function(message) {
userId = message;
};
//get seats data
myHub.client.populateSeatData = function(message) {
var parsedSeatsData = JSON.parse(message);
$('li.seat').removeClass(settings.selectedSeatCss);
$.each(parsedSeatsData, function(index, value) {
$("a:contains('" + value.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
});
};
// Client method to broadcast the message as user selected the seat
myHub.client.selectSeat = function(message) {
var parsedSeatData = JSON.parse(message);
$("a:contains('" + parsedSeatData.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
};
And can anyone please briefly explain what is str.push doing in this block of code? What is it exactly pushing into the array?
var init = function(reservedSeat) {
var str = [],
seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 2; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' + 'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' + '<a title="' + seatNo + '">' + seatNo + '</a>' + '</li>');
}
}
$('#place').html(str.join(''));
};

I had to use a toggleSeat() function instead of just using toggleClass.
public void toggleSeat(int userId, int seatNumber)
{
PlaneSeatArrangment mySeat = allSeats.Where(s => s.SeatNumber == seatNumber).FirstOrDefault();
var retunData = JsonConvert.SerializeObject(mySeat);
if (mySeat != null && userId == mySeat.UserId)
..............
}

Related

jQuery to emulate iPhone password input changes textbox to disabled in a Visual Studio web application

I am working on a web application in Visual Studio using visual basic and master pages. I have 10 textbox fields on a child page where I would like to emulate the iPhone password entry (ie. show the character entered for a short period of time then change that character to a bullet). This is the definition of one of the text box controls:
<asp:TextBox ID="txtMID01" runat="server" Width="200" MaxLength="9"></asp:TextBox>
At the bottom of the page where the above control is defined, I have the following:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="lib/jQuery.dPassword.js"></script>
<script type="text/javascript">
$(function () {
var textbox01 = $("[id$=txtMID01]");
alert(textbox01.attr("id"));
$("[id$=txtMID01]").dPassword()
});
</script>
When the page loads, the alert displays MainContent_txtMID01 which is the ID of the control preceeded with the name of the content place holder.
The following is the contents of lib/jQuery.dPassword.js (which I found on the internet):
(function ($) {
$.fn.dPassword = function (options) {
var defaults = {
interval: 200,
duration: 3000,
replacement: '%u25CF',
// prefix: 'password_',
prefix: 'MainContent_',
debug: false
}
var opts = $.extend(defaults, options);
var checker = new Array();
var timer = new Array();
$(this).each(function () {
if (opts.debug) console.log('init [' + $(this).attr('id') + ']');
// get original password tag values
var name = $(this).attr('name');
var id = $(this).attr('id');
var cssclass = $(this).attr('class');
var style = $(this).attr('style');
var size = $(this).attr('size');
var maxlength = $(this).attr('maxlength');
var disabled = $(this).attr('disabled');
var tabindex = $(this).attr('tabindex');
var accesskey = $(this).attr('accesskey');
var value = $(this).attr('value');
// set timers
checker.push(id);
timer.push(id);
// hide field
$(this).hide();
// add debug span
if (opts.debug) {
$(this).after('<span id="debug_' + opts.prefix + name + '" style="color: #f00;"></span>');
}
// add new text field
$(this).after(' <input name="' + (opts.prefix + name) + '" ' +
'id="' + (opts.prefix + id) + '" ' +
'type="text" ' +
'value="' + value + '" ' +
(cssclass != '' ? 'class="' + cssclass + '"' : '') +
(style != '' ? 'style="' + style + '"' : '') +
(size != '' ? 'size="' + size + '"' : '') +
(maxlength != -1 ? 'maxlength="' + maxlength + '"' : '') +
// (disabled != '' ? 'disabled="' + disabled + '"' : '') +
(tabindex != '' ? 'tabindex="' + tabindex + '"' : '') +
(accesskey != undefined ? 'accesskey="' + accesskey + '"' : '') +
'autocomplete="off" />');
// change label
$('label[for=' + id + ']').attr('for', opts.prefix + id);
// disable tabindex
$(this).attr('tabindex', '');
// disable accesskey
$(this).attr('accesskey', '');
// bind event
$('#' + opts.prefix + id).bind('focus', function (event) {
if (opts.debug) console.log('event: focus [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
checker[getId($(this).attr('id'))] = setTimeout("check('" + getId($(this).attr('id')) + "', '')", opts.interval);
});
$('#' + opts.prefix + id).bind('blur', function (event) {
if (opts.debug) console.log('event: blur [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
});
setTimeout("check('" + id + "', '', true);", opts.interval);
});
getId = function (id) {
var pattern = opts.prefix + '(.*)';
var regex = new RegExp(pattern);
regex.exec(id);
id = RegExp.$1;
return id;
}
setPassword = function (id, str) {
if (opts.debug) console.log('setPassword: [' + id + ']');
var tmp = '';
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == unescape(opts.replacement)) {
tmp = tmp + $('#' + id).val().charAt(i);
}
else {
tmp = tmp + str.charAt(i);
}
}
$('#' + id).val(tmp);
}
check = function (id, oldValue, initialCall) {
if (opts.debug) console.log('check: [' + id + ']');
var bullets = $('#' + opts.prefix + id).val();
if (oldValue != bullets) {
setPassword(id, bullets);
if (bullets.length > 1) {
var tmp = '';
for (i = 0; i < bullets.length - 1; i++) {
tmp = tmp + unescape(opts.replacement);
}
tmp = tmp + bullets.charAt(bullets.length - 1);
$('#' + opts.prefix + id).val(tmp);
}
else {
}
clearTimeout(timer[id]);
timer[id] = setTimeout("convertLastChar('" + id + "')", opts.duration);
}
if (opts.debug) {
$('#debug_' + opts.prefix + id).text($('#' + id).val());
}
if (!initialCall) {
checker[id] = setTimeout("check('" + id + "', '" + $('#' + opts.prefix + id).val() + "', false)", opts.interval);
}
}
convertLastChar = function (id) {
if ($('#' + opts.prefix + id).val() != '') {
var tmp = '';
for (i = 0; i < $('#' + opts.prefix + id).val().length; i++) {
tmp = tmp + unescape(opts.replacement);
}
$('#' + opts.prefix + id).val(tmp);
}
}
};
})(jQuery);
When I execute my code, the code behind populates the value of the textbox with "123456789" and when the page gets rendered, all the characters have been changed to bullets, which is correct. The problem I am having is that the textbox has been disabled so I can not edit the data in the textbox.
I removed (by commenting out) the references to the disabled attribute but the control still gets rendered as disabled.
As a side note, the code that I found on the internet was originally designed to work with a textbox with a type of password but when I set the TextMode to password, not only does the control get rendered as disabled, but the field gets rendered with no value so I left the TextMode as SingleLine.
Any suggestions or assistance is greatly appreciated.
Thanks!
As far as I know, it is not possible to have it so that while you type a password, the last letter is visible for a second and then turns into a bullet or star.
However what you can do is as the user types in password, with a delay of lets say 500ms store the string the user has typed in so far into some variable and replace the content of the password field or the text field with stars or black bullets. This will give you what you are looking for.

How to get rid of many IFs and make a system to differ elements?

In this piece of code you can see a JSON request that fetches some data. I need some help to check certain opportunities of minimizing the code and getting iterations with FOR instead of many IFs. Also, it would be nice if you advise anything on the differentiation system (how to make elements differ from each other)
<script type="text/javascript">
function deleteRow0() {
$('p.row0').remove();
};
function deleteRow1() {
$('p.row1').remove();
};
function deleteRow2() {
$('p.row2').remove();
};
function deleteRow3() {
$('p.row3').remove();
};
function deleteRow4() {
$('p.row4').remove();
};
</script>
<script type="text/javascript">
function hello2() {
//GETTING JSON INFO
$.getJSON("https://rawgit.com/Varinetz/e6cbadec972e76a340c41a65fcc2a6b3/raw/90191826a3bac2ff0761040ed1d95c59f14eaf26/frontend_test_table.json", function(json) {
$('#table-cars').css("display", "grid");
for (let counter = 0; counter < json.length; counter++) {
$('#table-cars').append("<p class='row" + counter +" main-text'>" + json[counter].title + "<br/>" + "<span class='sub-text'>" + json[counter].description + "</span>" + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].year + "</p>"
+ "<p id='color" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].color + "</p>"
+ "<p id='status" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].status + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].price + " руб." + "</p>"
+ "<p class='row" + counter +" main-text'>" + "<button class='delete' onclick='deleteRow" + [counter] + "()'>Удалить</button>" + "</p>");
// COLOR TEXT REPLACEMENT
if ($('p#color0').text("red")){
$('p#color0').text("").append("<img src='red.png'>");
}
if ($('p#color1').text("white")) {
$('p#color1').text("").append("<img src='white.png'>");
}
if ($('p#color2').text("black")) {
$('p#color2').text("").append("<img src='black.png'>");
}
if ($('p#color3').text("green")) {
$('p#color3').text("").append("<img src='green.png'>");
}
if ($('p#color4').text("grey")) {
$('p#color4').text("").append("<img src='grey.png'>");
}
// STATUS TEXT REPLACEMENT
if ($('p#status0').text("pednding")) {
$('p#status0').text("").append("Ожидается");
}
if ($('p#status1').text("out_of_stock")) {
$('p#status1').text("").append("Нет в наличии");
}
if ($('p#status2').text("in_stock")) {
$('p#status2').text("").append("В наличии");
}
if ($('p#status3').text("out_of_stock")) {
$('p#status3').text("").append("Нет в наличии");
}
if ($('p#status4').text("in_stock")) {
$('p#status4').text("").append("В наличии");
}
}
});
}
</script>
I expect this to be something like:
1) Iteration: For each p.row(i) {
compare it to many color (json.color)};
2) Any suggestion on differentiation system (i.e. changes in the FOR section, so it gives something easier to work with, not just simple p.row(n)). Of course, if it is possible.
I'm not going to rewrite the entire script, but in principle it would be something like this:
for (i = 0; i < 5; i++) {
var colors = ["red", "white", "black", "green", "grey"];
if ($('p#color' + i).text() == colors[i]){
$('p#color' + i).text("").append("<img src='" + colors[i] + ".png'>");
}
}
#Evik Ghazarian has a quality solution for the Text Translation portion of your script. Since this is the accepted answer, he allowed me to copy his solution so that the answers would be together:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}
Dynamic Iteration Counters
#Barmar mentioned in the comments below that the for loops that set a max iteration via i < 5 should actually be rewritten dynamically. I'll leave it to the OP to decide the best way to do this, but a good example might be something like i < json.length as used in the OP's original for loop.
First of all your code won't work because you are setting the text rather than comparing it. Second, you don't need to compare: just set the img src to text. Like below:
REMEMBER THIS IS FOR COLOR TEXT REPLACEMENT PART OF YOUR QUESTION
for (let i = 0; i < 5 , i ++){
let color = $("p#color"+i).text() + ".png";
$("p#color"+i).text("").append("<img src=" + color + ">");
}
FOR TEXT TRANSLATION YOU CAN USE:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}

How to send a javascript array to php [duplicate]

This question already has answers here:
How to pass data from Javascript to PHP and vice versa? [duplicate]
(7 answers)
Closed 4 years ago.
I have an array named "seat" in my javascript file.It is used to store the seat numbers when a user clicks on a seat in a theater layout.In my function,I've used a window alert to show the user his selected seats,and when he clicks OK button,I want to send these booked seats(values in my array) to a php file named "confirm".
Here is the javascript function.
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved!');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
$_POST('confirm.php', {seat: seat})
})
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
And this is my php code.
$seat = "";
if(isset($_POST['seat']))
{
$seat = $_POST["seat"];
print_r($seat);
}
When this is executed I get the window alert,but the values stored in the array does not pass to the php file.Is there something wrong with this code?Please help!I'm stuck here!!!
$_POST isn't a built-in method, and jQuery doesn't provide a method like that either-- you can't just "set" the values into the $_POST array like this.
To post using jQuery, you would do something like the following, including a handler for data returning from the server (if you have any):
$.post("confirm.php", { seat: seat})
.done(function(data){
alert('Received data from server: ' + data);
});
You need to send the data to your PHP script, this does nothing in your JS code:
$_POST('confirm.php', {seat: seat})
use something like jQuery post method or vanilla JS XMLHttpRequest

javascript varible grow on loop

Hare is my current function
var listItems = $("#list_li").children();
var count = listItems.length;
var i;
for (i = 0; i <= count; i++) {
const the_i = i;
$("#news_" + the_i + " h2").click(function () {
$('#news_' + the_i + ' article').addClass('active');
$('#news_' + the_i + ' h2').addClass('active');
$('#news_' + the_i + ' img').addClass('active');
$('#news_' + the_i).addClass('active');
If is clicked.
$('#news_1 article').removeClass('active');
$('#news_1 h2').removeClass('active');
$('#news_1 img').removeClass('active');
$('#news_1').removeClass('active');
}
});
}
My code adds up styles to it on click, it works fine, how ever, I need to make it so it would know if its clicked or not, I am using loop, because its news feed and it can get more and more, so without the struggle automatically know what to align.
I need something like this
var autoIncresingVar.i = 0;
so when it comes to the 1st one on loop, it would set it to 1 and on click check with "if" its clicked or not.
Let me try to explain Note that I know its not real code
each(i > 5) {
var newEl_"i" = 0;
on first element click
if {newEL_1 == 0) {
addClasses
newEL_i = 1;
} else if)newEl_1 == 1) {
removeClasses
newEL_i = 0;
}
}
You can use .hasClass() function for check if the current node has the 'active' class. If yes, remove it. Else, add it.
Example :
$("#news_" + the_i + " h2").click(function () {
if (!$('#news_' + the_i).hasClass('active'))
{
$('#news_' + the_i + ' article').addClass('active');
$('#news_' + the_i + ' h2').addClass('active');
$('#news_' + the_i + ' img').addClass('active');
$('#news_' + the_i).addClass('active');
}
else
{
$('#news_1 article').removeClass('active');
$('#news_1 h2').removeClass('active');
$('#news_1 img').removeClass('active');
$('#news_1').removeClass('active');
}
});
One approach would be to use .data() to set a property at an object where value is toggled between 0 and 1 at each click event
$("#news_" + the_i + " h2").data("clicked", 0)
.on("click", function() {
if (!$(this).data().clicked) {
// do stuff with `$(this).data().clicked` : `0`
} else {
// do stuff with `$(this).data().clicked` : `1`
}
// set `$(this).data().clicked` to `1` or `0`
$(this).data().clicked = !$(this).data().clicked ? 1 : 0;
})
Use below code.
for (i = 0; i <= count; i++) {
const the_i = i;
$("#news_" + the_i + " h2").click(function () {
$('#news_' + the_i + ' article').toggleClass('active');
$('#news_' + the_i + ' h2').toggleClass('active');
$('#news_' + the_i + ' img').toggleClass('active');
$('#news_' + the_i).toggleClass('active');
}
});
}
you can use the add attribute function to add an on click event to each element
http://coursesweb.net/jquery/add-change-remove-attribute-jquery

HTML read javascript and put result into a div

I'm new to HTML/javascript and I want to make something that displays Last.FM current playing songs, into a div on html, which displays it in text, I have a code that sends the current song through a chat on www.irccloud.com, and I was wondering If you could change it so that It could get received and put into a DIV on a page, the code is below:
and var r is the completed code, so how would I do something in the div that picks up the source as the link above and then grabs var r from it? If so, how would I do it??
I have tried the following code here
Sorry if I do not make sense.
(function () {
var e = "DeviousRunner";
window.lfmRecentTrack = function (t) {
var n = (new Array).concat(t.recenttracks.track)[0];
var album, spurl;
if (n.album["#text"]) {
album = " (from " + n.album["#text"] + ")";
} else {
album = "";
}
try {
var spotify = new XMLHttpRequest();
spotify.open("GET", "https://ws.spotify.com/search/1/track.json?q=" + encodeURIComponent(n.artist["#text"] + " - " + n.name), false);
spotify.send();
var spotresp = JSON.parse(spotify.responseText);
if (spotresp["tracks"].length > 0) {
//var urisplit = spotresp["tracks"][0]["href"].split(":");
//spurl = " https://open.spotify.com/" + urisplit[1] + "/" + urisplit[2];
spurl = spotresp["tracks"][0]["href"];
} else {
console.log("spotify: couldn't get url");
spurl = "";
}
} catch(e) {
console.log("spotify: " + e.message);
spurl = "";
}
var r = "is listening to " + n.name + " by " + n.artist["#text"] + " " + album + " (" + spurl + ")";
}
var n = document.createElement("script");
n.setAttribute("type", "text/javascript");
n.setAttribute("src", "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + e + "&api_key=dd5fb083b94a7196cf696b9d7d11bc63&limit=1&format=json&callback=window.lfmRecentTrack");
document.body.appendChild(n)
})();
I updated your FIDDLE,
by moving this:
var element = document.getElementById("rss");
element.innerHTML = r;
inside the function...
hope this is useful for you

Categories

Resources