How to make divs names always be 1,2,3 jQuery - javascript

My issue is that when i append 2 divs white jQuery, there names are:
This is div 1
This is div 2
But when i remove the first div (This is div 1)
and append another div
it adds one more div whit name (This is div 2):
This is div 2
This is div 2
The reason is because the name of the div counts the total amout of divs... Is there any other way to number all divs so they will always be like this:
This is div 1
This is div 2
This is div 3
Even if i the divs are:
This is div 1
This is div 6
This is div 12
I want them always to be 1,2,3
jQuery code:
$('#add_item').click(function() {
//div count
var countDivs = $("div").length;
//append content
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div '+countDivs+'</h2>')
var appendContent = ('<div>'+h2+removeBtn+'</div>')
$('#accordion').append(appendContent);
});
//remove button
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
return false;
});
JSFIDDLE

I think you'll have to edit contents of the divs each time a div is removed.
Let's say you have an element and you want to add divs to it.
You will add like you are right now and when you remove you edit all other divs.
The code would be something like this
$('#add_item').click(function() {
var countDivs = $("div").length;
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div '+countDivs+'</h2>')
var appendContent = ('<div class="appDiv">'+h2+removeBtn+'</div>')
$('#accordion').append(appendContent);
});
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
$('.appDiv').each(function(index,el){
$(el).find('h2').text('This is div '+(index+1));
});
return false;
});
here is the Fiddle
Hope this helps :)

Write a function to renaming the divs and call it after append/remove.
function reArrange() {
$("#accordion > div").each(function(i) {
$(this).find("h2").text("This is div" + (i + 1))
});
}
Fiddle

When an item is removed, change the title of all the elements after it.
$('#add_item').click(function() {
var countDivs = $("#accordion div").length + 1;
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div <span>' + countDivs + '</span></h2>')
var appendContent = ('<div>' + h2 + removeBtn + '</div>')
$('#accordion').append(appendContent);
});
$(document).on('click', '.removeBtn', function() {
var $div = $(this).parent();
$div.nextAll('div').find('span').html(function(i, html) {
return --html
});
$div.remove();
return false;
});
div {
position: relative;
}
#accordion {
margin-left: 60px;
padding: 10px;
background: #ddd;
}
#add_item {
position: absolute;
top: 20px;
left: 20px;
font-size: 20px;
padding: 5px 10px;
background: black;
color: white;
cursor: pointer;
}
.removeBtn {
font-size: 20px;
padding: 2px 10px 5px;
background: black;
color: white;
cursor: pointer;
position: absolute;
top: 0px;
font-family: verdana;
border-radius: 100%;
left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="accordion">
</div>
<a id="add_item">+</a>

you should use a global variable like "count":
var count=1;
$('#add_item').click(function() {
//div count
//var countDivs = $("div").length;
var countDivs =count;
//append content
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div '+countDivs+'</h2>')
var appendContent = ('<div>'+h2+removeBtn+'</div>')
$('#accordion').append(appendContent);
count++;
});
//remove button
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
return false;
});

