Multiple plus and minus buttons - javascript

I am using - and + buttons to change the number of the text box, I am having troubles dealing with different text fields, here is my code:
var unit = 0;
var total;
// if user changes value in field
$('.field').change(function() {
unit = this.value;
});
$('.add').click(function() {
unit++;
var $input = $(this).prevUntil('.sub');
$input.val(unit);
unit = unit;
});
$('.sub').click(function() {
if (unit > 0) {
unit--;
var $input = $(this).nextUntil('.add');
$input.val(unit);
}
});
button {
margin: 4px;
cursor: pointer;
}
input {
text-align: center;
width: 40px;
margin: 4px;
color: salmon;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=field1>
field 1
<button type="button" id="sub" class=sub>-</button>
<input type="text" id="1" value=0 class=field>
<button type="button" id="add" class=add>+</button>
</div>
<div id=field2>
field 2
<button type="button" id="sub2" class=sub>-</button>
<input type="text" id="2" value=0 class=field>
<button type="button" id="add2" class=add>+</button>
</div>
And here's the DEMO
You can see in the demo that the values change correctly only if you click buttons on the same field, but if you alternate between fields the values don't change properly.

This should be all you need:
$('.add').click(function () {
$(this).prev().val(+$(this).prev().val() + 1);
});
$('.sub').click(function () {
if ($(this).next().val() > 0) $(this).next().val(+$(this).next().val() - 1);
});
By using the unit variable you were tying both inputs together. And the plus in +$(this) is a shorthand way to take the string value from the input and convert it to a number.
jsFiddle example

You're using the same variable to hold the values of your two inputs. One simple option would be to use two variables instead of one:
var unit_1 = 0;
$('#add1').click(function() {
unit_1++;
var $input = $(this).prev();
$input.val(unit_1);
});
/* Same idea for sub1 */
var unit_2 = 0;
$('#add2').click(function() {
unit_2++;
var $input = $(this).prev();
$input.val(unit_2);
});
/* Same idea for sub2 */
and unit = unit just assigns the value of unit to itself, so that's no very useful and you can certainly leave it out.

An alternative approach is to use data attributes and have each element store its own value. Edit: it already stores its own value. Just access it.
var total;
// if user changes value in field
$('.field').change(function() {
// maybe update the total here?
}).trigger('change');
$('.add').click(function() {
var target = $('.field', this.parentNode)[0];
target.value = +target.value + 1;
});
$('.sub').click(function() {
var target = $('.field', this.parentNode)[0];
if (target.value > 0) {
target.value = +target.value - 1;
}
});
button {
margin: 4px;
cursor: pointer;
}
input {
text-align: center;
width: 40px;
margin: 4px;
color: salmon;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=field1>
field 1
<button type="button" id="sub" class=sub>-</button>
<input type="text" id="1" value=0 class=field>
<button type="button" id="add" class=add>+</button>
</div>
<div id=field2>
field 2
<button type="button" id="sub2" class=sub>-</button>
<input type="text" id="2" value=0 class=field>
<button type="button" id="add2" class=add>+</button>
</div>

Related

independent elemants onclick, same class name vanila js

i want to have multiple elements with same class that act independently, after 1 night of seeking if "forEach" has any 'forEach:active' i end up with code below, but i feel kind of little shame with 'nextSibling of parent of parent' but if is supported by atleast any modern browsers, then is better than nothing.
on codePen is working fine,as well as snippet here.
i wonder if i can find a better version in vanila js for it or if is there anything deprecated that i should change.
//get + button
const up = document.querySelectorAll('.up');
//tell to + to increase his previous frend value
[].forEach.call(up, function(element) {
element.addEventListener('click', function() {
this.previousElementSibling.value =
parseInt(this.previousElementSibling.value) + 1;
});
})
//get -
const down = document.querySelectorAll('.down');
//tell to - to decrease his next frend value && and hide
//dynamic
//input if == 0 && show firstAdd button
[].forEach.call(down, function(element) {
element.addEventListener('click', function() {
this.nextElementSibling.value =
parseInt(this.nextElementSibling.value) - 1;
if (this.nextElementSibling.value == 0) {
this.parentElement.parentElement.style.display = 'none';
this.parentElement.parentElement.nextElementSibling.style.display = 'initial';
}
});
})
//get firstAdd button
const fAdd = document.querySelectorAll('.firstAdd');
//tell to it to add dynamic input && to vanish itself after &&
//set input value = 1
[].forEach.call(fAdd, function(element) {
element.addEventListener('click', function() {
this.previousElementSibling.style.display = 'initial';
this.previousElementSibling.children[1].children[1].value = 1;
this.style.display = 'none'
});
})
.form-group {
width: 30%;
margin: 30px;
display: none;
}
.input-group {
flex-direction: row;
display: flex;
}
body {
background: #111;
}
<div class='one'>
<div class="form-group">
<label>value: </label>
<div class="input-group">
<button class="down">-</button>
<input type="text" class="myNumber" value='1'>
<button class="up">+</button>
</div>
</div>
<button class='firstAdd'>Add</button></div>
<br>
<div class='two'>
<div class="form-group">
<label>value: </label>
<div class="input-group">
<button class="down">-</button>
<input type="text" class="myNumber" value='1'>
<button class="up">+</button>
</div>
</div>
<button class='firstAdd'>Add</button></div>

Target Input and nextElementSibling With forEach Loop / event.Target Property - JavaScript

I have a series of forms on a page which each have a simple text counter on the input element (to illustrate the length of a title as it is being typed). When I was working out how to do the counter it was on a singular instance of the form.
How do I have it so the counter works in relation to the nextElementSibling when there are multiple instances of the form? I would've thought it would be done with e.target property, but I can't work out how to store the input element as a target so to speak? I thought e.target = item in the code below would work but this doesn't.
Codepen: https://codepen.io/thechewy/pen/powZppR
var title = document.querySelectorAll(".image-title-upload"),
charsRemaining = document.querySelectorAll(".image-title-upload").nextElementSibling,
maxValue = 125;
title.forEach((item) => {
item.addEventListener("input", (e) => {
//e.target = item; thought this might work but it doesn't
remaining = maxValue - item.value.length; // work out how many characters are left
charsRemaining.textContent = remaining;
});
});
form {
margin-bottom: 2rem;
}
span {
display: block;
margin-top: 4px;
}
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
this way
const
titleInput = document.querySelectorAll(".image-title-upload")
, maxValue = 125;
titleInput.forEach( item =>
{
item.oninput = e =>
{
item.nextElementSibling.textContent = maxValue - item.value.length
}
})
form {
margin-bottom: 2rem;
}
span {
display: block;
margin-top: 4px;
}
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
<form>
<input class="image-title-upload" type="text" name="image-title" placeholder="Title">
<span class="tl characters-remaining">125</span>
</form>
you can also use
e.target.closest('form').querySelector('.characters-remaining').textContent = ....

Adding labels to QR codes

I have created a QR code generator. The user can create multiple QR codes.
I would like the user to be able to name each QR code (referred to as a checkpoint) by writing the desired checkpoint name in the text input field, clicking the Assign Name button and having the text input field disappear, being replaced by the name the user typed into the field.
The user can input checkpoint names, however, it only works for the first QR code printed, and the label only appears below the QR code. Below is the code that I have so far. Any help or suggestions to help me get the ball rolling on this would be very much appreciated. Thank you!
Note: If you try to run this to see the QR codes, you will have to enter something in the text field and press generate. They won't appear automatically.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: arial, sans-serif;
}
section {
margin: 50px auto;
max-width: 350px;
text-align: center;
}
textarea {
width: 50%;
height: 50px;
margin-bottom: 10px;
}
#size {
max-width: 64px;
}
label {
display: inline-block;
width: 140px;
text-align: left;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<section>
<h1>QR Code Generator</h1>
<p>Enter a URL or some text bellow and hit the Generate button (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<div class="block">
<label for="size">Size (px):</label>
<input align="left" id="size" type="number" value="150" min="50" max="500" step="50">
<label for="amount">Amount of Labels:</label>
<input align="left" id="amount" type="number" value="1" min="1" max="500" step="1">
<button id="genQRcode">Generate</button>
</div>
<div id="content" style="display: none;"></div>
</section>
<p id="demo" align="center"></p>
<script>
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<script id="template-qr-code" type="text/html">
<p> <img id="qrcode" src="{{src}}" /></p>
<label for="checkpoint"> Checkpoint Name:</label>
<input id="cpname" type="text" value="">
<button onclick="myFunction()">Assign Name</button>
</script>
<script type="text/javascript">
window.addEventListener('load', function() {
var textarea = document.getElementById("textarea"),
content = document.getElementById("content"),
amount = document.getElementById("amount"),
qrTemplate = document.getElementById('template-qr-code');
function genQRcode() {
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size + "x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter valid data!");
textarea.focus();
content.style.display = "none";
} else {
for (var i = 0; i < amount.value; i++) {
var qrSrc = qrTemplate.innerHTML;
qrSrc = qrSrc.replace(new RegExp('{{src}}', 'g'), chart);
qrSrc = qrSrc.replace(new RegExp('{{i}}', 'g'), i);
content.insertAdjacentHTML('beforeEnd', qrSrc);
}
content.style.display = "";
}
}
document.getElementById("genQRcode").addEventListener("click", genQRcode);
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
genQRcode();
}
});
});
</script>
</body>
</html>
Your click function
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
is getting and setting an element by ID. That will only ever affect a single element on the page (usually the first one that the browser runs into with that specific id). You need to use a different selector / way of getting the label you want to change because you can't reuse ids.
Basically you need to make your label fields distinct so you can actually select them

