Is it possible to once press a random value on from the 25 given and change the value of the button next to it?
http://jsfiddle.net/ehcfqm22/
$(document).on('click', '#table input',function () {
var value1 = "";
value1 = $(this).val();
});
I'm able to get the current button value but that's about it.
You can change the value of the next button e.g. adding
$(this).parent("td").next("td").find("input").val(value1);
to your function.
I've added it in your Fiddle
For the previous button, it's
$(this).parent("td").prev("td").find("input").val(value1);
$(document).on('click', '#table input', function () {
var value1 = "";
value1 = $(this).val();
$(this).parent("td").next("td").find("input").val(value1);
});
for (a = 1; a <= 25; a++) {
var makeTable = false
if (!makeTable) {
$('#table').append('<table>');
}
$('#table').append('<tr>');
for (i = 1; i <= 5; i++) {
$('#table').append('<td>' + '<input type="button" class="numVa" value="' + a + '">' + '</td>');
a++;
}
a--;
$('#table').append('</tr>');
}
$('#table').append('</table>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="table"></div>
Update: For the previous unclear requirement that not only the value of the next and/or previous button should be changed, but also the values of the buttons above and below, adjusted Fiddle
Adjustment as follows: For getting the index/number of the cell and row of the clicked button, using index():
var bCell = $(this).parent("td");
var bRow = bCell.parent("tr");
var bCellNr = bCell.parent("tr").children().index(bCell);
var bRowNr = $("#table tr").index(bRow);
And then setting the values for the buttons with the same index in the following (bRowNr + 1) and previous (bRowNr - 1) rows :
$("#table tr:eq(" + (bRowNr + 1) + ") td:eq(" + bCellNr + " ),
#table tr:eq(" + (bRowNr - 1) + ") td:eq(" + bCellNr + " )")
.find("input").val(value1);
in case the button in the bottom row should change the value in case a button in the first row is clicked or
$("#table tr:eq(" + (bRowNr + 1) + ") td:eq(" + bCellNr + " )")
.find("input").val(value1);
if(bRowNr > 0)
{
$("#table tr:eq(" + (bRowNr - 1) + ") td:eq(" + bCellNr + " )")
.find("input").val(value1);
}
in case clicking a button in the first row shouldn't change last row button values (Fiddle. for this version).
As the previous table contained wrong markup (empty rows, several empty tables), the cleaned up code with the second variety as snippet:
$(document).on('click', '#table input', function () {
var value1 = "";
value1 = $(this).val();
$(this).parent("td").prev("td").find("input").val(value1);
$(this).parent("td").next("td").find("input").val(value1);
var bCell = $(this).parent("td");
var bRow = bCell.parent("tr");
var bCellNr = bCell.parent("tr").children().index(bCell);
var bRowNr = $("#table tr").index(bRow);
$("#table tr:eq(" + (bRowNr + 1) + ") td:eq(" + bCellNr + " )").find("input").val(value1);
if (bRowNr > 0) {
$("#table tr:eq(" + (bRowNr - 1) + ") td:eq(" + bCellNr + " )").find("input").val(value1);
}
});
for (a = 1; a <= 25; a++) {
$tr = $("<tr>");
for (i = 1; i <= 5; i++) {
$tr.append('<td>' + '<input type="button" class="numVa" value="' + a + '">' + '</td>');
a++;
}
a--;
$('#table').append($tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="table"></div>
If I understood your question correctly, pushing a button should make the text of the button next to it change, if so, this will work
$(document).on('click', '#table input',function () {
$(this).next("input[type='button']").val('i\'ve been changed by the '+$(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table"><input type="button" value="first button"/><input type="button" value="second button"/><input type="button" value="third button"/><div>
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.
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
I want to create a script, which would provide possibility of making food table with nutrients counting. Lets say a daily menu.
When user clicks buttons, ingredients are adding to table. There are + and - buttons in the line of ingredient to change amount of it by 1.
html:
<div class="menuContainer">
<div class="foodListContainer">
<div class="row"></div>
</div>
<div class="buttonsContainer">
<button value="100,g.,12.6,2.6,68,355">Buckweat</button>
<button value="1,ps.,6.3,5.7,0.35,78.5">Egg</button>
<button value="1,sp.,2.8,3.2,4.7,58">Butter</button>
<button value="100,g.,12.6,2.6,68,355">Meat</button>
</div>
js:
$(document).ready(function () {
//When user click a button
$(".buttonsContainer button").click(function () {
//catching the name of food
var choosenFood = $(this).text();
//catching the value of pressed button with info
//about this food and making an array with it
var value = $(this).val();
var arr = value.split(',');
//insert div's with info from array
$($.parseHTML(
'<div class="name">' + choosenFood + '</div><button class="up">+</button><div class="value">' + arr[0] + '</div><div class="unit">' + arr[1] + '</div><button class="down">-</button><div class="protein">' + arr[2] + '</div><div class="fat">' + arr[3] + '</div><div class="carbs">' + arr[4] + '</div><div class="kkal">' + arr[5] + '</div><br>')).appendTo(".row");
//trying to change value
$('.down').click(function () {
$(this).prev().prev(".value").html(function (i, val) {
return val * 1 - 1;
});
});
$('.up').click(function () {
$(this).next(".value").html(function (i, val) {
return val * 1 + 1;
});
});
});
The problem starts when there are 2 and more rows in the table. The more rows, the more + and - buttons change value. You better look at it here: https://jsfiddle.net/ts3n35bq/
I assume, that there is some problem with scopes. Probably, the crucial mistake is to call "up" and "down" actions right from "appendTo" action, and it seems like this functions repeated themselves in every row, until the end. But when I try to remove them from there, they don't work at all.
I will appreciate any advice or help. Thanks!
This should work for you.
$(document).ready(function () {
$('body').on('click', '.down', function() {
$(this).prev().prev(".value").html(function (i, val) {
return val * 1 - 1;
});
});
$('body').on('click', '.up', function() {
$(this).next(".value").html(function (i, val) {
return val * 1 + 1;
});
});
//When user click a button
$(".buttonsContainer button").click(function () {
//catching the name of food
var choosenFood = $(this).text();
//catching the value of pressed button with info about this food and making an array with it
var value = $(this).val();
var arr = value.split(',');
//insert div's with info from array
$($.parseHTML(
'<div class="name">' + choosenFood + '</div><button class="up">+</button><div class="value">' + arr[0] + '</div><div class="unit">' + arr[1] + '</div><button class="down">-</button><div class="protein">' + arr[2] + '</div><div class="fat">' + arr[3] + '</div><div class="carbs">' + arr[4] + '</div><div class="kkal">' + arr[5] + '</div><br>')).appendTo(".row");
//trying to change value
});
});
Use unbind on click function
$('.down').unbind().click(function () {
$(this).prev().prev(".value").html(function (i, val) {
return val * 1 - 1;
});
});
$('.up').unbind().click(function () {
alert($(this).next(".value").attr('id'));
$(this).next(".value").html(function (i, val) {
return val * 1 + 1;
});
});
$(".buttonsContainer").on('click','button',function (){
//your code
});
Instead of:
$(".buttonsContainer button").click(function () {
...
});
Use:
$(document).on('click', '.buttonsContainer button', function() {
...
});
Each time you click to add a div to your table you call $('.down').click() which binds the event to all the existing buttons with the "down" class. Adding more than a single row makes it so that for a single click event you have multiple handlers attached to the preexisting buttons.
You can easily fix this without changing much of your code. Instead of appending the new row directly save it to a variable first and add the click handler to the down/up element inside it:
var rowString = '<div class="name">' + choosenFood + '</div><button class="up">+</button><div class="value">' + arr[0] + '</div><div class="unit">' + arr[1] + '</div><button class="down">-</button><div class="protein">' + arr[2] + '</div><div class="fat">' + arr[3] + '</div><div class="carbs">' + arr[4] + '</div><div class="kkal">' + arr[5] + '</div><br>';
var newRow = $($.parseHTML(rowString));
newRow.filter(".down").click( function () {
$(this).prev().prev(".value").html(function (i, val) {
return val * 1 - 1;
});
});
newRow.filter(".up").click(function () {
$(this).next(".value").html(function (i, val) {
return val * 1 + 1;
});
});
newRow.appendTo(".row");
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)
I'm using the .each function to hide/show columns of a table. But the problem is that the code is very slow in IE. After searching on internet I saw that could be because of my .each() function and $(this).
For more information why I'm using this code, you can look at this post: Hide/show column
This is my old code:
include JQuery.min.js on page
javascript:
$(function () {
$('table th').each(function (_id, _value) {
if(_id > 2){
if($(this).find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($(this).find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
});
});
HTML:
<div id="togglers">Show/Hide columns<br/></div>
I tried to convert my javascript with this code (Source: jQuery very slow in IE), but I think there is still a problem with my i(or _id) and _value...
$(function () {
var items = $('table th');
var $currentItem;
for (var i = 0, j = items.length; i < j; i++) {
$currentItem = $(items[i]); // in place of $(this)
function (i, _value) {
if(i > 2){
if($currentItem.find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($currentItem.find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
}
}
});
It's possible that I need to use other code. Any suggestion is welcome! Tnx.
Performance issue has nothing to do with .each. DOM is tens of times slower than any way to iterate collection you choose.
Instead of iterating table on every toggle you can make CSS do it for you. Demo.
$(function() {
var togglers = $('#togglers'), //cache toggler ref
addToggler = function(idx, text) {
togglers.append('<span class="toggler" data-id="'
+ idx + '">' + text + '</span>');
},
table = $('#table'), //cache table ref
columns = 0;
//generate styles for 100 columns table :)
(function generateStyleSheet(len){
var styles = [], i = 0;
for(; i < len; i++) {
styles.push('.hide-' + i + ' .column-' + i + ' {display: none;}') ;
}
$('<style>' + styles.join('\n') + '</style>').appendTo(document.body);
}(100))
//bind on click once using event delegation
togglers.on('click', '.toggler', function(e){
var id = $(e.target).toggleClass('pressed').data('id');
table.toggleClass('hide-' + id);
});
//generate all togglers and count em
table.find('th').each(function(idx, header){
header = $(header);
addToggler(idx, header.text()); //make toggler
header.addClass('column-' + idx); //add class column-i
columns++;
});
//add column-i class to tds
table.find('td').each(function(idx, td) {
$(td).addClass('column-' + (idx%columns));
});
});