Changing an element type using jquery - javascript

I have the the following code:
$('#theForm').on('click', 'button', function(e){
var attrs = { };
var str =e.target.id;
var newStr = str.substring(0, str.length-1);
$("#file01b").replaceWith(function () {
attrs.text = $(this).text();
return $("<a />", attrs);
});
var field= document.getElementById(newStr);
field.value= field.defaultValue;
document.getElementById(newStr).style.display = "none";
});
All the code: http://jsfiddle.net/K9eWL/3/
and when I click on the first "Remove File" button it works fine, so I tried to make it automatically, in order it works for all the buttons:
$('#theForm').on('click', 'button', function(e){
var attrs = { };
var str =e.target.id;
var newStr = str.substring(0, str.length-1);
$("#str").replaceWith(function () {
attrs.text = $(this).text();
return $("<a />", attrs);
});
var field= document.getElementById(newStr);
field.value= field.defaultValue;
document.getElementById(newStr).style.display = "none";
});
All the code: http://jsfiddle.net/K9eWL/3/
but it doens't work, where is the error?
Thanks for the help.

How about, instead of:
$("#file01b").replaceWith(function () {
You use:
$("#"+e.target.id).replaceWith(function () {
Check your fiddle, updated.
Note: If the above is fine, then $(e.target).replaceWith(function () { will work as well.

'this.id' also works.
$("#"+this.id).replaceWith(function () {

Related

show() and toggle() not working as expected

b1 hides the image while b2 doesn't show it. Also the toggle function does not work? What is wrong in my code?
$(document).ready(function() {
$(".b1").click(function() {
$("img").hide();
});
$(".b2").click(function() {
$("img").show();
});
});
Without the code it is impossible to give the right answer . If I assume that everything is good with the HTML and CSS , I would do something like this :
$(document).ready(function() {
var imgOne = $(".b1");
var imageTwo = $(".b2");
var imgClass = $(".img-class");
imgOne.on("click",function() {
imgClass.hide();
});
imageTwo.on("click",function() {
imgClass.show();
});
});
You can also add console.log('pass') when you click to see if the functions are even doing something . Like this :
$(document).ready(function() {
var imgOne = $(".b1");
var imageTwo = $(".b2");
var imgClass = $(".img-class");
imgOne.on("click",function() {
console.log('pass hide');
imgClass.hide();
});
imageTwo.on("click",function() {
console.log('pass show');
imgClass.show();
});
});
You should see these prints in the console if everything works ok .
Try it out . Hope this helps :)

Creating a re-usable function in JavaScript

I'm extracting a part of the current button ID and want it to re-use this in several other functions.
How could I make the following section common,
var idRec = $(this).attr("id"),
inp = idRec.substr(4,this.id.length);
So that it could be used in multiple .on('click',) events. Please see the following code and advise,
$(function() {
function studentsRecords(e) {
//do_somehting
}
$(document).on('click', '.studentID', function(e) {
var idRec = $(this).attr("id"),
inp = idRec.substr(2, this.id.length);
//do_something_using_inp
}).on('click', '.admissionID', function(e) {
//do_something_else_using_inp
});
});
$(function() {
function studentsRecords(e) {
//do_somehting
}
function get_id(that){
var idRec = that.id;
var inp = idRec.substr(2,that.id.length);
return inp
}
$(document)
.on('click', '.studentID', function(e) {
var inp = get_id(this);
//do_something_using_inp
})
.on('click', '.admissionID', function(e) {
var inp = get_id(this);
//do_something_else_using_inp
})
})
You can declare inp before click function. http://fiddle.jshell.net/x3xo25vz/

jQuery click inside each loop

I want to loop my click events, to make the code shorter. I might have 30 of these values later on.
My working code
$(document).ready(function () {
var last_click = '';
$("#title").click(function() { last_click = 'title'; });
$("#subtitle").click(function() { last_click = 'subtitle'; });
$("#test").click(function() { last_click = 'test'; });
});
This is how I want it (not working)
My guess is that the each-loop runs on dom ready and then never again and that way the click-event can never be triggered?
$(document).ready(function () {
var last_click = '';
var contents = new Array();
contents = ['title', 'subtitle', 'test'];
$.each(contents , function(index, value){
$("#" + value).click(function() { last_click = value; });
});
});
If there is not solved like I would, I would be thankful for a nice workaround.
I would rather add a class to all elements you want to bind this to, eg class="last-click"
and define the binding once as:
$(".last-click").on('click', function() {
last_click = this.id;
}
If you really wanted to make it shorter, give them all a similar class.
$(document).ready(function () {
var last_click = '';
$(".theclass").click(function() {
last_click = this.id;
});
});
if you have value attribute for your buttons or elements, you can do it:
$(document).ready(function() {
var last_click = '';
$("input").click(function() {
last_click = $(this).attr('value');
alert(last_click);
});
});​
I assumed that you are using "input type="button". Also here is the demo you can see it in action: http://jsfiddle.net/rS2Gb/5/

Toggling two events on one button

I'm trying to add some functionality to be able to edit comments inline. So far it's pretty close, but I'm experiencing issues trying to trigger a second event. It works the first time, but after that, fails.
$(function() {
var $editBtn = $('.js-edit-comment-btn');
var clicked = false;
$editBtn.on('click', $editBtn, function() {
clicked = true;
var $that = $(this);
var $form = $that.closest('.js-edit-comment');
var $commentTextBody = $that.closest('div').find('.js-comment-body');
var commentText = $commentTextBody.text();
var $editableText = $('<textarea />');
if ($that.text() === 'Save Edits') {
$that.text('Saving...').attr('disabled', true);
} else {
$that.text('Save Edits').attr('alt', 'Save your edits');
}
// Replace div with textarea, and populate it with the comment text
var makeDivTextarea = function($editableText, commentText, $commentTextBody) {
$editableText.val(commentText);
$commentTextBody.replaceWith($editableText);
$editableText.addClass('gray_textarea js-edited-comment').width('100%').css('padding', '4px').focus();
};
makeDivTextarea($editableText, commentText, $commentTextBody);
var saveEdits = function($that, $editableText) {
$that.on('click', $that, function() {
if (clicked) {
var comment = $that.closest('div').find('.js-edited-comment').val();
$editableText.wrap('<div class="js-comment-body" />').replaceWith(comment);
$that.text('Edit').attr('alt', 'Edit Your Comment').attr('disabled', false);
$('#output').append('saved');
clicked = false;
return false;
}
});
};
saveEdits($that, $editableText);
return false;
});
});​
jsfiddle demo here
Hiya demo for your working solution: http://jsfiddle.net/8P6uz/
clicked=true was the issue :)) I have rectified another small thing. i.e. $('#output') is set to empty before appending another saved hence text **saved** will only appear once.
small note: If I may suggest use Id of the button or if there are many edit buttons try using this which you already i reckon; I will see if I can write this more cleaner but that will be sometime latter-ish but this should fix your issue. :) enjoy!
Jquery Code
$(function() {
var $editBtn = $('.js-edit-comment-btn');
var clicked = false;
$editBtn.on('click', $editBtn, function() {
clicked = true;
var $that = $(this);
var $form = $that.closest('.js-edit-comment');
var $commentTextBody = $that.closest('div').find('.js-comment-body');
var commentText = $commentTextBody.text();
var $editableText = $('<textarea />');
if ($that.text() === 'Save Edits') {
$that.text('Saving...').attr('disabled', true);
} else {
$that.text('Save Edits').attr('alt', 'Save your edits');
}
// Replace div with textarea, and populate it with the comment text
var makeDivTextarea = function($editableText, commentText, $commentTextBody) {
$editableText.val(commentText);
$commentTextBody.replaceWith($editableText);
$editableText.addClass('gray_textarea js-edited-comment').width('100%').css('padding', '4px').focus();
};
makeDivTextarea($editableText, commentText, $commentTextBody);
var saveEdits = function($that, $editableText) {
$that.on('click', $that, function() {
if (clicked) {
var comment = $that.closest('div').find('.js-edited-comment').val();
$editableText.wrap('<div class="js-comment-body" />').replaceWith(comment);
$that.text('Edit').attr('alt', 'Edit Your Comment').attr('disabled', false);
$('#output').text("");
$('#output').append('saved');
clicked = true;
return false;
}
});
};
saveEdits($that, $editableText);
return false;
});
});​

jQuery function that will remove specific word on click

I have the following information in a div
<div class="list">Abc, Test, Ready</div>
Below the div, I have this additional information
Remove Abc
Remove Test
Remove Ready
I am trying to write a jQuery function that will remove either Abc, Test, Ready (and the comma if necessary) when you click on the relevant remove link.
$('a').click(function() {
var str = $(this).attr("class");
$('.list').text($('.list').text().replace(str,''));
});
http://jsfiddle.net/PUure/
But if you really need commas removed, you need to be a bit more creative:
$('a').click(function() {
var str = $(this).attr("class");
var rgx = new RegExp(str + ',?\\s*');
$('.list').text($('.list').text().replace(rgx,''));
});
http://jsfiddle.net/PUure/4/
Edit: Updated for (lazily) removing trailing commas without regex ;)
Check the fiddle
$(document).ready(function(){
$('a').click(function(){
$('div.list').html($('div.list').html().replace($(this).attr('class') + ', ', '').replace($(this).attr('class'), ''));
});
});
You could do:
$('a').click(function(e){
e.preventDefault();
var word = $(this).attr('class');
var div = $('.list').text();
div = div.replace(word, '');
$('.list').text(div );
});
fiddle here http://jsfiddle.net/sysCc/
$('a').click(function(){
var str = $(this).attr('class');
var obj = $('.list');
var currentText = obj.text();
obj.text(currentText.replace(str,'');
});
or condensed:
$('a').click(function(){
$('.list').text($('.list').text().replace($(this).attr('class'),''));
});
You'd be better off keeping the data in an array, then modifying that array and refreshing your div with the new data.
var data = ["Abc", "Test", "Ready"];
refresh();
$("#Abc").click(function() { remove("Abc") });
$("#Test").click(function() { remove("Test") });
$("#Ready").click(function() { remove("Ready") });
function refresh() {
$("div").text(data.join(", "));
}
function remove(word) {
for(var i = 0; i < data.length; i++) {
console.log(i, data[i], word, data[i] == word);
if (data[i] == word)
data.splice(i, 1);
}
console.log(data);
refresh();
}
http://jsfiddle.net/Xeon06/dHp3b/

Categories