Pass js var into html block being added via appendTo - javascript

I've got this html which i'm injecting into the page when someone clicks a button. The html gets appended again each time the button is clicked using the js below.
<div style="display: none;">
<div class="grab-me">
<p>This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
});
});
But what i need to do is where it says "This is fieldset 1" i need to increase that number by 1 each time so subsequent appends say This is fieldset 2, This is fieldset 3 etc etc. I can't see how i can pass a variable (my count var) in to the html block when it gets cloned that will replace that number.
Here is a jsfiddle of it: http://jsfiddle.net/tzbgA/
Any help would be great! Thanks!!

you can give the sentence you want to change class. Then using jQuery selectors change the text inside it.
<body>
<button class="add-member">add more</button>
<div style="display: none;">
<div class="grab-me">
<p class="count">This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
<div id="register">
</div>
</body>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register')
.find('p.count').html('This is fieldset '+count);
count += 1;
});
});

add span:
<p>This is fieldset <span>1</span></p>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
$('.span').html('count');
});
});

var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me').clone();
$(grab p).html('This is fieldset '+count).appendTo('#register');
});
});

Fiddle: http://jsfiddle.net/howderek/tzbgA/2/
Here's a version that uses 8 lines of code:
Code (Javascript)
var count = 1,
html = ' <p>This is fieldset #</p><input name="foo[]"/> <input name = "bar[]"/> <input name = "oth[]"/>';
$(function () {
$('.add-member').live("click", function (e) {
e.preventDefault(e);
document.getElementById("register").innerHTML += html.replace("#",++count);
});
});

Related

Unable to delete row using jquery which was dynamically created

