I would like to have a radio button become checked when clicking on the cell in which it resides. Also the background color of the cell should change.
I have managed to get the cell to change background color when it is clicked but I want it to also select the radio button in addition to changing the background color.
I am new to javascript and i have got the jsfiddle working below based on other examples but cannot figure out the rest (tried a lot of different things)
http://jsfiddle.net/Lude352m/1/
Javascript:
$('.custom-matrix tr').click(function (e) {
console.log("Inside #out code");
var cell = $(e.target).get(0); // This is the TD you clicked
//if (cell.nodeName != 'TD') cell = $(cell).closest('td').get(0);
// Remove the background color for all cells
var c = $(cell).parents('tr').children('td');
$(c).each(function () {
$(c).removeClass('info');
});
// Add the background color for the clicked cell
$(cell).addClass("info")//.parent().siblings("tr").find("td.info").removeClass("info");
var rad = $(cell).children('input');
console.log("Radio: " + rad);
//for(var key in rad) {
// console.log('key: ' + key + '\n' + 'value: ' + rad[key]);
//}
$(rad).prop("checked", true)
// Output code to help (but will be removed once working)
// Empty the div '#out' (clear its contents)
$('#out').empty();
var tr = $(this); // This is the TR (row) you clicked
// Loop through the TD's within the TR ?? i think?
// The 'i' is used as a counter but not sure how it increases each loop
$('td', tr).each(function (i, td) {
$('#out').html(
//Cumulatively add the result of each TR (row) to the '#out' div's contents
$('#out').html() + '<br>' + i + ': ' + $(td).text() + (td === cell ? ' [clicked]' : '')
);
});
Your radio inputs are not a direct child of your <td>, but a child of the <label> inside the <td>, so
var rad = $(cell).children('input');
need to be changed to either
var rad = $(cell).children().children('input');
OR using .find()
var rad = $(cell).find('input');
Try this code
$(cell).find("input").attr('checked', true);
or
$(cell).find("input").prop('checked', true);
Here is a working Fiddle
Related
I am building a user interface with javascript and some jquery that is populated by a for loop from an array of products and their individual details. Once the products load with the abridged details, I want the user to be able to click on a 'details' button that will have make a pop up window appear showing the full details of the selected item. I have everything working HOWEVER the window is populated by the last item created by the for loop, as opposed to those of the item selected. I am pretty new to javascript and haven't been able to find any solutions that would fit this problem. Any ideas on how to accomplish this?
document.body.onload = addElement;
function addElement () {
for(i = 0; i < items.length; i++) {
//Create elements for items and pop windows, and html for individual item details
var prodDiv = document.createElement("div");
var popDiv = document.createElement("div");
// Add the rest of the html and looped data to variables
var popUpWindow = "<div class='popup-content'>" + divName + divPrice + divBrand + rating + prodId + divLong + "</p><button class='close'>Close</button></div></div>";
var blob = divImage + divName + divPrice + divBrand + divShort;
//Account for null values
if(items[i].brand == null) {
if(items[i].salePrice == null) {
var blob = divImage + divName + divPrice + divShort + dtlButton;
} else {
var blob = divImage + divName + divSale + divShort + dtlButton;
}
} else {
if(items[i].salePrice == null) {
var blob = divImage + divName + divPrice + divBrand + divShort + dtlButton;
} else {
var blob = divImage + divName + divSale + divBrand + divShort + dtlButton;
}
}
//Add item info to HTML element
prodDiv.innerHTML = blob;
popDiv.innerHTML = popUpWindow;
//Add class attributes
prodDiv.setAttribute("class", "col-sm-4 col-lg-2 prodContent");
popDiv.setAttribute("class", "popup-overlay");
//Add new element to div
var currentDiv = document.getElementById("allDiv");
currentDiv.appendChild(prodDiv);
currentDiv.appendChild(popDiv);
//Appends an "active" class to .popup and .popup-content when
the "Open" button is clicked
$(".open").on("click", function(){
$(".popup-overlay, .popup-content").addClass("active");
});
//Removes the "active" class to .popup and .popup-content when
the "Close" button is clicked
$(".close, .popup-overlay").on("click", function(){
$(".popup-overlay, .popup-content").removeClass("active");
});
}};
There're some problem.
You bind event in for loop, and event is bind for a class selector => all exists button will be binded again.
It's mean, if you have 10 item, first button will call 10 times click funtion.
You should move them outside for loop, or change selector.
And you must tell jquery exactly popup to show when you click a button
You can change like that:
1: add some thing to identify popup
var popUpWindow = "<div class='popup-content itemid-"+ yourItemId +"'>"
2: Then, bind to only right button
$(prodDiv).find(".open").on("click", function(e){
//do smthing to show right div,
// $(".itemid-"+yourItemId ) .....
});
and fix close button, too
I have a table with a default of 4 rows for user to input. please see the fiddle here http://jsfiddle.net/xaKXM/4/
When the user click on "Add More", the table will add new row to the "labelTable" with unique ID, as well as "configtableTable".
var displaymore = '<tr id=row'+currentIndex+'><td style="text-align: center">'+currentIndex+'</td>'+
'<td width="60%"><p id="label_row_'+currentIndex+'"></p></td>'+
'<td><button type="button" class="switch" id="switch_'+currentIndex+'"data-role="button" data-transition="fade">Activate</button></td></tr>';
When button "Submit" is pressed, user can see the description and the "Activate" button in the configtableTable. In order to make sure the Activate button is useful, i append thisIndex to a paragraph #ptest. It works for the first 4 default rows but does not work for the newly added rows (5 onwards).
What's wrong with my logic and code?
SOLVED: by creating a class "switch" and use .on()
$("#configtableTable").on('click', ".switch", function () {
thisIndex= $('td:nth(0)',$(this).closest('tr')).text();
if(thisIndex == ""){thisIndex = 0;}
$('#ptest').append(thisIndex);
$.post('/request', {responseNumber:$('#number_'+thisIndex).val(), key_pressed:"activate"});
});
there are two errors
1.In the generated code for "addmore", it should be following code for button
id="switch_' + currentIndex + '"
2.After creating new buttons, you have to add the click event for them.
I suggest the following code
$('#configsubmit').click(function () {
for (var x = 1; x <= currentIndex; x++) {
$('#label_row_' + x).html($('#label_' + x).val());
}
$('#configtable').show();
$("#configeditdiv").show();
$('#labels').hide();
$("#configtableTable [id^='switch_']:button").unbind('click');
$("#configtableTable [id^='switch_']:button").click(function () {
thisIndex = $('td:nth(0)', $(this).closest('tr')).text();
if (thisIndex === "") {
thisIndex = 0;
}
$('#ptest').append(thisIndex);
$.post('/request', {
responseNumber: $('#number_' + thisIndex).val(),
key_pressed: "activate"
});
});
I am using Jquery to dynamically populate the table element. My table will have three columns - Label, textarea and a button. I am binding a click event on click of the button. Below is my Jquery code.
var rowElem = $('<tr id="'+ key + '" class="queryRow"> </tr>');
rowElem.append($('<td class="queryTitleCol">' + key + '</td>'));
var colElem = $('<td class="queryValueCol"></td>');
var textAreaElem = $('<textarea rows="10" cols="75"/>');
colElem.append(textAreaElem);
rowElem.append(colElem);
textAreaElem.val(value);
var btnCol = $(
'<td valign="top">'
+ '<button style="width:42px; vertical-align:middle; margin:2px;" title="delete">'
+ '<span class="ui-icon ui-icon-trash" style="float:left;"/>'
+ '</button>'
+'</td>');
rowElem.append(btnCol);
$("button", btnCol).click(action);
}
In the button event I am using Jqury.closest to get the TR tag and label element. Below is my code for button click.
function action() {
var rowElem = $(this).closest("tr");
var labelTD = $(".queryTitleCol", rowElem);
}
But labelTD , I am always getting as [td.queryTitleCol] as an array. I am not able to get the td element to get the lable element. I tried with find(), but still I am getting as td array.
rowElem.find('td.queryTitleCol');
How can I traverse and get the label name on click function of the button. Any help will be really appreciated.
Try
var label = $(".queryTitleCol", rowElem)[0].innerHTML;
or
var label = $(".queryTitleCol", rowElem).text();
You could try something like
$('button').click(function(){
$(this).prev('.queryTitleCol').text();
});
This will always grab the previous element with queryTitleCol as its class. It only returns one element, so you shouldn't run into the problem you've been describing.
You can try this
function action() {
var titleCol = $(this).parent().parent().find('td:eq(0)').text();
}
Check this FIDDLE
I am using following code to update one textbox value txtUnitPrice based on other textbox txtQuantity ,both can be generated dynamically which is done.
//update unitprice based on quantity of product and tax applied
$('input').live('keyup', function () {
var inputId = $(this).attr('id'); //get textbox txtQuantity id
var rowNum = parseInt(/txtQuantity(\d+)/.exec(inputId)[1], 10); //get row id
var productValue = $("#ddlProduct" + rowNum).val();
var taxValue = $("#ddlTax" + rowNum).val();
var unitPriceValue = $("#txtUnitPrice" + rowNum).val();
var quantityValue = $("#txtQuantity" + rowNum).val();
if ((quantityValue != " ") && (quantityValue > 0)) {
$("#txtUnitPrice" + rowNum).val(unitPriceValue * quantityValue);
}
else {
$("#txtUnitPrice" + rowNum).val(unitPriceValue);
}
});
Now problem arising in the code above is that when I even moving cursor forward or backward in the textbox txtQuantity then the value for txtUnitPrice is changing becuase which this event 'keyup' is firing and hence whole code is executed with the existing txtunitprice value and multiplies this again with the existing txtquantity which I dont' want Please can anyone help me regarding this . Thanks
Just add a check to ignore the cursor movements like shown below
$('input').live('keyup', function (e) {
if([37, 38, 39, 40].indexOf(e.which)){
return false;//do nothing because the cursor keys have been pressed
}
//the rest of your code
});
There is one data table with two rows, as per below image
When user click on 2bit it should highlight that TD in that column only. I achieved this using jQuery for one check box selection, but when multiple check box selection like 2 and 4 it should highlight both the TD.
http://jsbin.com/exazoh/edit#preview working example for single value highlight.
Code: http://jsbin.com/exazoh/2/edit
Try the following function:
jQuery(function() {
// on change of an input with a name starting with "bit-select"...
jQuery('input[name^="bit-select"]').change(function(){
var checked = this.checked,
val = this.value,
column = $(this).closest("th").index() + 1;
// for each td in the current column
jQuery("#tableData tr.data td:nth-child(" +
column + ")").each(function() {
var $td = $(this);
// does the current td match the checkbox?
if ($td.text() == val) {
if (checked)
$td.addClass("jquery-colorBG-highLight");
else
$td.removeClass("jquery-colorBG-highLight");
}
});
});
});
I had to add the value attributes to the second set of checkboxes.
Working demo: http://jsbin.com/exazoh/4/edit#preview
Or the short version, since I notice you were using .filter() originally:
jQuery(function() {
jQuery('input[name^="bit-select"]').change(function(){
var method = this.checked ? "addClass" : "removeClass",
val = this.value;
jQuery("#tableData tr.data td:nth-child("+($(this).closest("th").index()+1)+")")
.filter(function(){return $(this).text()==val;})[method]("jquery-colorBG-highLight");
});
});
Demo: http://jsbin.com/exazoh/5/edit