How to add js code to different appended elements?

I have this code (snippet). If you type your name, it will add it below automatically.
If you click "Add member" and type a name inside the appended input, it appears below too (on its respective "Hello, ...")
If you do it again, this time won't work, because the jscode only applies to the first appended elements.
My question is: how do I apply this jscode with with a third or fourth member, and so on?
PS. Another question: how do I make it unable to remove the first input text (so it is required to have at least 1 member)?
var name1 = document.getElementById('first');
name1.addEventListener('input', function() {
var result = document.querySelector('span.one');
result.innerHTML = this.value;
});
$('.add').click(function() {
$('.block:last').after('<div class="block"><input type="text" id="X"><span class="remove">Remove member</span><br><br></div>');
$('.hello:last').after('<div class="hello">Hello, <span class="name"></span><br><br></div>');
var name1 = document.getElementById('X');
name1.addEventListener('input', function() {
var result = document.querySelector('span.name');
result.innerHTML = this.value;
});
});
$('.optionBox').on('click', '.remove', function() {
$(this).parent().remove();
$('.hello:last').remove();
});
.block {
display: block;
}
input {
width: 50%;
display: inline-block;
}
span.add, span.remove {
display: inline-block;
cursor: pointer;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="optionBox">
<div class="block">
<span class="add">Add member</span>
<br><br>
</div>
<div class="block">
<input type="text" id="first"> <span class="remove">Remove member</span><br><br>
</div>
</div>
<div class="newmember">
</div>
<br>
<div class="hello">
Hello, <span class="one"></span><br><br>
</div>
I have done a bit of workout for you. Please check it. I think this is what you are looking for. I am adding same id and class attr for the input and the div to display the content.
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class ="' + x + '" ><input type="text" class= "' + x + '" name="mytext[]"/>Remove</div>'); //add input box
$('.hello:last').after('<div class="hello" id = "' + x + '" >Hello, <span class="name"></span><br><br></div>');
$('input').on('input', function(e) {
divtoappend = $(this).attr('class');
var val = "";
var val = $(this).val();
var sel = "#" + divtoappend + " span";
$(sel).text('');
$(sel).append(val);
});
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
var rem = $(this).parents('div').attr('class');
$('#' + rem).remove();
$(this).parent('div').remove();
x--;
});
});
.block {
display: block;
}
input {
width: 50%;
display: inline-block;
margin : 4px;
}
span.add, span.remove {
display: inline-block;
cursor: pointer;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" class="1" name="mytext[]"></div>
</div>
<div class="hello" id="1">
Hello, <span class="1"></span><br><br>
</div>
Ok, I think we're all over-thinking this:
<div>
<button id="uxAddMember" class="btn btn-primary">Add Member</button>
</div>
<div class="container">
<div class="row" data-id="1">
<div class="form-control">
<input type="text" class="name" id="name" /> <span style="padding-left: 10px;"><button class="btn btn-warning">Remove Member</button>
</div>
</div>
</div>
<div>
<span id="uxHello"></span>
</div>
<script type="text/javascript">
$(document).ready(function() {
var rows = 1;
$('#uxAddMember').click(function() {
$('.container').append($('.row').attr('data-id', rows).html());
rows++;
});
});
$(document).on('keyup', '.name', function() {
$('#uxHello').html("Hello, " + $(this).val());
});
</script>
That doesn't include your removal functionality, but it takes care of the name output and adding new rows.

Button to clear text and reset search input not working

Ok, so I have a filterable search form that returns certain images in a grid, which works great, it resets when I delete the text in the search input, but when I click the "Clear" button, which should do the same thing as deleting the text, it doesn't work. Here is the HTML and JQuery used:
<form id="live-search" action="" class="styled" method="post" style="margin: 2em 0;">
<div class="form-group">
<input type="text" class="form-control" id="filter" value="" style="width: 80%; float: left;" placeholder="Type to search"/>
<span id="filter-count"></span>
<input type="button" class="clear-btn" value="Clear" style="background: transparent; border: 2px solid #af2332; color: #af2332; padding: 5px 15px; border-radius: 3px; font-size: 18px; height: 34px;">
</div>
</form>
This is the JQuery for the clearing text:
jQuery(document).ready(function(){
jQuery("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = jQuery(this).val(), count = 0;
// Loop through the comment list
jQuery(".watcheroo").each(function(){
jQuery(this).removeClass('active');
// If the list item does not contain the text phrase fade it out
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
jQuery(this).show();
count++;
}
});
// Update the count
var numberItems = count;
});
//clear button remove text
jQuery(".clear-btn").click( function() {
jQuery("#filter").value = "";
});
});
Any help would greatly be appreciated.
value is a property on a DOMElement, not a jQuery object. Use val('') instead:
jQuery(document).ready(function($) {
$("#filter").keyup(function() {
var filter = $(this).val(),
count = 0;
$(".watcheroo").each(function(){
var $watcheroo = $(this);
$watcheroo.removeClass('active');
if ($watcheroo.text().search(new RegExp(filter, "i")) < 0) {
$watcheroo.fadeOut();
} else {
$watcheroo.show();
count++;
}
});
var numberItems = count;
});
$(".clear-btn").click(function() {
$("#filter").val(''); // <-- note val() here
});
});
Note that I amended your code to alias the instance of jQuery passed in to the document.ready handler. This way you can still use the $ variable safely within the scope of that function.
As the accepted answer doesn't solve the problem.
Try input event instead of keyup
$("#filter").on("input", function() {.....
& then clear the filter input field on which event you want.
$(".clear-btn").on("click", function() {
$("#filter").val("").trigger("input");
});
Add this to your CSS:
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
<form>
<input type="search" name="search" placeholder="Search...">
</form>

Categories