I am creating new rows using jquery and want to delete that row when delete button is pressed. Adding new row part is working fine and the problem is in delete part. When I click on delete button then nothing happens. It doesn't even show alert which is written in code. It seems to me like delete button is not even getting pressed.
How can I delete that particular record when delete button is pressed?
JSfiddle is given below
https://jsfiddle.net/ec2drjLo/
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow">
</div>
As you have added the elements as a string, they are not valid HTML elements and that's why you can't add an event listener. You can add the click event to the document body and capture the event target, like
$(document).on('click', function (e){
if(e.target.className === 'deleteClass'){
//process next steps
}
}
You can try the demo below, not sure if it's the result you need, but the delete button works. Hope it helps!
let accountCount = 0;
$("#addAccount").click(function (e)
{
accountCount++;
let mystring = "<label class=\"ok\" id=\"[ID]\">[value]</label>";
let deleteString = "<button class=\"deleteClass\" id=\"deleteAccount"+ accountCount +"\">Delete Account</button>";
let currency = mystring.replace("[ID]", "currency"+ accountCount).replace("[value]", $("#currencyMain").val());
let amount = mystring.replace("[ID]", "amount"+ accountCount).replace("[value]", $("#amountMain").val());
$("#transactionRow").append(currency);
$("#transactionRow").append(amount);
let div = document.createElement('div');
div.innerHTML =deleteString;
$("#transactionRow").append(div);
$("#currencyMain").val('');
$("#amountMain").val('')
});
$(document).on('click', function (e)
{
if(e.target.className === 'deleteClass'){
var content = $("#transactionRow").html();
var pos = content.lastIndexOf("<label class=\"ok");
if(pos > 5)
$("#transactionRow").html(content.substring(0,pos));
else
alert("You cannot delete this row as at least one Account must be present");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow" style="border: 1px solid grey">
</div>

jquery : how to toggle div after using search function on it?

I'm using a search function to highlight text (function 2) in different chapters. In parallel most of this text is stored in div called content to ease reading. You can toggle these div to read the text (function 1).
When text is found by function 2, it's no longer possible to toggle the text in this chapter. I suppose this is related to use of "this" in function 1 (If I delete this it works) or handlers (if I add live in front of click in function 1 it works but live is deprecated and remplacement "on" is not working).
// function 1 : toggle content when clicking the button
$(".chapter button").on('click',function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
console.log(id)
$('#' + id + '+*').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
console.log(str);
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
// but i want to highlight all occurences of the word in this chapter ? how can I define index d ?
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
$(this).html($(this).html().replace(strCut[i], '<font color="red">$&</font>'));
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
The problem was your $(this).html(). The .replace that you did removes the event listener of your button, because it modifies the DOM. Instead of getting the whole .html(), I did it with .children(), and then replaced just the text of it.
About replacing all the occurrences of the chapter word, you could use a Regular Expression. Using a string will replace just the first occurrence of the string. With the regular expression you can replace all of them.
// function 1 : toggle content when clicking the button
$(".chapter button").click(function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
$('#' + id + '+*').closest('.content').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
var regex = new RegExp(strCut[i],"g")
$(this).children().each(function (index,element) {
const text = $(element).html().replace(regex,'<font color="red">$&</font>')
$(element).html(text)
})
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1 and the second ocurrence of chapter also highlighted
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
EDIT
I wasn't clear enough about the errors, sorry, and I've noticed the right solution.
The point is that, instead of modifying the parent element, I've changed the text of the childrens. When you change the whole html, you remove the listener of your buttons when you add it again to the html, and that's why isn't possible to toggle the divs.

How to sum a number in sequence after click a button?

$(document).ready(function(){
var current = 0;
current += 4;
$('.add').click(function(){
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
i want to sum a number in sequence after click the add button like the above snippet, so the results will be 4 8 12 16 18 and so on. Teach me how to do this ?
Try this: Your increment should be in the click function as well. SO the increment actually occurs when you click, if it's outside, it won't occur.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
You have to increment in click handler. Right now it is getting incremented only once.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
You need to move the line current += 4; to inside the click function . so only you can increment the value on click .otherwise you will get 4 for every click.
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
Move count inside click function.
$(document).ready(function() {
var current = 0;
$('.add').click(function() {
current += 4;
$('.box').html(current);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div class="box">
0
</div>
Try this:
The key is to grab the current value, add 4 to it and then replace that value with the new sum.
$(document).ready(function(){
$('.add').click(function(){
var existing = parseInt($("#result").text());
$('.box').text(existing + 4);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div id ="result" class="box">
0
</div>
Try this one. Get the box value and next check value is numeric if true then add 4 and bind value in div.
$('.add').click(function () {
var current = $('.box').text();
if ($.isNumeric(current))
$('.box').html(parseInt(current)+4);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">add</button>
<div id ="result" class="box">
0
</div>
Move Current variable inside the click function..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var current = 0;
$('.add').click(function(){
current += 4;
$('.box').html(current);
});
});
</script>
<button class="add">add</button>
<div class="box">
0
</div>
working example
It is very simple, you just need to use loop and a array variable. set limit according to your requirement.
<html>
<body>
<script type="text/javascript">
$(document).ready(function(){
var current = 0;
var c=0;
var res = [];
$('.add').on('click', function(){
for (c = 0; c < 3; c=c+1){
current += 4;
res[c] = current
$('.box').html('&nbsp'+res);
}
});
});
</script>
<button class="add">add</button>
<div class="box">
</div>
</body>
</html>

html checkbox list that shows and hides links when filtered

I have written code that creates a checkbox list where when i click the checkbox below my list of options i would like a link to show underneath that the user can click (show/hide) I cannot figure out why my code will not work. If the user unchecked the box the link disappears but nothing happens when i click my check boxes. I would like to do this fix in JQuery
<!DOCTYPE html>
<html>
<div class ="container">
<head></head>
<body>
<input id="grp1" type="checkbox" value="group_1" onClick="http://google.com" />
<label for="grp1"> group 1 </label>
<div>
<input id="grp2" type="checkbox" value="group_2" onClick="http://google.com" >
group_2</label>
</div>
</body>
</html>
You'll have to use javascript to hide/show the wanted elements in html. There are many approaches to this. The most basic one would be something like
<!DOCTYPE html>
<html>
<body>
<div id="container">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("container").onclick = function (e) {
//check every box if it's checked
if (document.getElementById('grp1').checked) {
document.getElementById('url1').style.display = 'block';
} else {
document.getElementById('url1').style.display = 'none';
}
if (document.getElementById('grp2').checked) {
document.getElementById('url2').style.display = 'block';
} else {
document.getElementById('url2').style.display = 'none';
}
}
</script>
</body>
</html>
Of course you can use different approaches like creating the element in javascript then adding it to the html if you don't like the idea if existing hidden elements. You might also use loops to loop through checkbox element and simply show/hide the url accordingly. And more to make the code flexible on any number of boxes. Something like this
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="checkBoxContainer">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
</div>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("checkBoxContainer").onclick = function (e) {
var linkNumber = 1; //This is number of the first url element with ud url1
var containerChildren = document.getElementById("checkBoxContainer").children;
//loop through the children elements
for (var i = 0; i < containerChildren.length; i++) {
var oneChild = containerChildren[i]; //catch only one child in a variable
//simply filter the input elements which are of type checkbox
if(oneChild.tagName === "INPUT" && oneChild.type === "checkbox"){
//Show or hide the url accordingly.
if (oneChild.checked) {
document.getElementById('url' + linkNumber++).style.display = 'block';
} else {
document.getElementById('url' + linkNumber++).style.display = 'none';
}
}
}
}
</script>
</body>
</html>
The onclick HTML attribute doesn't work that way. The attribute value is executed as javascript. You can make a js function to show/hide the link.
Hi you want to try this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.group-link{
display: block;
}
.hidden{
display: none;
}
</style>
</head>
<body>
<div class="jsParent">
<label for="grp1">
<input id="grp1" type="checkbox" value="group_1" onchange="showLink(this)"/> group 1
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/dogs-101/videos/the-doberman">Group 1 Link</a>
</div>
<div class="jsParent">
<label for="grp2">
<input id="grp2" type="checkbox" value="group_2" onchange="showLink(this)"/> group_2
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/cats-101/videos/ragdoll">Group 2Link </a>
</div>
<script type="text/javascript">
function showLink(el){
var parent = el.parentElement.parentElement;
var linkEl = getAnchorEl(parent);
if(linkEl){
if(el.checked){
linkEl.classList = linkEl.classList.value.replace('hidden', '');
}else{
linkEl.classList = linkEl.classList.value + ' hidden';
}
}
}
function getAnchorEl(parent){
var childrens = parent.children;
var linkEl = null;
for (var i = 0; i < childrens.length; i++) {
var childEl = childrens[i];
if(childEl.classList.value.indexOf('jsLink') > -1){
linkEl = childEl;
break;
}
}
return linkEl;
}
</script>
</body>
</html>
Your question is undoubtedly a duplicate but I am answering because I would like to help you identify issues with the code you posted.
I notice you have a <div>tag between your tag and tag. Why? This is a bit of an over simplification but as a general rule never put anything between your <html> and <head> tag and only place <div> tags inside your <body> tag. Also be mindful of how you nest your elements. That tag starts after and before .
Even if that were correct placement you close the before you close your div arbitrarily in the middle of your body tag. you should never have
<div>
<p>
</div>
</p>
Instead it should look like this
<div>
<p>
</p>
</div>
In your onClick attribute you have a random URL. That will not open a new window. You new too put some javascript in there.
<input onClick="window.open('http://google.com')">
Also your second label tag does not have an opening, just a </label> close tag
To answer your question - I suggest you look at the jQuery toggle function.
<input type="checkbox" id="displayLink" />
Google
<script type="text/javascript">
$("#displayLink").click(function(){
$("#googleLink").toggle();
});
</script>
As a general rule you should favor event handlers (such as the $("").click() posted above) to handle events (like clicking) as opposed to html attributes such as onClick.

JQuery Adding the values of 2 divs into a third div

I have 3 divs with numbers in each...
<div id="one">1</div>
<div id="two">5</div>
<div id="total">0</div>
What I need to do for example is:
If #one is click then Add the values of #one and #two and update it on #total
So, in the case above total would look like this:
<div id="total">6</div>
HTML:
<div id="one">1</div>
<div id="two">5</div>
<div id="total">0</div>
<input id="btn-calculate" type="button" value="Calculate" />
JavaScript:
var one = document.getElementById('one'),
two = document.getElementById('two'),
total = document.getElementById('total');
document.getElementById('btn-calculate').onclick = function() {
total.innerHTML = parseInt(one.innerHTML) + parseInt(two.innerHTML);
};
Demo
$('#one').click(function(){
$("#total").text(
parseFloat($(this).text()) +
parseFloat($("#two").text())
);
});
​$("#one")​.click(function(){
$("#total").html(parseInt($(this).text()) + parseInt($("#two").text()))
})​
http://jsfiddle.net/daniilr/G4Snm/
Try this,
Live Demo
$("#one").click(function() {
$('#total').text(parseFloat($('#one').text()) + parseFloat($('#two').text()));
});​

Categories

Resources