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

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());
});
});​

Related

Appending HTML inputs using JavaScript gives "undefined" value

I have a small code trying to append values using HTML inputs to the same document.
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
<script type="text/javascript">
var child = document.getElementById("text").value;
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para' + toString(child) + '</p>');
}
</script>
the variable child dose not take the text value from the input, which outputted as `undefined'
image 1: typed Test
Image 2: Clicked the Button
how to get the value form the input as New ParaTest?
Code Edited using the answer.
You don't need toString() method, remove it.
Get the reference of element in the child variable and get the value the func()
var child = document.getElementById("text");
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para: ' + child.value + '</p>');
}
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
child variable needs to assign inside func function and don't need toString()
try this
function func(){
var h = document.getElementById('myh');
let child = document.getElementById("text").value;
h.insertAdjacentHTML('afterend','<p> New Para' + child + '</p>');
}
<html>
<body>
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
</body>
</html>
Your variable should be global. Try taking it inside the function and then check it.
function func(){
var child = document.getElementById("text").value;
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend','<p> New Para' + toString(child) + '</p>');
}

script not executing for appended data but executing for prewritten html code inside form, also script is already loaded in top of page

i have a code where i on click on #add it appends some html which have unique class name with them. The code is appended something like this
<script>
var x = 1;
$("#add").click(function() {
$("#form").last().append('<input name="item' + x + '" placeholder="name" type="text" class="jj' + x + '"/><input type="text" class="xx' + x + '" name="some' + x + '">');
x = x + 1;
});
</script>
Also i have scripts written for these classes already loaded at starting of the page
<script>
var npp = "something";
$(document).ready(function() {
//o
$(".jj").click(function() {
$(".xx").val(npp);
});
//1
$(".jj1").click(function() {
$(".xx1").val(npp);
});
//2
$(".jj2").click(function() {
$(".xx2").val(npp);
});
//3
$(".jj3").click(function() {
$(".xx3").val(npp);
});
});
</script>
in console it shows no error, but also the script isn't executing for the elements added by append function, also the script is being executed for first element already present in html inside form.
<form id="form" action="..." method="post">
<input type="text" name="item" class="jj">
<input type="text" name="some" class="xx">
</form>
<button id="add">Add new field</button>
My actual is somewhat different but the basic functioning/logic is same. Kindly advice why my script isn't working.
Here is a good answer explaining your problem: Read it here with examples
And I quote:
Because those are dynamically added elements to the existing HTML, so
you need to delegate it using on event
handler attachment with the document.
so instead of:
$(".jj").click(function(){
$(".xx").val(npp);
});
do:
$("body").on('click' , '.jj', function () {
$(".xx").val(npp);
});
And so on...
Instead of using .click function use on to be applied on any elements you add to your html code.
Example:
$("body").on('click' , '.jj2' , function(){
$(".xx2").val(npp);
});

replace set of strings in array

Using $('div#top_container').html(), I get the following as an example:
<div class="top" id="top_container">
<div class="example">First</div>
<div class="example">Second</div>
</div>
giving...
<div class="example">First</div>
<div class="example">Second</div>
Here, using .replace(), I want to replace <div class="example"> with *%^% (random set of characters) and remove </div>:
var content = $('div#top_container').html();
var clean_1 = content.replace('<div class="example">','*%^%'); //add $*!#$
var clean_2 = clean_1.replace('</div>',' '); //remove </div>
giving...
console.log(clean_2); --> *%^%First*%^%Second
Now, the number of example div elements can vary and I need to first find out how to target them all. Also is there a cleaner way to target both <div class="example"> and </div> at the same time?
EDIT:
I am not looking to change the html itself, but rather have the edited version as a variable that I can do stuff with (such as send it to php via ajax).
How would I do this?
Use replaceWith() method with a callback and generate prefered text string by getting text content using text() method.
$('div.example').replaceWith(function(v) {
return '%^%' + $(this).text();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="example">First</div>
<div class="example">Second</div>
</div>
UPDATE: If you don't want to update the original element then use clone() and do the remaining thinks on the cloned element.
var res = $('#parent')
// clone element
.clone()
// get element with `example` class
.find('.example')
// update content
.replaceWith(function(v) {
return '%^%' + $(this).text();
})
// back to previos selector and get html content
.end().html();
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="example">First</div>
<div class="example">Second</div>
</div>
Create one prototype like :
String.prototype.replaceAll = function (toReplace, replaceWith){
return this.split(toReplace).join(replaceWith);
}
and your jquery code be like :
$("div#top_container").each(function( i ) {debugger;
console.log(this.innerHTML.replaceAll('<div class="example">','*%^%').replaceAll('</div>',' ');)
});
You can use replaceWith function
$(function () {
$(".example").replaceWith(function(){
return "%^%"+$(this).text();
});
});
You can make a clone of container if you don't want to change original div.
var html="";
$(function () {
var newHtml = $("#top_container").clone();
$(newHtml).find(".example").replaceWith(function () {
html+= "%^%" + $(this).text();
});
});
console.log(html);

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

Add new classname for element onclick()

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"/>

Categories