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.
Related
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']
I am currently working on a project that utilizes an input to create a list of items. I have the addition of programs working, however the deletion of an item is where I am having problems.
The items are added to an array via .push() and the method of deletion is via the .splice() method. The function correctly splices the correct array element but ends up doing a second pass and deleting the elements before it. How do I stop the splice from happening more than once?
$(skill_add_button).click(function(e){ //on add input button click
var skill_input=document.getElementById("skill_input").value;
document.getElementById("skill_input").value = "";
e.preventDefault();
if(s < 12){ //max input box allowed
if (skill_input==""){
skillset = skill_arr.join('');
alert(skillset);
} else {
s++; //text box increment
$(skill_wrap).append('<div class="skill_tag" id="skill_tag'+s+'">'+skill_input+'</div>'); //add input box
skill_arr.push(skill_input+'|s|');
alert(skill_arr);
$('.skill_tag').hover(function(){
$(this).css("background-color", "#C14330");
$(this).css("cursor", "pointer");
}, function(){
$(this).css("background-color", "#04CA29");
});
$('.skill_tag').click(function() {
var skill_id = $(this).attr('id');
var index = skill_id.split('skill_tag').pop();
skill_arr.splice(index,1);
$('#'+skill_id).remove();
alert(skill_arr);
s--;
});
}
}
if(s > 11) {
$(skill_add_button).remove();
}
});
If I try to put my .skill_tag click function outside of my skill_add_function, it does not work at all.
Each time you click on $(skill_add_button) you create a new div.skill_tag but and you add .click event on ALL .skill_tag elements of the page.
Save your generated div into a var and use this var to add click event.
var myDiv = '<div class="skill_tag" id="skill_tag'+s+'">'+skill_input+'</div>';
$(skill_wrap).append(myDiv); //add input box
[...]
myDiv.hover(function(){
[...]
myDiv.click(function(){
$('body').on('click','.skill_tag',function(){
//TODO::add code here
})
I want to create DOM elements with info taken from input type text. To be more specific:
I want the user to be able to write a location and after he presses "Go!" button an element to be created with the text inserted and I also want to have a delete icon which when pressed to delete that insert.
I created a function in which I took the input value but I cannot create the 'del' button
If I create another <img> inside using the same method, when I create the second entry it will put another <img> to the previous entry
search_btn.click(function() {
var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i;
var search_value = search_box.val();
var final_result = search_value.trim();
if (place_reg.test(final_result)) {
createDest(final_result);
} else {
alert('Please insert a valid destination');
}
document.getElementById('search_box').value = "";
});
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){ return txt.charAt(0).toUpperCase() +
txt.substr(1).toLowerCase();});
}
function createDest(value) {
var destination_i_search = document.createElement("div");
destination_i_search.innerHTML = toTitleCase(value);
destination_i_search.setAttribute("class" , "place");
$("#dest").append(destination_i_search);
}
It is very difficult to understand what you wish it to do, without a full example, but from comments you may want something like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/s6hn0n18/6/
I have converted it to use jQuery where appropriate.
var search_btn = $('#search');
var search_box = $('#searchbox');
search_btn.click(function () {
var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i;
var search_value = search_box.val() || "";
var final_result = search_value.trim();
if (place_reg.test(final_result)) {
createDest(final_result);
} else {
alert('Please insert a valid destination');
}
search_box.val("");
});
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
function createDest(value) {
// use a div container
var div = $("<div/>");
div.html(toTitleCase(value));
div.addClass("place");
// If you want to replace the previous entry
$("#dest").append(div);
var del = $('<input class="delete" type="button" value="X"/>');
$("#dest").append(del);
}
// This is a delegated event handler, attached to a non-changing ancestor
$(document).on('click', '.delete', function(){
// Remove the previous div (if of class place)
$(this).prev('.place').remove();
// Remove the delete button too
$(this).remove();
});
The key is to add a delegated event handler for the delete buttons. These work by listening for the specified event (click in this case) bubbling up to a non-changing ancestor. It the applies the jQuery selector. It the calls the function for any matching element that caused the event. The default ancestor is document if nothing closer to the changing content is available. In this case you could use #dest
e.g.
$('#dest').on('click', '.delete', function(){
I've written a custom form validation script, but for some reason, wrapping input[type=text] elements in <div class="inputWrapper" /> stops me from preventing input[type=submit]'s default setting.
Here's the relevant code:
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
Is breaking:
$("input[type=submit]").click(function(event) {
event.preventDefault();
});
Why is this happening? If you need a more full script, let me know, and I'll just post the whole thing.
Alright, so for some reason, disabling that line of code allows .preventDefault on the input[type=submit] to work, but if I just use
// wrap inputs
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
// validate on form submit
$("input[type=submit]").click(function(event) {
event.preventDefault();
});
It works fine. So here's the full script, what could cause this weirdness?
$(document).ready(function() {
// wrap inputs
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
$("textarea").wrap("<div class=\"inputWrapper\" />");
// validate text inputs on un-focus
$("input[type=text].required").blur(function() {
if ($(this).hasClass("error")) {
// do nothing
} else if ($(this).val() === "") {
$(this).addClass("error");
$(this).parent(".inputWrapper").append("<div class=\"errorPopup\">" + $(this).attr("placeholder") + "</div>");
}
});
// validate textareas on un-focus
$("textarea.required").blur(function() {
if ($(this).hasClass("error")) {
// do nothing
} else if ($(this).val() === "") {
$(this).addClass("error");
$(this).parent(".inputWrapper").append("<div class=\"errorPopup\">" + $(this).attr("placeholder") + "</div>");
}
});
// validate on form submit
$("input[type=submit]").click(function(event) {
event.preventDefault();
// check fields
$(this).parent("form").children("input.required").each(function() {
// check textboxes
if ($(this + "[type=text]")) {
if (!$(this).val()) {
$(this).addClass("error");
};
};
// end textboxes
// check textareas
$(this).parent("form").children("textarea.required").each(function() {
if (!$(this).val()) {
$(this).addClass("error");
};
});
// end textareas
// check checkboxes and radio buttons
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var inputName = $(this).attr("name");
if (!$("input[name=" + inputName + "]").is(":checked")) {
var inputId = $(this).attr("id");
$("label[for=" + inputId + "]").addClass("error");
};
};
// end checkboxes and radio buttons
});
// end fields
// submit form
var errorCheck = $(this).parent("form").children(".error").length > 0;
if (errorCheck == 0) {
$(this).parent("form").submit();
} else {
alert("You didn't fill out one or more fields. Please review the form.");
window.location = "#top";
};
// end submit form
});
// clear errors
$("input.required").each(function() {
// clear textboxes
if ($(this + "[type=text]")) {
$(this).keypress(function() {
$(this).removeClass("error");
$(this).next(".errorPopup").remove();
});
};
// end textboxes
// clear textareas
$("textarea.required").each(function() {
$(this).keypress(function() {
$(this).removeClass("error");
$(this).next(".errorPopup").remove();
});
});
// end textareas
// check checkboxes and radio buttons
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var inputName = $(this).attr("name");
var labelFor = $(this).attr("id");
$(this).click(function() {
$("input[name=" + inputName + "]").each(function() {
var labelFor = $(this).attr("id");
$("label[for=" + labelFor + "]").removeClass("error");
});
});
};
// end checkboxes and radio buttons
});
// end clear textbox errors
});
Alright, I was wrong about what the problem was. It's related to the line I thought it was, but it's actually having an issue finding the .error after I wrap the inputs.
Here's where the problem lies:
var errorCheck = $(this).parent("form").children(".error").length > 0;`\
var errorCheck = $(this).parent("form").children(".error").length > 0;
When you .wrap the text inputs, they are no longer children of the form. Use .find
By the way, $(this + "selector") is not valid. You probably want to use $(this).is("selector")
You will need some sort of reference maintained with the new DOM element. This would be placing it as an initialised DOM element in a variable first (not as a string as you did) and the same for the original element, which will be placed back in to maintain the event:
var $inputWrapper = $("<div class=\"inputWrapper\" />"),
$inputText = $("input[type=text]");
$inputText.wrap("<div class=\"inputWrapper\" />");
Then you can replace the element back in.
I have a bunch of radio buttons that are below. These radio buttons are part of a larger form and are optional, so If a user clicks on one, then decides he/she doesn't want the option selected, there is no way to undo this.
I was wondering if there was any jQuery etc, that, when clicking a link for example, clear any radio selection, based on the group name in the HTML?
Thanks
var group_name = "the_group_name";
// if jquery 1.6++
$(":radio[name='" + group_name + "']").prop('checked', false);
// prev than 1.6
// $(":radio[name='" + group_name + "']").attr('checked', false);
Working demo: http://jsfiddle.net/roberkules/66FYL/
var Custom = {
init: function() {
checkAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and click it
$(container).find('input[type=checkbox]:not(:checked)').each(function(){
if($.browser.msie){
$(this).attr('checked','checked');
}else{
$(this).trigger('click');
};
});
};
uncheckAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and unselect them
$(container).find('input[type=checkbox]:checked').each(function(){
$('label[for="'+$(this).attr('id')+'"]').trigger('click');
if($.browser.msie){
$(this).attr('checked','');
}else{
$(this).trigger('click');
};
});
};
I have created it in an init function, and adter then i called the init.
}
window.onload = Custom.init;
I have created a solution like roberkules' solution, except mine clears the radiobutton if you click the radiobutton itself while it's checked. Use this if you don't want to add an extra "Clear" button to your layout.
http://jsfiddle.net/P9zZQ/6/
// Requires JQuery 1.4+ (possibly earlier)
$(function () {
// Turn off a radiobutton if clicked again while on
var checkOff = function (event) {
var target = $(event.target);
if (target.is('label')) {
// deal with clicked label
if (target.attr('for')) {
// label has 'for' attribute
target = $('#' + target.attr('for'));
} else {
// label contains a radiobutton as a child
target = target.find('input[type=radio]');
}
}
if (target.is('input:checked[type=radio]')) {
event.preventDefault();
window.setTimeout(function () {
target.attr('checked', false);
}, 200);
}
}
// Find all radiobuttons and labels inside .radio-clearable containers
$(
'.radio-clearable input[type=radio], ' +
'.radio-clearable label').mousedown(function (event) {
// When clicked -- clear if it was checked
checkOff(event);
}).keydown(function (event) {
// When receiving space, escape, enter, del, or bksp -- clear if it was checked
if (event.which == 32 || event.which == 27 || event.which == 13 || which == 46 || which == 8) {
checkOff(event);
}
});
});
Usage: For any radiobutton you want to be clearable in this manner, wrap it in a container with class "radio-clearable".
The code is triggered by clicking or sending a key (Space, Escape, Enter, Del, BkSp) to the radiobutton element or to its label.