Checkbox unclick event Javascript - javascript

I have problem that checkbox uncheck event. When I unclick the checkbox it should be revert back. How can I do this?
<body>
<script>
function change()
{
var cb = document.querySelectorAll('input[type="checkbox"]')[0];
var td = document.querySelectorAll("td[contenteditable]")[0];
cb.addEventListener("click", function () {
td.className = td.className + " crossed";
});
}
</script>
</body>

Either toggle the class like:
cb.addEventListener("click", function () {
td.classList.toggle("crossed");
});
JSFiddle Demo
Or check if the checkbox is checked:
cb.addEventListener("click", function () {
if(cb.checked) td.classList.add("crossed");
else td.classList.remove("crossed");
});
JSFiddle Demo
If you want to keep the older browser support, you can do it like:
cb.addEventListener("click", function() {
if (cb.checked) td.className += " crossed";
else {
var tdclass = td.className.split(" "),
ind = tdclass.indexOf("crossed");
tdclass.splice(ind, 1).join(" ");
td.className = tdclass;
}
});
JSFiddle Demo

While you've already accepted an answer, I'd suggest a minor adjustment to the following:
function change() {
// querySelector() returns the first element matching the
// selector (or null, if no matching element is found):
var cb = document.querySelector('input[type="checkbox"]'),
td = document.querySelector("td[contenteditable]");
// use the change event on the check-box:
cb.addEventListener("change", function () {
// adds, or removes, the class 'crossed'
// based on the assessment that follows;
// of the cb node is checked (true) the
// class is added (if not already present),
// otherwise it's removed:
td.classList.toggle('crossed', cb.checked);
});
}

okay u want a tick to be re-enable when u click on it to unclick!!!
$("input[type='checkbox']").props('checked','false') {
$("input[type='checkbox']").props('checked','true')
}
Try to use a selector like id or something in place of: input[type='checkbox']

Related

JQuery undo append

I've got a table with a button inside a td, once I press the button it adds text to the td. I want to remove this text inside the td once i press the button again. note that this button is used multiple times in the table hence the class attribute.
Which method could I use to get this done?
This is my code:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<br>" + "test"); // td class="ReleaseTD"
}
// the code above this works
else {
$(this).text("Add");
$('.ReleaseTD').remove("<br>" + "test");
// this obviously is wrong but this is where i would like the correct code
};
});
You could create ID for text inside like this:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<span id='textID'><br>" + "test</span>");
}
else {
$(this).text("Add");
$('#textID').remove();
};
});
Please try the following:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<span id='txt_name'><br>" + "test</span>");
}
// the code above this works
else {
$(this).text("Add");
$('#txt_name').remove();
};
});
Two ways:
1) Append your text into a span with a unique ID, and then delete this ID. For example, delete the ID with the largest number. Dumbest way would be to just store the latest ID in a global variable.
var global_last_appended_id = 0;
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
global_last_appended_id ++;
$('.ReleaseTD').append("<span id='appended-text-" + global_last_appended_id + "'><br>" + "test</span>");
}
// the code above this works
else {
$(this).text("Add");
$('#appended-text-' + global_last_appended_id).remove();
global_last_appended_id--; //go one step back so next time we remove the previous paragraph
};
});
Update: after your edit I've added the ability to undo multiple times. Basically there is unlimited undo.
2) [lame and wrong] Save the previous .html() - the whole HTML code of your element - into a global variable; then restore the previous version of the text from the global variable when necessary.

jQuery .click()/.on("click"...) I need help swapping text on alternate clicks