The easiest update would be to trigger a recount (or other named-event) and, upon addition or removal of an element – by clicking either the #add_item or .removeBtn – call that function using the on() method to listen for that event.
In the below code we bind the event-listener to the #accordion element, as the closest ancestor present in the DOM on page load:
$('#add_item').click(function() {
var removeBtn = ('<a class="removeBtn">x</a>');
var h2 = ('<h2></h2>');
var appendContent = ('<div>'+h2+removeBtn+'</div>');
$('#accordion').append(appendContent).trigger('recount');
});
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
// triggering the 'recount' event from the
// #accordion:
$('#accordion').trigger('recount');
return false;
});
// listening for the 'recount' event:
$('#accordion').on('recount', function(){
// looking within the #accordion for
// the <h2> elements (which contain the
// text to update), and using the text()
// method's anonymous function along with
// its i argument (the index of the current
// <h2> in the collection):
$(this).find('h2').text(function(i){
// returning the text string concatenated
// with the index plus 1 (to get a 1-based
// count, rather than JavaScript's 0-based):
return 'This is div ' + (i + 1);
});
});
$('#add_item').click(function() {
var removeBtn = ('<a class="removeBtn">x</a>');
var h2 = ('<h2></h2>');
var appendContent = ('<div>' + h2 + removeBtn + '</div>');
$('#accordion').append(appendContent).trigger('recount');
});
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
$('#accordion').trigger('recount');
return false;
});
$('#accordion').on('recount', function() {
$(this).find('h2').text(function(i) {
return 'This is div ' + (i + 1);
});
});
div {
position: relative;
}
#accordion {
margin-left: 60px;
padding: 10px;
background: #ddd;
}
#add_item {
position: absolute;
top: 20px;
left: 20px;
font-size: 20px;
padding: 5px 10px;
background: black;
color: white;
cursor: pointer;
}
.removeBtn {
font-size: 20px;
padding: 2px 10px 5px;
background: black;
color: white;
cursor: pointer;
position: absolute;
top: 0px;
font-family: verdana;
border-radius: 100%;
left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="accordion">
</div>
<a id="add_item">+</a>
References:
on().
text().
trigger().

Related

How to delete the parent node that has the id generated automatically? How to specify that id?

I have created the tree like structure using appendChild() in JavaScript.
When clicking add button a root node gets added. When clicking root node a parent node gets added. When clicking parent node a child node gets added.
Now I am trying to delete that add by adding a small icon. On clicking that icon that particular node need to be deleted.
Now I have tried using delete button. On clicking delete button the root node gets deleted. But only one node is deleted.
function remove_div(){
var A = document.getElementById('test-0');
A.parentNode.removeChild(A);
}
Because I have called only one ID.
How to call that particular id to delete that node.
I have generated the ID dynamically.
div1.id = 'test-' + document.querySelectorAll('.ui-modal > .msg1').length;
how to get the specific id to be deleted.on clicking root node that particular node has to be deleted.Similarly for parent and child node too
function add_div() {
var div1 = document.createElement('ul');
document.body.appendChild(div1);
div1.className = 'ui-modal';
div1.id = 'test-' + document.querySelectorAll('.ui-modal > .msg1').length;
div1.innerHTML = '<li class="msg1" onclick="event.stopPropagation();add_div2(this);">root</li>';
}
function remove_div() {
var A = document.getElementById('test-0');
A.parentNode.removeChild(A);
}
function add_div2(elem) {
var div2 = document.createElement('ul');
elem.appendChild(div2);
div2.className = 'sub-div';
div2.id = 'sub_test-' + document.querySelectorAll('.sub-div > .msg2').length;
div2.innerHTML = '<li class="msg2" onclick="event.stopPropagation();add_div3(this);">parent</li>';
}
function add_div3(elem) {
var div3 = document.createElement('ul');
elem.appendChild(div3);
div3.className = 'inner-sub-div';
div3.id = 'inner_sub_test-' + document.querySelectorAll('.inner-sub-div > .msg3').length;
div3.innerHTML = '<li class="msg3" onclick="event.stopPropagation();">child</li>';
}
.ui-modal {
width: 100px;
border: 1px solid red;
position: relative;
left: 0;
z-index: 55;
}
.sub-div {
margin-top: 10px;
width: 150px;
left: 100px;
border: 1px solid blue;
position: relative;
z-index: 66;
}
.inner-sub-div {
margin-top: 10px;
width: 150px;
left: 250px;
border: 1px solid blue;
position: relative;
z-index: 77;
}
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE" onclick="remove_div();">
</div>
I want to get that specific id of which root is clicked.
I'm not sure if this is what you want:
function add_div(){
var div1 = document.createElement('ul');
document.body.appendChild(div1);
div1.className = 'ui-modal';
div1.id = 'test-' + document.querySelectorAll('.ui-modal > .msg1').length;
div1.innerHTML = '<li class="msg1" onclick="event.stopPropagation();add_div2(this);">root<button onclick="event.stopPropagation();remove_div(this);">-</button></li>';
}
function remove_div(target){
// the div
var A = target.parentNode.parentNode;
A.parentNode.removeChild(A);
}
function add_div2(elem){
var div2 = document.createElement('ul');
elem.appendChild(div2);
div2.className = 'sub-div';
div2.id = 'sub_test-' + document.querySelectorAll('.sub-div > .msg2').length;
div2.innerHTML = '<li class="msg2" onclick="event.stopPropagation();add_div3(this);">parent<button onclick="event.stopPropagation();remove_div(this)">-</button></li>';
}
function add_div3(elem){
var div3 = document.createElement('ul');
elem.appendChild(div3);
div3.className = 'inner-sub-div';
div3.id = 'inner_sub_test-' + document.querySelectorAll('.inner-sub-div > .msg3').length;
div3.innerHTML = '<li class="msg3" onclick="event.stopPropagation();">child<button onclick="event.stopPropagation();remove_div(this)">-</button></li>';
}
.ui-modal{
width: 100px;
border: 1px solid red;
position: relative;
left:0;
z-index: 55;
}
.sub-div{
margin-top: 10px;
width: 150px;
left: 100px;
border: 1px solid blue;
position: relative;
z-index: 66;
}
.inner-sub-div{
margin-top: 10px;
width: 150px;
left: 250px;
border: 1px solid blue;
position: relative;
z-index: 77;
}
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
</div>
Ok basically, you can achieve that easily using jQuery and the .parent() function. You do not need a button, you can have a picture/icon with a class and apply click function on it. This is the code below commented:
//this will add click function to the element with clickToRemove class, it can be any element h1 or image or icon. in this case i used h1 for testing only
$(".clickToRemove").on("click", function(){
// this line basically gets the clicked element parent and remove it.
$(this).parent().remove();
});
Here is a jsfiddle, please let me know if you need more help.
Edit: I left the above jQuery for anyone else who wants to use it. Below is pure Javascript and a new jsfiddle.
//getting all the elements you decided for them to be act like a button
var button = document.getElementsByClassName("removeParent");
//adding a click event to the clicked element
button[0].addEventListener("click", function(){
//the "this" word specifies that only get the clicked element parent
var parent = this.parentNode;
//remove parent
parent.remove();
});
this is the jsfiddle
use a parent div and add everything to it: -
function add_div(){
var div1 = document.createElement('ul');
document.getElementById("sam").appendChild(div1)
div1.className = 'ui-modal';
div1.id = 'test-' + document.querySelectorAll('.ui-modal > .msg1').length;
div1.innerHTML = '<li class="msg1" onclick="event.stopPropagation();add_div2(this);">root</li>';
}
function remove_div(){
var list = document.getElementById("sam");
list.removeChild(list.childNodes[0]);
}
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE" onclick="remove_div();">
</div>
<div id="sam">
</div>

Create multiple textareas in a loop with different ids

I create the checkout page of an eshop and I have a loop in which I display the products that the user has added to the cart. Inside the loop, I display the info for the products I have a text area so the user can choose the quantity of each product. The problem is that the id of each text area must be unique. How can I create many textareas in a loop with different ids?
textarea:
<form name='txtAreaForm' method='GET'>
<textarea disabled name='textArea' id='counter'></textarea>
</form>
Also, I have two buttons (+-) to change the value of the textarea, this is the .js file:
var counter = 1;
// Display total
$("#counter").text(counter);
// When button is clicked
$("#plusButton").click(function(){
counter = counter + 1;
$("#counter").text(counter);
});
//Subtract
$("#minusButton").click(function(){
if (counter>1) {
counter = counter - 1;
$("#counter").text(counter);
}
});
Though the question is not quite clear to me, you can do something like the following:
var counter = 1;
// Display total
$("#counter").text(counter);
var counter = counter + 1;
for(var i=0; i<5; i++){
$("form").append('<textarea name=textArea"+counter+" id=counter"+counter+">1</textarea><input class="plus" type="button" value="+" /><input class="minus" type="button" value="-" /><br>');
}
// When button is clicked
$(".plus").click(function(){
var txtArea = $(this).prev('textarea').text();
$(this).prev('textarea').text(parseInt(txtArea)+1);
});
//Subtract
$(".minus").click(function(){
var txtArea = $(this).prev().prev('textarea').text();
if(txtArea >=2){
$(this).prev().prev('textarea').text(parseInt(txtArea)-1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='txtAreaForm' method='GET'>
</form>
You can use just JavaScript to render a form with as many textareas with its id as necessary and set the actions to each button related to each of them.
See this demo:
(function() {
// Set the plus action on every button with the class name «plus».
function setPlusAction() {
function plus(e) {
var textarea = e.target.previousSibling; // Find the textarea element related to the button clicked.
textarea.value = textarea.value * 1; // Convert the value into number.
textarea.value++; // Increment its value.
}
var elems = document.getElementsByClassName("plus"), i, len = elems.length, button;
for (i = 0; i < len; i++) {
button = elems[i]; // Find the current button.
button.onclick = plus; //Set the «plus» function on every button which has been found.
}
}
// Set the minus action on every button with the class name «minus».
function setMinusAction() {
function minus(e) {
var textarea = e.target.previousSibling.previousSibling; // Find the textarea element related to the button clicked.
textarea.value = textarea.value * 1; // Convert the value into number.
if (textarea.value > 1) {
textarea.value--; // Decrement its value.
}
}
var elems = document.getElementsByClassName("minus"), i, len = elems.length, button;
for (i = 0; i < len; i++) {
button = elems[i]; // Find the current button.
button.onclick = minus; //Set the minus function on every button which has been found.
}
}
// Render a form with the quantity of textareas required.
function buildForm(textareas) {
var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
for (i = 0; i < textareas; i++) {
html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
html += i;
html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
}
html += "</form>";
return html; // Return the html content with the form.
}
/*
1. Render the form with document.getElementById("div").innerHTML = buildForm(50);
2. Once the form is renderd call setPlusAction() function;
3. And call setMinusAction() function;
*/
document.getElementById("div").innerHTML = buildForm(50); // Set 50 textareas.
setPlusAction();
setMinusAction();
})();
#div div {
border: solid 1px #ccc;
margin: 2px;
padding: 2px;
}
button.plus,
button.minus {
cursor: pointer;
}
<div id="div"></div>
Update:
jQuery version:
$(function() {
// Render a form with the quantity of textareas required.
function buildForm(textareas) {
var html = "<form name=\"txtAreaForm\" method=\"GET\">", i;
for (i = 0; i < textareas; i++) {
html += "<div><textarea disabled name=\"textArea\" id=\"textarea";
html += i;
html += "\">1</textarea><button class=\"plus\" type=\"button\">+</button><button class=\"minus\" type=\"button\">-</button></div>";
}
html += "</form>";
return html; // Return the html content with the form.
}
$("#div").html(buildForm(50)); // Render the form with 50 textareas.
$(".plus").on("click", function() {
var texarea = $(this).prev(), value = texarea.val() * 1;
value++;
texarea.val(value);
});
$(".minus").on("click", function() {
var texarea = $(this).prev().prev(), value = texarea.val() * 1;
if (value > 1) {
value--;
texarea.val(value);
}
});
});
#div div {
border: solid 1px #ccc;
margin: 2px;
padding: 2px;
}
button.plus,
button.minus {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div"></div>
Remember: IDs must be unique.
I prefer using a class, because I think it is more clear for the code.
Example: my_set_Of_Text_area.add ('<div><span> Ananas : </span>','</div>');
I prefer using data to made the link with the counting area and the + / - buttons.
$(function() {
class TxtAreaFab {
constructor(Form_ID, TextAreaPrefix, BtPlusClass, BtMinusClass) {
this._ref = 0;
this._TaP = TextAreaPrefix;
this._BtPlus = BtPlusClass;
this._BtMinus = BtMinusClass;
this._$ID = $('#' + Form_ID);
}
add(before, after) {
var elements = before;
this._ref++;
elements += "<textarea disabled id='TxtArea_" + this._ref + "'>1</textarea>";
elements += "<button class=" + this._BtPlus + " data-ref=\"TxtArea_" + this._ref + "\">+</button>";
elements += "<button class=" + this._BtMinus + " data-ref=\"TxtArea_" + this._ref + "\">-</button>";
elements += after;
$(elements).appendTo(this._$ID);
}
/* ----- not used , just here for sample
clear () {
this._$ID.html('');
this._ref = 0;
}
*/
};
var my_set_Of_Text_area = new TxtAreaFab('txtAreaForm', 'zoneTA_', 'ClassBtPlus', 'ClassBtMinus');
my_set_Of_Text_area.add('<div><span> Apples : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Oranges : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Pears : </span>', '</div>');
my_set_Of_Text_area.add('<div><span> Bananas : </span>', '</div>');
$('#txtAreaForm').on('click', "button", function(e) {
e.stopPropagation();
var $txtArea = $("#" + $(this).data("ref")),
v = parseInt($txtArea.val());
if ($(this).hasClass('ClassBtPlus')) $txtArea.val(++v);
if ((v > 1) && ($(this).hasClass('ClassBtMinus'))) $txtArea.val(--v);
return false;
});
my_set_Of_Text_area.add('<div><span> Ananas : </span>', '</div>');
});
#txtAreaForm div {
clear: both;
height: 30px;
}
#txtAreaForm div span {
display: block;
float: left;
width: 120px;
font-weight: bold;
text-align: right;
padding-right: 10px;
}
#txtAreaForm textarea {
display: block;
float: left;
width: 40px;
height: 16px;
font-weight: bold;
text-align: center;
resize: none;
}
<form name='txtAreaForm' id='txtAreaForm' method='GET'></form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Special Fun solution! (but real).
I did it with only 9 lines of JavaScript / jQuery, and a little more in CSS.
And no need for textarea id. (Ok, my 2 "if" statements have only 1 line).
For the HTML part, each text box is placed in a "p" (paragraph), and that's it:
<p><textarea disabled > 1 </textarea></p>
<p><textarea disabled > 2 </textarea></p>
<p><textarea disabled > 3 </textarea></p>
The trick is in the CSS where I use :after and :before like the "+" or "-" buttons.
placed to the right of each box "p".
form p:after {
right: -22px;
content:'+';
...
form p:before {
right: -43px;
content:'-';
In the jQuery part.
I use the relative position of the mouse click to determine whether the operation should be a plus or minus. For the little story: -- $ (this) .outerWidth (); -- Is usefull.
Of course, it would still be better to add an ID on each textarea; but after reflection, it appeared to me that these input fields could be generated at the PHP server (?).
So, strange as it may seem, this solution is very serious. ;)
Everything is in the snippet.
$(function() {
$('form p').click(function(e) {
var
posX = (e.pageX - $(this).offset().left) - $(this).outerWidth();
Sign = (posX > 22) ? "moins" : (posX > 0) ? "plus" : "none",
Valn = parseInt($(this).children('textarea').text());
if (Sign === 'plus') $(this).children('textarea').text(++Valn);
if ((Sign === 'moins') && (Valn > 1)) $(this).children('textarea').text(--Valn);
});
});
textarea,
form,
p,
textarea {
font-family: Tahoma, sans-serif;
font-size: 16px;
}
textarea {
float: left;
width: 40px;
height: 22px;
font-weight: bold;
text-align: center;
resize: none;
line-height: 20px;
}
form p {
box-sizing: border-box;
display: block;
float: left;
clear: both;
position: relative;
border: 0;
margin: 5px 0 0 20px;
padding: 0;
}
form p:before,
form p:after {
position: absolute;
top: 2px;
width: 20px;
height: 20px;
display: block;
color: white;
background-color: darkslategray;
text-align: center;
font-size: 18px;
}
form p:after {
right: -22px;
content: '+';
line-height: 18px;
}
form p:before {
right: -43px;
content: '-';
line-height: 16px;
}
<form name="txtAreaForm" method='GET'>
<p><textarea disabled> 1 </textarea></p>
<p><textarea disabled> 2 </textarea></p>
<p><textarea disabled> 3 </textarea></p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

How can I make an element on hover?

All I'm trying to do is something like this mechanism:
Here is what I've tried so far:
$(document).ready(function(){
$('a').bind('mouseenter', function() {
var self = $(this);
this.iid = setInterval(function() {
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}, 525);
}).bind('mouseleave', function(){
this.iid && clearInterval(this.iid);
});
});
body{
padding: 20px;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: reletive;
width: 130px;
height: 30px;
display:none;
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>tag1</a>
<a>tag2</a>
As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?
Also is what I'm doing a right algorithm for such thing?
Thank you.
I am not sure why you are using setInterval but I think this should work. I removed setInterval and everytime the mouseenter event occurs we can append <div class='tag_info'> and every time mouseleave event occurs we can remove the the appended div.
$(document).ready(function(){
$('#test').bind('mouseenter', function() {
var self = $(this);
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}).bind('mouseleave', function(){
$(this).children('.tag_info').remove();
});
});
body{
padding: 20px;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: reletive;
width: 130px;
height: 30px;
display:none;
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="test">tag1</a>
Like Dij said:
What you're doing:
setInterval - (repeats your function every 525ms)
What you want:
setTimeout - (executes your function once after 525ms delay)
Read more:
setInterval https://www.w3schools.com/jsref/met_win_setinterval.asp
setTimeout https://www.w3schools.com/jsref/met_win_settimeout.asp

how to work with arrays and objects in javascript

I've got an array of cars and i'm looping through each car. I take input from the user using window.prompt() method. I take that value and filter it through my array of cars. I just want to know how I can restrict the car name the user selects to only those in the array
Fiddle : https://jsfiddle.net/qomu1fny/
var CarsWorld = {
cars : ['Honda','toyota','mercedes','jaguar'],
init: function(){
var getData = prompt('Which Car You Wanna Drive','');
for(var i = 0 ; i < this.cars.length ; i++){
$('.wrap').append(' ' + this.cars[i] + ' <br/> ');
}
},
};
CarsWorld.init();
var getData = prompt('Which Car You Wanna Drive','');
var foundCar = "";
for(var i = 0 ; i < this.cars.length ; i++){
$('.wrap').append(' ' + this.cars[i] + ' <br/> ');
//check if this car in the array is the picked car
if(this.cars[i] == getData){
foundCar = getData;
}
}
$('.wrap').append('you picked ' + foundCar);
Note that if the car isn't on the list then it won't output anything. Fiddle here: http://jsfiddle.net/e5qh3pvw/
I've tried to rephrase your question to something more understandable (currently under peer review). I understand you want to have a prompt that will restrict the choices of the user to the car models in your array.
Unfortunately, window.prompt() cannot achieve this, neither is there any synchronous (blocking) way to achieve it. You will need to use a modal dialog, and insert a regular html select element with your choices, or use a group of radio buttons.
I have created a fiddle that started getting bloated as I progressed. I used a few advanced techniques, just to engage your curiousity, since I suspect you are new to javascript.
Javascript:
var CarsWorld = {
cars : ['Honda','toyota','mercedes','jaguar'],
init: function(){
var getData = 'none';
for(var i = 0 ; i < this.cars.length ; i++){
$('.wrap').append(' ' + this.cars[i] + ' <br/> ');
}
var prompter = new CarsWorld.PromptSelect('Which Car You Wanna Drive', function(selected){
getData = selected;
alert('You chose '+ getData +'! ');
//other logic you want to apply on getData
});
prompter.show();
}
};
CarsWorld.PromptSelect = function(message, callback) {
self = this;
this.init = function(){
self.dropdown = '<select id="selectedCar">';
$.each(CarsWorld.cars, function(index, car){
self.dropdown += '<option>' + car + '</option>';
});
self.dropdown += '</select>';
self.markup = [
'<div class="prompt">',
'<div class="title">CarsWorld Prompt</div>',
'<div class="body">',
'<label for="selectedCar">'+ message +':</label>' + this.dropdown + '</div>',
'<div class="footer">',
'<button class="btn-ok">Ok</button>',
'<button class="btn-cancel">Cancel</button>',
'</div>',
'</div>'
].join('');
};
this.show = function(){
$('.overlay').show();
$('body').css('overflow', 'hidden');
self.init();
$('body').append(self.markup);
$('.prompt .btn-ok').on('click', function(){
self.hide();
callback($('#selectedCar').val());
self.destroy();
});
$('.prompt .btn-cancel').on('click', function(){
self.destroy();
});
return self;
};
this.hide = function(){
$('.prompt').hide();
$('.overlay').hide();
$('body').css('overflow', 'auto');
return self;
};
this.destroy = function(){
self.hide();
return self;
};
};
CarsWorld.init();
HTML:
<div class="wrapper">
<h1> Please choose the car of your type </h1>
<div class="wrap"></div>
<div class="overlay"></div>
</div>
CSS:
.overlay {
display: none;
position: absolute;
width: 100%;
height: 100%;
z-index: 990;
background: #444;
opacity: 0.5;
top: 0;
left: 0;
}
.prompt {
display: block;
position: absolute;
z-index: 999;
width: 300px;
height: 200px;
top: 50%;
left: 50%;
margin-left: -200px;
margin-top: -100px;
}
.prompt .title {
background: black;
color: white;
height: 10%;
padding: 10px;
border-radius: 3px 3px 0 0;
text-align: center;
font-weight: bold;
}
.prompt .body {
background: white;
height: 60%;
padding: 20px;
}
.prompt .footer {
background: grey;
text-align: right;
padding: 10px;
height: 10%;
border-radius: 0 0 3px 3px;
}

Event Handlers On Newly Created Elements

I have a web app with a number of textareas and the ability to add more if you wish.
When you shift focus from one textarea to another, the one in focus animates to a larger size, and the rest shrink down.
When the page loads it handles the animation perfectly for the initial four boxes in the html file, but when you click on the button to add more textareas the animation fails to accomodate these new elements... that is, unless you place the initial queries in a function, and call that function from the addelement function tied to the button.
But!, when you do this it queries as many times as you add a new element. So, if you quickly add, say 10, new textareas, the next time you lay focus on any textarea the query runs 10 times.
Is the issue in my design, or jQueries implementation? If the former, how better can I design it, if it is the latter, how can I work around it?
I've tried to chop the code down to the relevant bits... I've tried everything from focus and blur, to keypresses, the latest is on click.
html::
<html>
<head>
<link rel="stylesheet" type="text/css" href="./sty/sty.css" />
<script src="./jquery.js"></script>
<script>
$().ready(function() {
var $scrollingDiv = $("#scrollingDiv");
$(window).scroll(function(){
$scrollingDiv
.stop()
//.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "fast" );
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>boxdforstacks</title>
</head>
<body>
<div class="grid">
<div class="col-left" id="left">
<div class="module" id="scrollingDiv">
<input type="button" value="add" onclick="addele()" />
<input type="button" value="rem" onclick="remele()" />
<p class="display">The value of the text input is: </p>
</div>
</div> <!--div class="col-left"-->
<div class="col-midd">
<div class="module" id="top">
<p>boxa</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxa" ></textarea>
<p>boxb</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxb"></textarea>
<p>boxc</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxc"></textarea>
<p>boxd</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxd"></textarea>
</div>
</div> <!--div class="col-midd"-->
</div> <!--div class="grid"-->
</body>
</html>
<script type="text/javascript" src="boxd.js"></script>
js:
function onit(){
$('textarea').on('keyup change', function() {
$('p.display').text('The value of the text input is: ' + $(this).val());
});
}
$('textarea').on("click",function(){
//alert(this.id.substring(0,3));
if ( this.id.substring(0,3) == 'box' ){
$('textarea').animate({ height: "51" }, 1000);
$(this).animate({ height: "409" }, 1000);
} else {
$('textarea').animate({ height: "51" }, 1000);
}
}
);
var boxfoc="";
var olebox="";
var numb = 0;
onit();
function addele() {
var tops = document.getElementById('top');
var num = numb + 1;
var romu = romanise(num);
var newbox = document.createElement('textarea');
var newboxid = 'box'+num;
newbox.setAttribute('id',newboxid);
newbox.setAttribute('class','tecksd');
newbox.setAttribute('placeholder','('+romu+')');
tops.appendChild(newbox);
numb = num;
onit();
} //addele(), add element
function remele(){
var tops = document.getElementById('top');
var boxdone = document.getElementById(boxfoc);
tops.removeChild(boxdone);
} // remele(), remove element
function romanise (num) {
if (!+num)
return false;
var digits = String(+num).split(""),
key = ["","c","cc","ccc","cd","d","dc","dcc","dccc","cm",
"","x","xx","xxx","xl","l","lx","lxx","lxxx","xc",
"","i","ii","iii","iv","v","vi","vii","viii","ix"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
} // romanise(), turn numbers into roman numerals
css :
.tecksd {
width: 97%;
height: 51;
resize: none;
outline: none;
border: none;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
font-size: 70%;
background: white;
/* box-shadow: 1px 2px 7px 1px #0044FF;*/
}
.tecksded {
width: 97%;
resize: none;
outline: none;
border: none;
overflow: auto;
position: relative;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
font-size: 70%;
background: white;
/* box-shadow: 1px 2px 7px #FFDD00;*/
}
/*#postcomp {
width: 500px;
}*/
* {
#include box-sizing(border-box);
}
$pad: 20px;
.grid {
background: white;
margin: 0 0 $pad 0;
&:after {
/* Or #extend clearfix */
content: "";
display: table;
clear: both;
}
}
[class*='col-'] {
float: left;
padding-right: $pad;
.grid &:last-of-type {
padding-right: 0;
}
}
.col-left {
width: 13%;
}
.col-midd {
width: 43%;
}
.col-rght {
width: 43%;
}
.module {
padding: $pad;
}
/* Opt-in outside padding */
.grid-pad {
padding: $pad 0 $pad $pad;
[class*='col-']:last-of-type {
padding-right: $pad;
}
}
body {
padding: 10px 50px 200px;
background: #FFFFFF;
background-image: url('./backgrid.png');
}
h1 {
color: black;
font-size: 11px;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
}
p {
color: white;
font-size: 11px;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
}
You should use the following:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on("click", "textarea", function () {
event.preventDefault();
alert('testlink');
});
Since the textarea is added dynamically, you need to use event delegation to register the event handler.
Try
$(document).on('click', 'textarea', function() {
// do something
});
The issue is you are binding the textareas only on the page load. I made a JSFiddle with working code: http://jsfiddle.net/VpABC/
Here's what I changed:
I wrapped:
$('textarea').on("click", function () {
//alert(this.id.substring(0,3));
if (this.id.substring(0, 3) == 'box') {
$('textarea').animate({
height: "51"
}, 1000);
$(this).animate({
height: "409"
}, 1000);
} else {
$('textarea').animate({
height: "51"
}, 1000);
}
});
in a function so it looked like this:
function bindTextAreas() {
$('textarea').unbind("click");
$('textarea').on("click", function () {
//alert(this.id.substring(0,3));
if (this.id.substring(0, 3) == 'box') {
$('textarea').animate({
height: "51"
}, 1000);
$(this).animate({
height: "409"
}, 1000);
} else {
$('textarea').animate({
height: "51"
}, 1000);
}
});
}
bindTextAreas();
What this does is it allows you to call this function, bindTextAreas, whenever you create a new textarea. This will unbind all the current events than rebind them. This will make it so your new textarea is has the click handler setup.
An place where this function is called is in the addele function like this:
function addele() {
var tops = document.getElementById('top');
var num = numb + 1;
var romu = romanise(num);
var newbox = document.createElement('textarea');
var newboxid = 'box' + num;
newbox.setAttribute('id', newboxid);
newbox.setAttribute('class', 'tecksd');
newbox.setAttribute('placeholder', '(' + romu + ')');
tops.appendChild(newbox);
numb = num;
onit();
bindTextAreas();
} //addele(), add element
Notice the bindTextAreas(); line near the bottom. This reloads all the click handlers.

Categories

Resources