Add new classname for element onclick() - javascript

This is my code in jsfiddle:
http://jsfiddle.net/qn7JG/1/
function go_to(lat,lon,hinttext,balloontext,event){
var domElement =$(event.target);
domElement.addClass('selected');
console.log(domElement);
return false;
}
I'm want to add new classname, when I click by link.
How I can do it?

EDITED
I was in hurry on last post an I forget the most important addClass :)))
I hope you get the clue with jquery data params.
After a lot of testing I find a solution for you
html:
<div id="res">
<a href="" class="ff" data-lat="123 " data-long="321 " data-hinttext="some hit text !" data-ballon="balloontext" >textr123</a>
</div>
js:
$('.ff').live('click', function(e) {
e.preventDefault();
var lat = $('.ff').data('lat');
var long = $('.ff').data('long');
var hinttext = $('.ff').data('hinttext');
var balloontext = $('.ff').data('ballon');
alert(lat + long + hinttext + balloontext);
$(this).addClass('selected');
return false;
});
});
and the DEMO IS HERE

Try this
$(element_id).addClassName(newClassName);
It will simply Add the class name.It won't remove the previous class name.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).click(function(event) {
var text = $(event.target.nodeName).selector;
$(text).addClass("newclass");
});
</script>
<style>
.newclass{
color: #00ff00;
}
</style>
<p>hello</p>
<input type="text" id="amount"/>

Related

Change text of element for each element that have the same class in jQuery

