jQuery function that will remove specific word on click - javascript

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/

Related

Cannot read property 'split' of undefined

Im facing a problem here when im trying to split class attribute like that
<div class='message_holder user1212 chatid142'></div>
so from my function i want to get user id (1212) and chatid ( 142)
But im getting the error in my tittle
how can i fix that pls.
function user_chat_id(){
classList = $(this).attr("class").split(/\s+/); //----here im getting the error
$.each(classList, function(index, item) {
if (item.indexOf("user") > -1) {this_id = item;}
if (item.indexOf("chatid") > -1) {this_chat_id = item;}
});
this_id = this_id.replace('user', '');
this_chat_id = this_chat_id.replace('chatid', '');
return [this_id,this_chat_id];
}
Edit :
and when i call it
$(document).on ("mouseenter", ".message_holder", function () {
var this_id = user_chat_id();
alert(this_id);
})
Why your code is not working.
$(this) will be current window. In that .attr("class") will be undefined. So when you try to split it will throw an error.
Demo for showing $(this) will be current window.
$(document).ready(function(){
$("p").click(function(){
a()
});
});
function a(){
console.log($(this))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on this paragraph.</p>
Soluton
Pass the current element as an argument to the function.
Changes to be made
var this_id = user_chat_id($(this)); //While calling.
function user_chat_id(elem){ // in function definition
You should use elem instead of $(this)
Demo for showing how to pass the element with it
$(document).ready(function(){
$("p").click(function(){
a($(this))
});
});
function a(elem){
console.log(elem)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on this paragraph.</p>
The problem with your current code is that the value of this in your function is undefined (if in strict mode) or set to the global context (if not in strict mode) because it's just a regular function call. So, $(this).attr("class") will just return undefined and then when you try to do .split() on it, you get the error you see.
I'd suggest a much cleaner implementation that uses a regex to get the numbers for you:
function getId(str, key) {
var regex = new RegExp("\\b" + key + "(\\d+)\\b");
var match = str.match(regex);
return match ? match[1] : null;
}
function user_chat_id(obj){
var classList = obj.className;
var userId = getId(classList, "user");
var chatId = getId(classList, "chatid");
return [userId, chatId];
}
$(document).on ("mouseenter", ".message_holder", function () {
var this_id = user_chat_id(this);
alert(this_id);
});
In addition, the HTML you show:
<div class='message_holder user1212 chatid142></div>
is missing a closing quote on the class attribute. It should be:
<div class='message_holder user1212 chatid142'></div>
Working demo:
function getId(str, key) {
var regex = new RegExp("\\b" + key + "(\\d+)\\b");
var match = str.match(regex);
return match ? match[1] : null;
}
function user_chat_id(obj){
var classList = obj.className;
var userId = getId(classList, "user");
var chatId = getId(classList, "chatid");
return [userId, chatId];
}
$(document).on ("mouseenter", ".message_holder", function () {
var this_id = user_chat_id(this);
alert(this_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='message_holder user1212 chatid142'>Put the mouse over this text</div>

how collect random id in jquery with .on('click')

At the moment i have a list of elements and when clicked on one of them
it will get the number accordingly. However i need a different approach
that won't count the number of elements but returns the id number of that
specific element.
http://jsfiddle.net/FN4fy/
$('#outputData').on('click', 'li.element', function() {
var num = $('#outputData li.element').index(this);
alert(num);
var loc = window.location + "";
var pos = loc.indexOf('#');
if (pos > -1) {
loc = loc.substring(0, pos);
};
loc = loc + '#ti' + num;
window.location = loc;
});
try this
$('#outputData li').click(function() {
var idOfLi = $(this).attr('id');
alert(idOfLi);
// rest of your code
});
and this is jsfiddle
$(this).attr("id") will give the current element id, because event binded to li.
$('#outputData').on('click', 'li.element', function() {
window.location += $(this).attr("id") ;
});
Javascript:
JSFiddle with ti
JSFiddle without ti
jQuery
JSFiddle With ti
JSFiddle - Without ti
Answer
You can use this.id if you want ti#, or this.id.substring(2) if you just want the number.
You can also use
window.location += "#"+this.id.substring(2);
If you want to go to the location on the current page.
Here is the jsFiddle
$('#outputData').on('click', 'li.element', function() {
var num = $(this).attr('id');
alert(num); // returns id
});
In case you want to fetch the number alone, then
$('#outputData').on('click', 'li.element', function() {
var num = parseInt($(this).attr('id').match(/\d+$/),10);
alert(num); // returns number
});

Changing an element type using jquery

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 () {

Adding number to p.value

Here's the fiddle. I'm trying to make it so when you press the button, it adds 1 to #num.
JS:
$(document).ready(function () {
$('#b').button({
icons: {
secondary: '.ui-icon-triangle-1-n'
}
});
$('#b').click(function () {
var x = '#num'.value;
var u = x + 1;
document.getElementById('#num').innerHTML = u;
});
});
Try this .It should work
$(document).ready(function () {
$('#b').button({
icons: {
secondary: '.ui-icon-triangle-1-n'
}
});
$("#b").click(function () {
var x = parseInt($('#num').html());
var u = x + 1;
$('#num').html(u);
});
});
Assuming the first part is working somehow (not sure what "button" is), try this:
$('#b').click(function () {
var x = $('#num').text();
var u = parseInt(x) + 1;
$('#num').html(u);
});
var x = Number($('#num').text());
You are not retrieving the value the correct way. Try the above
$(document).ready(function () {
$('#b').button({
icons: {
secondary: '.ui-icon-triangle-1-n'
}
});
$(this).click(function () {
// var x = '#num'.value;
var x = $('#num').html();
var u = parseInt(x) + 1;
document.getElementById('#num').innerHTML = u;//why not use $('#num').html(u);
});
});
you can try this .
Here's a fiddle using jQuery's data function to store and increment the value:
http://jsfiddle.net/nyhpt/3/
There are several mistakes:
'#num'.value is not valid. You should use $('#num') to get the jQuery nodes
if you'd like to use document.getElementById, that should be document.getElementById('num'). Note there's no leading '#'
to get or set HTML content in tags like p, div, span, use .innerHTML (for DOM nodes) or .html() (for jQuery nodes); to get input value from input, textarea, use .value (for DOM nodes) or .val() (for jQuery nodes)
any value or HTML content in a node is a string, so you'd better change it into a number via parseInt (Javascript allows you add a string to an integer, but that's actually a string concatenate)
I'd like to change your codes in this way:
$(this).click(function () {
var x = parseInt($('#num').html());
var u = x + 1;
document.getElementById('num').innerHTML = u;
});

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/

Categories