What I am trying to accomplish is something 'like'
$("button .toggleExcerpt)
.toggle( function FIRST() {
do first function...
} , function SECOND() {
do second function...
But since it's deprecated, I don't know what alternative to use. Ive tried using if/else inside of a .on("click", function()... but didn't seem to work.
jQuery:
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
//".toggleExcerpt" is an empty <button> in the HTML
$(".toggleExcerpt").append(readMore);
$(".toggleExcerpt")
.on("click", function (event) {
$(this).contents(".readMore")
.replaceWith(readLess);
console.log("readMore ran");
})
.on("click", function (event) {
$(this).contents(".readLess")
.replaceWith(readMore);
console.log("readLess ran");
})
Both of the click events are logging to the console, so I know that the first event is running, and then is quickly replaced by the second event, but I would love to make these (or simply the text inside the span) to alternate....
I've already looked at this suggestion, but I am not sure how to implement it in my example, nor if this particular jQuery implementation is what I need.
To check the class is exists or not , you have to use .hasClass() . if class found,use .remove() to remove that element and .append() to add another.
For example, You can try this code :
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
//".toggleExcerpt" is an empty <button> in the HTML
$(".toggleExcerpt").append(readMore);
$(".toggleExcerpt")
.on("click", function (event) {
if($(this).find('span').hasClass('readmore') === true){
$(this).find('span.readmore').remove();
$(this).append(readLess);
}else{
$(this).find('span.readLess').remove();
$(this).append(readMore);
}
})
Check this snippet:
var readMore = "read about the solution...";
var readLess = "hide full description...";
var excerptState = true;
//".toggleExcerpt" is an empty <button> in the HTML
$(".toogleExcerpt").html(readMore);
$(".toogleExcerpt").click(function () {
$(this).html( excerptState ? readLess : readMore );
// invert state
excerptState = !excerptState
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="toogleExcerpt"></button>
Why not try letting a boolean swap back and forth for you?
Here's your snippet:
$(document).ready(function() {
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
var more = true;
//".toggleExcerpt" is an empty <button> in the HTML
$("#toggleExcerpt").append(readMore);
$("#toggleExcerpt")
.on("click", function(event) {
if (more) {
$(this).contents(".readMore")
.replaceWith(readLess);
console.log("readMore ran");
more = false;
} else {
$(this).contents(".readLess")
.replaceWith(readMore);
console.log("readLess ran");
more = true;
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="toggleExcerpt"></button>
I think I created a solution for you.
Just use a flag var that increments by 1, and check if it is odd or even and depending on if it is odd or even it will alternate the text for you onclick:
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
//".toggleExcerpt" is an empty <button> in the HTML
var flag = 0;
$(".toggleExcerpt").append(readMore);
$(".toggleExcerpt")
.on("click", function(event) {
if (flag % 2 == 0) {
$(this).contents(".readMore")
.replaceWith(readLess);
console.log("readMore ran");
} else {
$(this).contents(".readLess")
.replaceWith(readMore);
console.log("readLess ran");
}
flag++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="toggleExcerpt" style="width:300px">

How to write DRY code when working $(this) and $each for form inputs

I've written some code which enables and disables input and select fields on a series of forms. I have repeated a lot of code and I wanted to know how I would write this in a DRY, scalable way.
I created a Fiddle and and it repeats three times - edit, cancel and save.
$(edit).each(function(){
$(this).on('click', function(){ }); });
Here is my fiddle.
https://jsfiddle.net/tellmehow/5tcs6f82/9/
I will keep working on this, but if anyone has any pointers or a similar Fiddle, please let me know. Thanks.
You could reduce your repetition of hide/show/disable etc, by putting your form/button manipulation into a single function like this:
function setFormMode($form, mode){
switch(mode){
case 'view':
$form.find('.save-button, .cancel-button').hide();
$form.find('.edit-button').show();
$form.find("input, select").prop("disabled", true);
break;
case 'edit':
$form.find('.save-button, .cancel-button').show();
$form.find('.edit-button').hide();
$form.find("input, select").prop("disabled", false);
break;
}
}
Create three "onclick" functions (because, presumably you'll want to do other things as well):
function edit_onclick(){
setFormMode($(this).closest("form"), 'edit');
}
function cancel_onclick(){
setFormMode($(this).closest("form"), 'view');
//TODO: Undo changes?
}
function save_onclick(){
setFormMode($(this).closest("form"), 'view');
//TODO: Send data to server?
}
And then bind:
$('.save-button').on('click', save_onclick);
$('.cancel-button').on('click', cancel_onclick);
$('.edit-button').on('click', edit_onclick);
Fiddle: https://jsfiddle.net/5tcs6f82/10/
You can also do something like the following. It doesn't use jQuery but demonstrates an alternative approach that adds or removes a class called hidden to hide or show the buttons. It also uses event delegation to reduce the number of listeners.
.hidden {
display: none;
}
The following is the main function, it can be more concise if a toggle class function is used.
/* If click is from element with class edit-button, hide it and show
* buttons with class cancel-button or save-button.
* If click is from element with class cancel-button or save-button,
* hide them and show button with class edit-button
*/
function toggleButtons(event) {
var form = this;
var target = event.target;
// If the click came from a button with class edit-button, hide it and
// show the cancel and save buttons, otherwise show the edit button and
// hide the cancel and show buttons
if (hasClass(target, ['cancel-button','save-button','edit-button'])) {
var buttons = form.querySelectorAll('.cancel-button, .save-button, .edit-button');
Array.prototype.forEach.call(buttons, function(el) {
if (hasClass(el, 'hidden')) {
removeClass(el, 'hidden');
} else {
addClass(el, 'hidden');
}
});
}
}
Instead of adding a listener to each element, just add one listener to each form:
window.onload = function() {
for (var forms=document.forms, i=0, iLen=forms.length; i<iLen; i++) {
// Add listener to each form
forms[i].addEventListener('click', toggleButtons, false);
// Hide the cancel and save buttons
Array.prototype.forEach.call(forms[i].querySelectorAll('.cancel-button, .save-button'),
function(el){addClass(el, 'hidden')}
);
}
}
Some library functions that replace equivalent jQuery
// Return true if el has class className
// If className is an array, return true if el has any class in className
function hasClass(el, className) {
if (typeof className == 'string') {
className = [className];
}
var re = new RegExp('(^|\\s+)(' + className.join('|') + ')(\\s+|$)');
return re.test(el.className);
}
// Add class className to el
function addClass(el, className) {
var classes;
if (!hasClass(el, className)) {
classes = el.className.match(/\S+/g) || [];
classes.push(className);
el.className = classes.join(' ');
}
}
// Remove class className from el
function removeClass(el, className) {
var re;
if (hasClass(el, className)) {
var re = new RegExp('(^|\\s+)' + className + '(\\s+|$)','g');
classes = el.className.replace(re, ' ').match(/\S+/g);
el.className = classes.join(' ');
}
}

Accessing elements of a table row on the basis of checked radio button

On my webpage, I have a table in which there's a radio button for each row. The name of radio buttons is the same for all rows to access them as a group. I have a button which alerts the row number whose radio button is checked. I'd like to access individual elements of the table of that row as well. Any thoughts as top how I might be able to achieve this would be very welcome.
Here's a Fiddle for the issue:
http://jsfiddle.net/Gz668/13/
On the click of the button "edireq", it currently alerts the row number whose radio button is checked. I'd like to access the values of other fields of the table (requestor, approver, status etc. too.)
Here's the jquery code
$("#edireq")
.button()
.click(function () {
var ele = document.getElementsByName('reqradio');
var len = ele.length;
var flag = -1;
for (var j = 0; j < len; j++) {
if (ele[j].checked) {
flag = j;
}
}
if (flag > -1) {
alert("Row : " + (flag + 1));
} else {
alert("Select a row first");
}
});
Thanks.
You have an odd mix of native javascript and jQuery. You can use the :checked selector to get the chosen radio button, then get the closest tr and read the text of each td within that row. Try this:
$(document).ready(function () {
$('#reqtablenew tr').click(function () {
$('#reqtablenew tr').removeClass("active");
$(this).addClass("active").find('input[name="reqradio"]').prop('checked', true);
});
$("#edireq").button().click(function () {
var $ele = $('input[name="reqradio"]:checked');
if ($ele.length) {
var $tds = $ele.closest('tr').find('td');
var id = $tds.eq(1).text();
var requestor = $tds.eq(2).text();
// and so on..
alert(id);
alert(requestor);
}
else {
alert("Select a row first");
}
});
});
Example fiddle
Try this:
var list = ["Req id","Requestor","Approver","Status","Product","Version","Source","Destination"]; //list of title
if (flag > -1) {
$(".active").find("td:gt(0)").each(function(i){
console.log(list[i]+": "+$(this).text());
});
}
Fiddle here.
I came up with the following:
http://jsfiddle.net/Gz668/16/
$(document).ready(function () {
$("table").on("click", "tr", function(){
$(".active").removeClass("active");
$(this).toggleClass("active");
$(this).find("input[type='radio']").prop("checked", true);
});
$("#edireq").on("click", function(){
activeRow=$(".active");
cells=activeRow.children();
if(cells.length >0){
row={
select:cells[0],
requestId:cells[1],
requestor:cells[2],
approver:cells[3],
status:cells[4],
product:cells[5],
version:cells[5],
source:cells[6],
destination:cells[7]
};
alert(row.requestor.textContent);
}
})
});

How to remove all element except one?

I would like to remove all element from my canva except the one on which I click.
I create a set, put all element inside and remove the set :
button.click(function () {
var to_remove = paper.set();
paper.forEach(function (el) {
to_remove.push(el);
});
to_remove.remove();
});
But i don't success to test if my element is my button or not.
Axel
You can simply cache your clicked element and compare it during the loop.
button.click(function() {
var clickedEl = this,
toRemove = paper.set();
paper.forEach(function(el) {
if (el !== clickedEl) {
toRemove.push(el);
}
});
toRemove.remove();
});​
Demo: http://jsfiddle.net/yRNNe/

Categories