I don't understand why the check() function doesn't want to fire, I know that if I set this function to setInterval(check, 1000) or to function $("#btn-click") it will work but why it doesn't work now? I would appreciate if you explain me
$(function() {
$("#field").on("keyup", function() {
var x = $(this).val();
$("#outcome").text(x);
});
$("#btn-save").click(function() {
var name = $("#outcome").text();
var x = $("table tbody").append("<tr><td>" + name + "</td></tr>")
$("#field").val("");
$("#outcome").text("");
});
check();
function check() {
if ($("table tbody").has("tr")) {
$("table tbody tr td").on("click", function(e) {
var tar = $(e.target);
var b = $(this);
if (tar.is(b)) {
b.css("color", "red");
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type='text' id='field'>
<p>The result is: <span id="outcome"></span></p>
<span id="btn-save" class="btn-save">save</span>
<table>
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
The function fires, but there's no td element to attach events to.
If you want to bind events to elements that will be dynamically generated, you do not need a check function, just use $(body').on(evtType,selector,handler)
Check below for an example. every td you'll add dynamically will still be bound to the event listener, because it's attached to 'body'.
$(function() {
$("#field").on("keyup", function() {
var x = $(this).val();
$("#outcome").text(x);
});
$("#btn-save").click(function() {
var name = $("#outcome").text();
var x = $("table tbody").append("<tr><td>" + name + "</td></tr>")
$("#field").val("");
$("#outcome").text("");
});
check();
function check() {
console.log('firing')
}
$('body').on('click', 'table tbody tr td', function(e) {
var tar = $(e.target);
var b = $(this);
if (tar.is(b)) {
b.css("color", "red");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type='text' id='field'>
<p>The result is: <span id="outcome"></span>
</p>
<span id="btn-save" class="btn-save">save</span>
<table>
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
check() is firing. It's just not doing anything because of your if logic, which had bad selectors pointing to elements (tbody, td) that you don't have.
You won't get a td element in your table until AFTER you click btn-save because that click event handler creates the td elements. Your code wants to run check before that button gets clicked.
I've removed the reference to tbody and changed your td reference to th and now it works:
$(function() {
$("#field").on("keyup", function() {
var x = $(this).val();
$("#outcome").text(x);
});
$("#btn-save").click(function() {
var name = $("#outcome").text();
var x = $("table tbody").append("<tr><td>" +name+"</td></tr>")
$("#field").val("");
$("#outcome").text("");
});
check();
function check() {
console.log("HELLO FROM CHECK!");
if ($("table").has("tr")) {
$("table tr th").on("click", function(e) {
var tar = $(e.target);
var b = $(this);
if (tar.is(b)) {
b.css("color", "red");
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='field'>
<p>The result is: <span id="outcome"></span></p>
<span id="btn-save" class="btn-save">save</span>
<table>
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Related
I have two JavaScript functions: one toggles (hide/show) a table row when a link is clicked, and another that filters table rows (showing only rows with text that's entered into a text field). When someone enters text into the text field, I want to be able to hide all of the shown table rows (that were toggled). So, basically, I'm trying to add part of the toggle function to the filter function. The toggle function needs to function on its own, but all items will be hidden when text is entered.
Toggle Function
If a table row has an ID (id="celltohid1" or id="celltohid1"), then the following function hides or shows that row when a link it clicked...
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'table-row')
e.style.display = 'none';
else
e.style.display = 'table-row';
}
//-->
</script>
Filter Function
Below is the Filter function...
<script>
$(document).ready(function(){
$(".search").on("keyup",function(){
var searchTerm = $(this).val().toLowerCase();
$("#DMTbl tbody tr.contentrow").each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
});
});
</script>
Goal (and my weak attempt)
I need to add functionality that hides all the rows with IDs that contain "celltohid" (if all the id's are celltohid#)... I don't know JavaScript, so below is my weak attempt at this. Every row with the unique ids "celltohid#" has a class "descexpand". So, I tried adding a toggle to change the display style for that class ... but it's not working...
<script>
$(document).ready(function(){
$(".search").on("keyup",function(){
var searchTerm = $(this).val().toLowerCase();
$("#DMTbl tbody tr.contentrow").each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
var clasname = "descexpand";
var e = document.getElementByClass(clasnam);
if(e.style.display == "table-row") {
e.style.display = "none";
}
});
});
});
</script>
Can anyone help?
You don't need <td/> id's for filtering. You can simply check the string in <tr/> and hide if there text doesn't exist.
$(document).ready(function() {
$(".search").off('keyup').on("keyup", function() {
var searchTerm = $(this).val().toLowerCase();
$("table tbody tr").each(function(index) {
var lineStr = $(this).text().toLowerCase();
if (lineStr.indexOf(searchTerm) < 0) {
$(this).hide();
} else {
$(this).show();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</tbody>
</table>
<input class="search" type="text" />
With help I've gotten this script to change the class of the function to include countable but need to get the total calculation to update the sum of all fields shown when that change takes place.
The scripts are split with the top one set to calculate the total of all countable class fields and the second script section set to show the line items and add the countable class.
<script>
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.countable').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
</script>
<script>
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
These checkboxes allow display of the line items when selected.
<input class="my-activity" type="checkbox" value="42"/> example<br/>
<input class="my-activity" type="checkbox" value="43"/> example<br/>
<table id="sum_table">
<tr class="42" style="display:none">
<td>example</td>
<td></td>
<td></td>
<td class="price">7800</td>
</tr>
<tr class="43" style="display:none">
<td>First Area</td>
<td></td>
<td></td>
<td class="price">6900</td>
</tr>
<tr class="totalColumn">
<td>Total:</td>
<td></td>
<td class="totalCol"></td>
</tr>
</table>
You need to load jQuery before you can use it, so move:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
above the other 2 scripts. Then, replace your first script with this:
function showTotal(){
//grab the .countable elements from the #sum_table
var $countables =$("#sum_table .countable");
//loop through and add up the total from their texts
var total = 0;
for(var i = 0; i < $countables.length; i++){
total += Number($countables.eq(i).text());
}
//put the total in the .totalCol element
$("#sum_table td.totalCol").html(total);
}
and call this function at the end of your onchange function, like this:
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var val = $(this).val();
var isChecked = $(this).is(":checked");
var $trElement = $('.' + val);
var $tdPriceElement = $trElement.find('td.price');
$trElement.toggle(isChecked);
$tdPriceElement.toggleClass('countable', isChecked);
//CALL IT HERE:
showTotal();
});
});
I want multiple textarea(ck editor) where user can input multiple data in it , i tried various function and methods of jquery like clone() and appendTo but the problem is they are cloning the textarea but ckeditor is not working, after cloning the textarea i am unable to wrote anything in it
Please help me with it.
This is what i tried
test1
http://jsfiddle.net/FADxv/793/
test2
http://jsfiddle.net/kbqjnecx/3/
Thanks
Add an id to each new textarea and manually initialize the editor using
CKEditor.replace(id [,config])
Something like:
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
var editorId = 'editor_' + x;
$(wrapper).append('<div> <textarea id="'+editorId+'" class="ckeditor" name="ck[]"></textarea>Remove</div>'); //add input box
CKEDITOR.replace(editorId, { height: 200 });
}
});
DEMO
Check this for cloning ckeditor.
Check this fiddle : http://jsfiddle.net/manektech/47htysb5/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.ckeditor.com/4.5.4/standard/ckeditor.js"></script>
</head>
<body>
<div class="row hide_mail_id_domain">
<div class="col-sm-12">
<table class="table">
<thead>
<tr>
<th>Option</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<textarea class="ckeditor" required="" name="question_option_1" ></textarea>
</td>
<td></td>
</tr>
</tbody>
</table>
Add More
</div>
</div>
<script>
var REMOVE = '';
var i=1;
$(document).ready(function () {
$('.add_more').click(function () {
var oneplus=i+1;
var tr_object = $('tbody').find('tr:first').clone();
// getting and renaming existing textarea by name.
$(tr_object).find('textarea[name="question_option_1"]').attr("name", "question_option_"+oneplus+"");
$(tr_object).find('input').val('');
$(tr_object).find('td:last').html('Remove');
$('tbody').append(tr_object);
//replace code
CKEDITOR.replace("question_option_"+oneplus+"");
// when i were clicking on add more during my testing , then extra cke-editor id also appending to DOM. so for removing other then first
// included below code
$('#cke_question_option_1').each(function() {
var $ids = $('[id=' + this.id + ']');
if ($ids.length > 1) {
$ids.not(':first').remove();
}
});
i=i+1;
oneplus++;
});
$(document).on('click', '.remove_more', function () {
var id = $(this).closest('tr').find('.id').val();
if (id != '') {
if (REMOVE != '') {
REMOVE = REMOVE + ',' + id;
} else {
REMOVE = id;
}
$('#id').val(REMOVE);
}
$(this).closest('tr').remove();
});
});
</script>
</body>
</html>
I have the following code to enable inline editing of td cells:
$('.edit_td').click(function(e) {
e.stopPropagation();
resetEditedCells();
$(this).addClass('active').html('<input type="text" value="' + $(this).html() + '">');
});
function resetEditedCells() {
$('.edit_td.active').html(function() {
return $(this).find('input').val();
});
}
$(document).click(function() {
if($('.edit_td').hasClass('active')) {
var fisk = $('.active input[type=text]').val();
$('.edit_td').find('input').hide().html(fisk);
}
});
I have two problems:
When the TD has transformed to an input field, I can't write a new text in it. I cant edit the text.
When I click outside the table, I want the input field to transform back to the td with its original text value, but it does not do that with my code above. The input field is removed, but the text is also removed/hidden. I only want the input to disappear.
Anyone who can help me?
Here is a working version of what you wanted.
const $edits = $('.edit_td');
$edits.on('click', function(e){
e.stopPropagation();
const $this = $(this);
if(!$this.hasClass('active')){
$this.addClass('active');
const val = $this.html();
console.log(val);
$this.html(`<input type="text" value="${val}"/>`);
}
});
function removeActive() {
$edits.each(function() {
const $this = $(this);
if ($this.hasClass('active')) {
const val = $this.find('input').val();
$this.empty();
$this.html(val);
$this.removeClass('active');
}
});
}
$(document).on('click', removeActive);
table {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="edit_td">Test 123</td>
</tr>
<tr>
<td class="edit_td">Test 456</td>
</tr>
<tr>
<td class="edit_td">Test 789</td>
</tr>
</table>
I suggest you hide/show the td/input box instead of changing the html, that will save you from a lot of trouble afterwards.
I am new to javascript.
Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?
Kindly note that I am inserting the data in table cells using innerHTML.
Below is the code snippet of what i have tried.?
Java Script function:
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var row = table.insertRow(-1);
var rowValues1 = finSumArr1[i].split("|");
for(var k=0;k<=10;k++)
{
var cell1 = row.insertCell(k);
var element1 = rowValues1[k];
cell1.innerHTML = element1;
}
}
for(var i=1; i<rowCount; i++)
{
for(var k=0;k<=10;k++)
{
document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);
}
}
}
HTML table code in jsp :
<TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >
<th>Symbol</th>
<th>Claimant</th>
<th>MJC</th>
<th>S</th>
<th>Type</th>
<th>Indemnity Resv</th>
<th>Indemnity Paid</th>
<th>Medical Resv</th>
<th>Medical Paid</th>
<th>Legal Resv</th>
<th>Legal Paid</th>
</tr>
<tr>
<td>
</td>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</tr>
</table>
<table id="table"></table>
$("#table").append("<tr><td>Hi there</td></tr>");
$("#table").on( "click", "tr", function(){
// do something
alert( $(this).children("td:first").text() );
});
Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).
This will require the jQuery library
http://jquery.com/
http://api.jquery.com/on/
One way to do it would be using document.createElement
Instead of doing:
yourParentElement.innerHTML = "<tr>Something</tr>";
You can do
var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
//code to be executed onclick
};
yourParentElement.appendChild(tr);
Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):
yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event
}
You can read more about events here, but just so you have an idea onclick will only let you set one function.
If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.
Lastly, if you want to set up an event on every tr you can use:
var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event
after you insert your <tr> using innerHTML, create a click event listener for it.
document.getElementById("the new id of your tr").addEventListener("click", function() {
what you want to do on click;
});
Something like this: http://jsfiddle.net/gnBtr/
var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');
var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'
// Function to change the content of containerEl
function modifyContents() {
containerEl.innerHTML = inner;
var contentEl = document.getElementById('content');
contentEl.addEventListener("click", handleClickOnContents, false);
}
// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
alert("you clicked on a div that was dynamically created");
}
// add event listeners
startEl.addEventListener("click", modifyContents, false);
Check it out:
$('#your_table_id tbody').on('click', 'tr', function (e) {
$('td', this).css('background-color', 'yellow');
} );
css:
tr:hover td{
background-color: lightsteelblue !important;
}
It works fine for me, specially when I'm using jquery dataTable pagination.