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
Related
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.
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)
..............
}
UPDATE:
I changed my script to this and it works. Way simpler and it works.
function myFunction(valor) {
var elementos = document.getElementsByClassName("inner");
var i;
for (i = 1; i < elementos.length+1; i++) {
document.getElementById("age"+i).style.visibility = "hidden";
}
document.getElementById("age"+valor).style.visibility = "visible";
}
I have this script:
function myFunction(valor) {
alert("Has seleccionado " + valor);
var elementos = document.getElementsByClassName("inner");
//alert ("Tienes " + elementos.length + " elementos.");
var i;
for (i = 1; i < elementos.length + 1; i++) {
var sty = document.getElementById("age" + i);
//alert("age"+i);
if (getComputedStyle(sty).getPropertyValue("visibility") == "hidden") {
document.getElementById("age" + valor).style.visibility = "visible";
} else {
document.getElementById("age" + i).style.visibility = "hidden";
}
}
}
That I control with a slider control. What I'm doing is hiding or showing some divs with depending of what I choose from the slider.
This is how I paint my data before trying to hide or shsow elements with the slider:
$(window).load(function() {
$.getJSON('http://xxxxx/xxxxx.json', function(data) {
var output = "<ul class='lista'><div class='outer'>";
for (var i in data.lbclassic) {
output += "<div style='visibility:hidden;' class='inner'id=" + "age" + data.lbclassic[i].ageinweeks + ">" + "<p>" + data.lbclassic[i].ageinweeks + "--" + data.lbclassic[i].cumul + "--" + data.lbclassic[i].perhh + "--" + data.lbclassic[i].perhd + "--" + data.lbclassic[i].eggweightinweek + "--" + data.lbclassic[i].eggmasscumul1 + "--" + data.lbclassic[i].eggmassinweek + "--" + data.lbclassic[i].eggmasscumul + "</p></div>";
}
output += "</div></ul>";
document.getElementById("placeholder").innerHTML = output;
});
});
This works great until one point - once I get to the last element (90 in this case), it won't show up.
Isn't it more easy to use the css "display:none;" feature for hidding your element.
.yourclass{
display:none;
}
just edit the class with js
Link to CSS
function myFunction(valor) {
var elementos = document.getElementsByClassName("inner");
var i;
for (i = 1; i < elementos.length+1; i++) {
document.getElementById("age"+i).style.visibility = "hidden";
}
document.getElementById("age"+valor).style.visibility = "visible";
}
My app is looking into a folder and then show all folders and html file inside it in a dropdown menu, and display any html files inside an iframe. I have a file called "highlighted.html" which I don't want to show in the dropdown menu, but if it is in the current directory I do want to show it automatically in an iframe.
This is my code to show what is in folder:
First function create a dropdown box loading dynamically folders or files (with html extension).
In second function: if click on an existing subfolder, then open that folder and look inside for html file(s) to open it in a iframe
function rendSelects($currentSelectItem, strPath) {
var currentSelectLevel = (null === $currentSelectItem ? -1 : parseInt($currentSelectItem.attr('data-selector-level'))),
nextOneSelectorHtml =
'<select ' +
'class="dropdown selectpicker" ' +
'name="dd" ' +
'data-selector-level="' + (currentSelectLevel + 1) + '" ' +
'data-path="' + strPath + '" ' +
'onchange="onFsSelectChange(this)"' +
'><option text selected> -- select an option -- </option>';
$('div.selectors-container select.dropdown').each(function (i, el) {
if (parseInt(el.getAttribute('data-selector-level')) > currentSelectLevel) {
el.parentNode.removeChild(el);
$(el).selectpicker('destroy');
}
});
if (fsStructure[strPath].subfolders.length > 0) {
for (var i = 0; i < fsStructure[strPath].subfolders.length; i++) {
nextOneSelectorHtml +=
'<option ' +
'class="subfolder-option" ' +
'data-subfolder="' + fsStructure[strPath].subfolders[i] + '" >' + fsStructure[strPath].subfolders[i] +
'</option>';
}
}
if (fsStructure[strPath].subshtmls.length > 0) {
for (var i = 0; i < fsStructure[strPath].subshtmls.length; i++) {
nextOneSelectorHtml +=
'<option ' +
'class="html-page-option" ' +
'data-html-page-name="' + fsStructure[strPath].subshtmls[i] + '">' + fsStructure[strPath].subshtmls[i] +
'</option>';
}
}
nextOneSelectorHtml += '</select>';
$('div.selectors-container').append(nextOneSelectorHtml);
$('div.selectors-container').trigger('dropdownadded.mh');
}
function onFsSelectChange(el) {
var currentSelectorPath = el.getAttribute('data-path'),
selectedOption = el.options[el.selectedIndex];
if (selectedOption.classList.contains('subfolder-option')) {
loadFolderStructure(currentSelectorPath + '/' + selectedOption.getAttribute('data-subfolder'), $(el))
}
if (selectedOption.classList.contains('html-page-option')) {
playSwf(currentSelectorPath + '/' + selectedOption.getAttribute('data-html-page-name'));
}
}
I have provided a working demo at http://tdhtestserver.herobo.com/.
SOLVED
Well. If highlighted.html does exist in folder, no select constitution. Let's display an iFrame with src=highlighted.html IIUC. Am I OK ?
First function create a dropdown boxes where it load dynamically folders or files with html extension.
Ok, so let's check if highlighted.html is here.
function rendSelects($currentSelectItem, strPath) {
//here : (begin of change)
if(strPath.indexOf("hightlighted")>=0) {
$("#myiFrame").attr('src', /path/to/highlighted)
}
// enfd of change. The continue as :
var currentSelectLevel = (null === $currentSelectItem ? -1 : parseInt($currentSelectItem.attr('data-selector-level'))),
nextOneSelectorHtml =....
ACTUALLY, the matter is to choose between : 1. $(myframeid).attr(src...) AND 2. $('div.selectors-container').append(nextOneSelectorHtml); /// you have to "render" 1 or 2, depending on finding highlighted in or not.
function rendSelects($currentSelectItem, strPath) {
//1of3 // let's add a boolean
var is_highlighted_here = false;
var highlighted_path="";
//done.
var currentSelectLevel = (null === $currentSelectItem ? -1 : parseInt($currentSelectItem.attr('data-selector-level'))),
nextOneSelectorHtml =
'<select ' +
'class="dropdown selectpicker" ' +
'name="dd" ' +
'data-selector-level="' + (currentSelectLevel + 1) + '" ' +
'data-path="' + strPath + '" ' +
'onchange="onFsSelectChange(this)"' +
'><option text selected> -- select an option -- </option>';
$('div.selectors-container select.dropdown').each(function (i, el) {
if (parseInt(el.getAttribute('data-selector-level')) > currentSelectLevel) {
el.parentNode.removeChild(el);
$(el).selectpicker('destroy');
}
});
if (fsStructure[strPath].subfolders.length > 0) {
for (var i = 0; i < fsStructure[strPath].subfolders.length; i++) {
nextOneSelectorHtml +=
'<option ' +
'class="subfolder-option" ' +
'data-subfolder="' + fsStructure[strPath].subfolders[i] + '" >' + fsStructure[strPath].subfolders[i] +
'</option>';
}
}
if (fsStructure[strPath].subshtmls.length > 0) {
for (var i = 0; i < fsStructure[strPath].subshtmls.length; i++) {
// 2of3 // oh !! look at here :
if( fsStructure[strPath].subshtmls[i].indexOf("highlighted")>=0 )
{
s_highlighted_here=true;
highlighted_path = fsStructure[strPath].subshtmls[i];
}
//done. scroll to bottom.
nextOneSelectorHtml +=
'<option ' +
'class="html-page-option" ' +
'data-html-page-name="' + fsStructure[strPath].subshtmls[i] + '">' + fsStructure[strPath].subshtmls[i] +
'</option>';
}
}
nextOneSelectorHtml += '</select>';
// 3of3 // here finally
if(is_highlighted_here) {
$("#myiFrame").attr('src', highlighted_path);
}
else {
$('div.selectors-container').append(nextOneSelectorHtml);
$('div.selectors-container').trigger('dropdownadded.mh');
}
}//function end
Well, if i display only changed :
- at the very function start :
//1of3
var is_highlighted_here = false;
var highlighted_path="";
when parsing the folder struct :
// 2of3 // oh !! look at here :
if( fsStructure[strPath].subshtmls[i].indexOf("highlighted")>=0 )
{
s_highlighted_here=true;
highlighted_path = fsStructure[strPath].subshtmls[i];
}
And finally, when rendering :
// 3of3
if(is_highlighted_here) {
$("#myiFrame").attr('src', highlighted_path);
}
else {
$('div.selectors-container').append(nextOneSelectorHtml);
$('div.selectors-container').trigger('dropdownadded.mh');
}
I answer on my question because some of you haven't understood my issue or they don't know how to do it. So I found that was so easy and all i've done was only one line of code.
high( currentSelectorPath + '/'+selectedOption.getAttribute('data-subfolder')+'/highlighted.html');
This line was changed everything, where high is a new iframe
function onFsSelectChange( el ) {
var
currentSelectorPath = el.getAttribute('data-path'),
selectedOption = el.options[el.selectedIndex];
if ( selectedOption.classList.contains('subfolder-option') ) {
loadFolderStructure( currentSelectorPath + '/' + selectedOption.getAttribute('data-subfolder'), $(el) )
high( currentSelectorPath + '/'+selectedOption.getAttribute('data-subfolder')+'/highlighted.html');
}
if ( selectedOption.classList.contains('html-page-option') ) {
playSwf( currentSelectorPath + '/' + selectedOption.getAttribute('data-html-page-name') );
}
}
The table cell updates correctly to "" (empty) in the changeScore function, but that same cell does not change at all in the editUpdate function when I try to place the new score in there. It just stays empty. Any ideas?
function changeScore(playerKey)
{
var table = document.getElementById("scoreTable");
players[playerKey].score = players[playerKey].oldScore;
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
document.getElementById('inputArea').innerHTML = '<font size="6">Did <b>' + players[playerKey].name + '</b> take <b>' + players[playerKey].bid + '</b> trick(s)?</font><br /><button value="Yes" id="yesButton" onclick="editUpdate(' + playerKey + ', \'yes\')">Yes</button>    <button value="No" id="noButton" onclick="editUpdate(' + playerKey + ', \'no\')">No</button>';
}
function editUpdate(thePlayerKey, answer)
{
var table = document.getElementById("scoreTable");
players[thePlayerKey].oldScore = players[thePlayerKey].score;
if (answer == "yes"){
**
}else{
**
}
table.rows[currentRound - 1].cells[thePlayerKey + 1].innerHTM = '<font color="' + players[thePlayerKey].font + '">' + players[thePlayerKey].score + '</font>';
document.getElementById('inputArea').innerHTML = '<button onclick="startRound()">Start Round</button>     <button onclick="edit()">Edit Scores</button>';
}
innerHTM should be innerHTML
This:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
Should be:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTML = '';
(Same for 2nd function)