So, I'm trying to only show certain part of the text. The info is passed like this. Ex: ["PS4"] and I only want the PS4 text to show so I did this with jQuery:
var text = $('.gender').text();
var text2=text.substring(text.indexOf('"')+1,text.lastIndexOf('"'));
$('.gender').text(text2);
The problem is that I want to change every single element text that have .gender class but only having their corresponding text, like so:
["PS4"]["XBOX"]
<div class="gender">PS4</div><div class="gender">XBOX</div>
I tried to do it with .each() function but I got something like this:
<div class="gender">PS4"]["XBOX</div><div class="gender">PS4"]["XBOX</div>
Here's the code with jQuery .each():
$('.gender').each(function(){
var text = $('.gender').text();
var text2=text.substring(text.indexOf('"')+1,text.lastIndexOf('"'));
$('.gender').text(text2);
});
EDIT:
I have an HTML with this:
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
So I want to remove the '[""]' from every element that have .gender class so it shows like this:
<div class="gender">PS4</div>
<div class="gender">XBOX</div>
Use $(this) and not $(".gender")
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.substring(text.indexOf('"') + 1, text.lastIndexOf('"'));
$(this).text(text2);
});
demo
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.substring(text.indexOf('"') + 1, text.lastIndexOf('"'));
$(this).text(text2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
You may go for RegEx, with $.text(callback)
$(function() {
$('.gender').text(function() {
return $(this).text().replace(/^\[\"(.*)\"\]$/, '$1');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
Breakup of, ^\[\"(.*)\"\]$ as below:
^ starts with
(.*) group having any match of any length
$ ends with
Try this one also:
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.replace("\"]", "");
text2 = text2.replace("[\"", "");
$(this).text(text2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>

JQuery: How to add a class to certain lines in textarea and display the modified textarea?

So what I am trying to do is:
-> Get contents from textarea (input by user) (var entered).
-> Split each line by \n and store them in a variable (var lines).
-> Use a for loop to iterate through all lines and add class (.modify) to the lines that does not contain characters [\u3400-\u9FBF]. Other lines stays the same.
-> Store all lines in a new container (div class="new_text) and display it.
Here is what I have so far:
<!--DOCTYPE html-->
<html>
<head>
<style>
textarea {
width: 650px;
min-width:650px;
max-width:650px;
height:650px;
min-height:650px;
max-height:650px;
}
.modify {
color : red;
}
</style>
<script>
$(document).ready(function() {
$("#test").click(function(){
var i;
var entered = $('#textInput').val();
var lines = entered.split('\n');
res = "";
for(i=0;i<lines.length;i++){
if (lines[i].match(/[\u3400-\u9FBF]/)) {
res = lines[i];
$(".new_text").append(res);
} else {
res = lines[i];
$(".new_text").append(res).addClass("modify");
}
}
});
});
</script>
</head>
<body>
<div class="container">
<form role="form">
<div class="userInput">
<label for="textInput">Input Here:</label>
<textarea class="form-control" rows="40" id="textInput"></textarea>
</div>
<button type="button" class="btn btn-Warning" id="test">Test</button>
</form>
<div class="new_text"></div>
</div>
</body>
</html>
This however does not change anything from the original textarea input, any idea what is wrong? or is this not an acceptable way to accomplish what I am trying to do? Thanks in advance!
For the item which doesn't contain the required condition, you need to wrap the text inside an element in order to apply a css class.
for(i=0;i<lines.length;i++){
if (lines[i].match(/[\u3400-\u9FBF]/))
{
res = lines[i];
$(".new_text").append(res);
}
else
{
res = lines[i];
$('<p/>',{
text: res,
'class': 'modify'
}).appendTo('.new_text');
}
}
Here's the working example : https://jsfiddle.net/DinoMyte/6x80vabm/10/
Ditto to the first answer. You can only add a class to proper HTML.
Also, inside of the modify selector, you have color = red;. That's invalid CSS. It should be color: red;.
Another problem I noticed is that there is no button with id="test", so there's nothing that will actually trigger the test click handler.
Your problem with all the text going red is because you're adding the "modify" class to ".new_text" and not to your new element.
You need to call append with valid HTML. A line of text won't be sufficient. Try this:
$(".new_text").append(
$("<p>" + res + "</p>").addClass("modify")
);

Access inner text using $(this) with jQuery

I have a button and I want to log the inner text using the jQuery when that button is clicked. I know how to use the id to get the text of the buttton ($("#testID").text()), but that's not an option for me. I would like to use the $(this) keyword instead of the id, but I'm not sure how to do that.
The html:
<button id="testID" onclick="getButtonText()">Button Text</button>
The javascript:
function getButtonText() {
console.log("this text = " + $(this).text()); //not working
}
Pass in this
The html:
<button id="testID" onclick="getButtonText(this)">Button Text</button>
The javascript:
function getButtonText(self) {
console.log("this text = " + $(self).text()); //not working
}
Otherwise, this will be the window object
You need to pass the caller element to the function...
function getButtonText(element) {
var $this = $(element);
console.log("this text = " + $this.text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="testID" onclick="getButtonText(this)">Button Text</button>
Though the proper jQuery way of doing it would be like this...
$('#testID').on('click',function() {
console.log("this text = " + $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="testID">Button Text</button>
You can give it a class on the button and then whenever a class is click, it will determine the DOM, which is $(this). Example:
In your html file:
<button id="testID" class="test-btn">Button Text</button>
In your script file:
$(document).ready(function () {
$(".test-btn").click(function(){
$("#message").text("The Text is: " + $(this).text() );
});
});
See my example on Plunker: http://plnkr.co/edit/e94QraQfCOzGlkirvTJj?p=preview

How to define a method and attribute to my appended div?

I have DIVs dynamically appended to the DOM. I want each of them to have some method, like when I click a button inside the div, the div will be removed from the DOM; and some attributes that I can read from.
So I figure I need an object, but this is what confuses me:
var block = tmpl('added_video_thumb', data);
$('#wrapper').append(block);
I want the block to be the object, so I did this:
var blocks = function(id, data){
this.block = tmpl('added_video_thumb', data);
}
And I changed the code to this:
var block = new blocks('added_video_thumb', data);
$('#wrapper').append(block);
Then I don't know how to define the method, I don't want to call a function like:
$('#delete').click(function(){
block.remove();
})
What I want is when I do this:
var block = new blocks();
It takes care of everything. Please help me construct this blocks object.
If I understand your problem, it is that you want to dynamically create an element and assign methods to it's own children.
HTML
<button id="add">Add</button>
<div class="container">
</div>
JS
function addBlock() {
var div = $( '<div class="inner_div">
<button class="delete">Delete</button>
</div>' );
div.children('button.delete').on( 'click', function() {
$(this).parent().remove();
});
$('.container').append(div);
}
Example on fiddle : http://jsfiddle.net/wyXxn/1/
​
You can check the following fiddle
HTML Code
<input type="text" placeholder="ID" id="id-input" />
<input type="text" placeholder="data" id="data-input" />
<button id="add-div">Add Div</button>
<div id="wrapper">
</div>​
JS Code
$(function(){
var block = function(id, data) {
this.id = id;
this.data = data;
$("#wrapper").append('<div id="' + id + '">'+ data +'<br /> <button id="del-' + id + '">Delete Me!</button> </div>');
$("#del-"+id).click(function() {
$("#"+id).remove();
});
}
$("#add-div").click(function() {
var newBlock = new block($("#id-input").val(), $("#data-input").val());
});
});​

Ordering elements by number in JQuery

how could I arrange the following div's by the value in the attribute amount with jquery? Thanks.
<a href="#" id="id1" class="lTest" amount="12">
<div>abcd1</div>
<a/>
<a href="#" id="id2" class="lTest" amount="64">
<div>abcd2</div>
<a/>
<a href="#" id="id3" class="lTest" amount="32">
<div>abcd3</div>
<a/>
<a href="#" id="id4" class="lTest" amount="8">
<div>abcd4</div>
<a/>
This one should work.
<!doctype html>
<html>
<head>
<script src='jquery.js'></script>
<script>
$(document).ready(init);
function init() {
var parent = $('#someid');
var children = $('a', parent);
children.sort(function(a, b) {
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
})
$.each(children, function(i, child) {
parent.append(child);
});
}
</script>
</head>
<body>
<div id="someid">
<div>abcd2</div>
<div>abcd4</div>
<div>abcd3</div>
<div>abcd1</div>
</div>
</body>
</html>
[Edit] Replaced by a SSCCE to prove it's working. I've changed x in abcdx to the expected ordering. You should end up with abcd1, abcd2, abcd3 and abcd4 in this order.
Try this:
var links = $('a.lTest').sort( function(a,b) { return $(a).attr('amount') - $(b).attr('amount'); } );
for ( var i = 1; i < links.length; i++ ) {
links.eq(i-1).insertBefore( links.eq(i) );
}
first, assume the tags are surrounded by a div (id ="testDiv")
Sorry, my initial way of doing this is wrong...
DO NOT DO THIS: BROKEN!!! (See edit below)
var testDiv = $('#testDiv');
var children = testDiv.children('.lTest');
children.each(function() {$(this).remove();});
var testArray = $.makeArray(children);
testArray.sort(function(a,b){
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount');
});
children.each(function() {testDiv.append(this);});
EDIT: THIS IS WORKING VERSION:
var testDiv = $('#testDiv');
var children = testDiv.children('.lTest').remove();
children = children.sort(function(a,b){
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
});
testDiv.append(children);
Your first comment on Tinister's answer indicates that your test page doesn't know anything about JQuery. Make sure you are properly including JQuery in your tests and that the HTML is correctly constructed. Then you will probably find that one of the other answers works.
John

Categories