I have a span tag and a button tag
<span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
I want to append more span tag with new class from this array with increment value by clicking button.
Like this output:
<span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
i try `
this JsFiddle
But i can not add class name to new append tag from array.
Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here
value increaseesenter code here this snippet
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
another attempt...anyone can help.. to get desire output
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;
$("#add").click( function() {
(i < elements.length){
$(".new-field").append('<span class="myspan">1</span><script');
var value = parseInt($(".myspan").text(), 10) + 1;
elements[i].className += ' ' + backgrounds[i%len];
i++;
$(".background").text(i);
}
});
*/
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt used convert ths string to number
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var len = backgrounds.length;
$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
$(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
})
console.log($(".new-field").html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
Check the fiddle. Hope this helps!
HTML :
<div id="mainContainer">
<span class="myspan">1</span>
</div>
<button id="add">Add +1</button>
JS :
var arr = ["myspan1", "myspan2", "myspan3", "myspan4"];
$("#add").on("click", function() {
var spans = $("span");
var classList = [];
$.each(spans, function() {
var elemCls = $(this).attr('class').length > 1 ? $(this).attr('class').split(' ') : $(this).attr('class');
if (elemCls) {
$.each(elemCls, function() {
classList.push(this.toString());
});
}
});
$.each(arr, function(i, e) {
if ($.inArray(e, classList) == -1) {
$("#mainContainer").append("<span class='" + e + "'>" + parseInt(spans.length + 1) + "</span>");
return false;
}
});
});
Related
I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>
getting no errors but trying to loop through all the inputs and add them all to the total (var = paidTotal). The first input works but the rest don't when others are added with an add button. Something wrong with the loop?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = document.getElementById('check').value;
var personsCheck = document.getElementById('personsCheck').value;
var paidTotal = document.getElementById('paidTotal');
for(var i = 1; i < personsCheck.length; i+=1){
personsCheck[i] += paidTotal;
}
paidTotal.innerHTML = checkTotal - personsCheck;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
make it as class
<input type="text" class="personsCheck" name="person">
and access it by
var personsCheck = document.getElementsByClassName('personsCheck');
ids have to be unique. You'll only get one element from document.getElementById().
Try using a class instead, something like
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
and use document.getElementsByClassName('persons') to get an array of all of the input fields that have that class.
Your code logic is not something what you want to achieve.
I can not find any logic to use the input element with id=personsCheck.
First of all, you are appending input element with same id again and again which is invalid, because in a document id attribute must be unique. Use class attribute instead.
To get the total you can first get the elements with querySelectorAll(), theb use forEach() to loop through all of them to add one by one.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = Number(document.getElementById('check').value);
var persons = document.querySelectorAll('.persons');
var personsCheck = Number(document.getElementById('personsCheck').value)
var paidTotal = document.getElementById('paidTotal');
var total = 0;
persons.forEach(function(p){
total += Number(p.value);
});
paidTotal.textContent = checkTotal - total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
I have this jquery code where everytime i hit "btn_add" i get 3 new textfields (usd_value, pesos_value and percent )...i want to add a change event to all usd_value texts so when they change, pesos_value of all items change their values for =usd_value * percent.Im tryiing to do the delegation at the end of code but it's not working :
<script type="text/javascript" src="jquery-2.1.4.js" charset="UTF-8" ></script>
<script type="text/javascript">
$(document).ready(function(){
var obj = $('input[name="percent"]').length;
var n = 0;
$('#btn_add').click(function(){
n++;
$('table').append('<tr id="btn_minus'+n+'"><td><input type="text" name="cost_element" value="0" readonly/></td><td><input type="text" name="description" value="{{cost_element.description}}"/></td><td><input type="text" id="id_usd_value" name="usd_value" value="{{cost_element.usd_value}}"/></td><td><input type="text" id="id_pesos_value" name="pesos_value" value="{{cost_element.pesos_value}}"/></td><td><input type="text" size= 3 id="id_rer_value" name="percent" value="{{cost_element.percent}}"/>%</td><td><input class="btn_minus btn btn-danger" name="btn_minus'+n+'" type="button" value="X"/></td></tr>');
obj = $('input[name="percent"]').length;
});
$('table').on('click',".btn_minus",function(){
var id = $(this).attr('name');
$('tr[id="'+id+'"]').remove();
});
$('.btn_delete').click(function(){
location.href = "";
});
setInterval(function(){
var percents = new Array();
$('input[name="percent"]').each(function() {
percents.push($(this).val());
});
var sum = 0;
for(var i=0, l=percents.length; i<l; i++) {
sum = sum + parseInt(percents[i],10);
}
$('#msgValidar').empty();
if(sum == 100){
$('#msgValidar').append('<h5 style="color: blue">Los valores de procentaje estan correctos.</h5>');
$('#btn_ok').removeClass('disabled');
}else{
if(obj != 0){
$('#msgValidar').append('<h5 style="color: red">Los valores de procentaje deben sumar exactamente 100%.</h5>');
$('#btn_ok').addClass('disabled');
}
}
}, 500);
$('table').on('change','.usd_value',function(){
alert('work!');
});
});
</script>
Can you help me ?? Thanks !!
There are many errors in your code. First of all, you can't add dinamically more object with the same ID, and then refer to the objects by ID, the ID must be unique. You closed wrong the parenthesis too. And the change event is not wrong, but in your "append", you isn't setted the class, but "name" and "ID" TAG, and the reference ".usd_value" is a class selector...
Try this, but you must correct the rest of your code:
<script type="text/javascript">
$(document).ready(function() {
var n = 0;
$('#btn_add').click(function() {
n++;
$('table').append('<tr id="btn_minus' + n + '"><td><input type="text" name="cost_element" value="0" readonly/></td><td><input type="text" name="description" value="{{cost_element.description}}"/></td><td><input type="text" id="id_usd_value" name="usd_value" class="usd_value" value="{{cost_element.usd_value}}"/></td><td><input type="text" id="id_pesos_value" name="pesos_value" value="{{cost_element.pesos_value}}"/></td><td><input type="text" size= 3 id="id_rer_value" name="percent" value="{{cost_element.percent}}"/>%</td><td><input class="btn_minus btn btn-danger" name="btn_minus' + n + '" type="button" value="X"/></td></tr>');
});
$('table').on('click', ".btn_minus", function() {
var id = $(this).attr('name');
$('tr[id="' + id + '"]').remove();
});
$('.btn_delete').click(function() {
location.href = "";
});
$('table').on('change', '.usd_value', function() {
alert('work!');
$('#id_pesos_value').val() = $('#id_usd_value').val() * $('#percent').val();
// in this last line you have wrong the assignment and you can't refer to ID
// change with class like ".id_usd_value" etc...
});
});
//}); <-- this is too much !
</script>
This is your code corrected on JSFiddle
I want to call myfunc() using the id button, how I do that?
I dont want to use nothing but the id to call this function..what code I need to add in my script?
<html>
<head>
<script>
function myfunc() {
var count = 0;
var line = 0;
var i = 0;
var phrase = document.getElementById('phrase').value;
var filter = document.getElementById('filter').value;
var arr = phrase.split(" ").reverse();
for (i = 0; i < arr.length; i++) {
if (arr[i].search(filter) == -1) {
if (line % 2 == 0) {
document.getElementById('words').innerHTML += " <u><span class='word' style='background:#D8D8D8; border:1px solid black; ' >
" + arr[i] + "</span></u>";
line++;
} else {
document.getElementById('words').innerHTML += " <span class='word' style='background:#D8D8D8; border:1px solid black; '>
" + arr[i] + "</span>";
line++;
}
}
if ((arr[i].search(filter) != -1) && (filter)) {
count++;
}
}
document.getElementById('count').innerHTML = count + " word(s) filtered out";
}
</script>
</head>
<body>
<h1>Sentence Reverser!</h1>
<div>Phrase:
<input id="phrase" type="text" size="40" />
</div>
<div>Filter:
<input id="filter" type="text" size="10" />
</div>
<div>
<button id="go">Go!</button>
</div>
<div id="words"></div>
<div id="count"></div>
</body>
</html>
You can add the following
document.getElementById('go').onclick = myfunc
After the element has loaded. In practice this means below the element, or in the head within a window loaded event.
You can use addEventListener() to attach the function on particular event inside the window.onload, something like this.
window.onload = function (){
document.getElementById('go').addEventListener('click', myfunc);
function myfunc(){
//your all code be here
}
}
DEMO
To be as short as possible, you can add this script after the HTML, or in the document load event:
go.onclick = myfunc
But this is far from best practice. A better practice would be to add an onclick attribute to your button:
<button id="go" type="button" onclick="myfunc()"> Go! </button>
I have a requirement in which I had to add a duplicate of the existing fieldset in a form. I'm able to achieve the cloning process successfully. But I'm not able to change the name and id of the filedset elements. It is the same as the first fieldset but I want it to be with a different name and id to differentiate it(even adding a number at the end would be fine). Below are my js and fieldset.
<div id="placeholder">
<div id="template">
<fieldset id="fieldset">
<legend id="legend">Professional development</legend>
<p>Item <input type ="text" size="25" name="prof_itemDYNID" id ="prof_item_id"/><br /></p>
<p>Duration <input type ="text" size="25" name="prof_durationDYNID" id="prof_duration_id" /><br /></p>
<p>Enlargement <label for="enlargement"></label><p></p>
<textarea name="textareaDYNID" cols="71" rows="5" id="prof_enlargement">
</textarea></p>
<p><input type="button" value="Add new item" id="add_prof" onclick="Add();" /></p>
</fieldset>
</div>
</div>
function Add() {
var oClone = document.getElementById("template").cloneNode(true);
document.getElementById("placeholder").appendChild(oClone);
}
Also, this is just a sample fieldset and it will be different as well. I heard that this can be done using regex but not sure how to do it. Please help.
Not sure this could be achieve using regex, but somewhat following code should work...
var copyNode = original.cloneNode(true);
copyNode.setAttribute("id", modify(original.getAttribute("id")));
document.body.appendChild(el);
Here comes the best(as per my assumption) answer to the above problem..
function addMe(a){
var original = a.parentNode;
while (original.nodeName.toLowerCase() != 'fieldset')
{
original = original.parentNode;
}
var duplicate = original.cloneNode(true);
var changeID= duplicate.id;
var counter = parseInt(changeID.charAt(changeID.length-1));
++counter;
var afterchangeID = changeID.substring(0,changeID.length-1);
var newID=afterchangeID + counter;
duplicate.id = newID;
var tagNames = ['label', 'input', 'select', 'textarea'];
for (var i in tagNames)
{
var nameChange = duplicate.getElementsByTagName(tagNames[i]);
for (var j = 0; j < nameChange.length; j++)
{if (nameChange[j].type != 'hidden'){
var elementName = nameChange[j].name;
var afterSplitName = elementName.substring(0,elementName.length-1);
nameChange[j].name = afterSplitName + counter;
var elementId = nameChange[j].id;
var afterSplitId = elementId.substring(0,elementId.length-1);
nameChange[j].id = afterSplitId + counter;
}
}
}
insertAfter(duplicate, original);
}
function insertAfter(newElement, targetElement)
{
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
{
parent.appendChild(newElement);
}
else
{
parent.insertBefore(newElement, targetElement.nextSibling);
}
}