I want to make a modal pop up which inside of it contain a (+/-) button, it's work if it's not inside the modal, but it doesn't work inside of the modal.
Here is my (+/-) code :
<div class="col-md-12">
<button style="border: 1px solid #000000;padding: 2px;color: black"
class="incr-btn" data-action="decrease" href="#">-</button>
<input id="number" type="text" name="quantity" value="1"
style="max-height: 29px;max-width: 15px; border: 1px solid #000000">
<button style="border: 1px solid #000000;padding: 2px;color: black"
class="incr-btn" data-action="increase" href="#">+</button>
</div>
And here is my (+/-) js :
<script type="text/javascript">
$(".incr-btn").on("click", function (e) {
var $button = $(this);
var oldValue = $button.parent().find('.quantity').val();
$button.parent().find('.incr-btn[data-action="decrease"]').removeClass('inactive');
if ($button.data('action') == "increase") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below 1
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
$button.addClass('inactive');
}
}
$button.parent().find('.quantity').val(newVal);
e.preventDefault();
});
</script>
Related
*Edit: Fixed so that all inputs are now validated on one form. However, I can only add one variable to check if blank, as soon as I add more, none of the submit functions work. I have been trying multiple things.
function validateForm() {
var inputVelocity = document.getElementById("dzCalculator").inputVelocity.value;
var inputYellowPhase = document.getElementById("dzCalculator").inputYellowPhase.value;
var inputRedPhase = document.getElementById("dzCalculator").inputInterPhase.value;
var inputReactionTime = document.getElementById("dzCalculator").inputReactionTime.value;
if(inputVelocity === "" && inputYellowPhase === "" && inputRedPhase === "" && inputReactionTime === ""){
alert("Input all fields to calculate.");
return false;
}
}
I have checked the HTML matches - it does. But I found I could not use onsubmit="return validateForm" as this wouldn't work at all.
This is only 4 of the form values, there are seven all up. But when I can get the four working, I can get them all working.
How can I use JS to make sure that no input is left blank or empty? I already have made it so that it will only accept numbers and decimal points. So no one can add an incorrect field. But currently, they can leave a field blank which means my calculator generates a NaN response.
Also, how can I make sure one of my fields can not accept a number greater than 1 or less than 0. I tried min="0" max="1" in the input tag, but because I have removed spinners, this doesn't work.
So, in summary, I am looking to make sure when a button is clicked that all the form sections are filled in and that one of the fields doesn't accept a number greater that 1 or less than zero.
there are 2 options for this.
You can select all the inputs (inside the form tag) using querySelector and check the value of each input by looping through them.
use this trick selector to get all the invalid inputs
document.querySelectorAll('input:not([value]):not([value=""])');
replace input with more precise selector.
Can you please give more detail about how your form is in multiple places?
For input I think you need to use step attribute
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Reference: javascript_form_validation
Depends when would you like to validate form fields
For example: Form validation on submit
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<html>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Give name to your form using name attribute such as <form name="myForm" ..>
Then using document.forms["myForm"] you can have access to your form
There you can validate your input fields value. return true if validates
This works for me. You can use it, style it however you want or not. You do need JQuery. It has powerful selectors.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
body{
font-size: 12px;
}
.main-container{
display: flex; /* DO NOT CHANGE */
height: 100vh; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
}
.c-message{
display: flex; /* DO NOT CHANGE */
position: fixed; /* DO NOT CHANGE */
top: 0px; /* DO NOT CHANGE */
left: 0px; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
height: 100%; /* DO NOT CHANGE */
}
.c-msgbox{
padding: 30px;
text-align: center;
margin: auto; /* DO NOT CHANGE */
background-color: #e4e4e4;
border-radius: 4px;
border: 1px solid #adadad;
-webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
-moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
}
.standerd-button2{
border: none;
font-family: arial,helvetica,clean,sans-serif;
font-size: 10px;
font-weight: 600;
color: white;
background: #1A709F;
padding: 3px;
text-align: center;
vertical-align: middle;
-webkit-border-radius: 3px;
width: max-content;
min-width: 50px;
margin: 2px;
}
.standerd-button2:hover{
background: crimson;
cursor: default;
}
.f-table {
display: table;
width: max-content;
padding: 5px;
border-spacing: 2px;
}
.f-tablerow {
display: table-row;
}
.f-tablecell{
display: table-cell;
}
.label-cell-r{
text-align: right;
}
.dd-required{
margin: auto;
color: red;
}
input, select{
border: 1px solid lightgrey;
}
</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
<div>
<form id="f1" name="f1">
<div class="f-table">
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="firstname">First Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="firstname" name="firstname" type="text" data-er="First Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="lastname">Last Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="lastname" name="lastname" type="text" data-er="Last Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="company">Company</label>
</div>
<div class="f-tablecell input-cell">
<select id="company" name="company" data-er="Company Name">
<option value="0"> - Select Comapny - </option>
<option value="1">Company 1</option>
<option value="2">Company 2</option>
<option value="3">Company 3</option>
<option value="4">Company 4</option>
</select>
<span class='dd-required'>*</span>
</div>
</div>
</div>
<input id="b1" type="submit" value="Submit" />
</form>
</div>
<div>
<script type="text/javascript">
$.fn.CustomAlert = function (options, callback) {
var settings = $.extend({
message: null,
detail: null,
yesno: false,
okaytext: null,
yestext: null,
notext: null
}, options);
var frm = "";
detail = "<b>" + settings.detail + "</b>";
message = "<b>" + settings.message + "</b>";
if (settings.detail === null) {
detail = "";
};
frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";
if (settings.yesno === false) {
frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
} else {
frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
"<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
};
var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
"<div class='c-msgbox'>" +
"<form>" + frm + "</form>" +
"</div>" +
"</div>";
$(".main-container").append(frmesg);
if (!settings.yesno) {
$("#cmessage #ok").click(function () {
$("#cmessage").remove();
callback(false);
});
} else {
$("#cmessage #yes").click(function () {
$("#cmessage").remove();
callback(true);
});
$("#cmessage #no").click(function () {
$("#cmessage").remove();
callback(false);
});
};
};
$.fn.JsFormCheck = function () {
var MessData = "";
this.find('select, input').each(function () {
if ($(this).attr("data-er")) {
m = $(this).attr("data-er");
switch ($(this).get(0).tagName) {
case "INPUT":
if ($(this).val().length === 0) {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
case "SELECT":
if ($(this).val() === "0") {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
};
};
});
if (MessData.length > 0) {
MessData = "<b>" + MessData + "</b>";
x = $().CustomAlert({message: "<b>Please fill in the following required fields to continue.</b>",
detail: MessData,
okaytext: "Close",
yesno: false});
return true;
} else {
return false;
};
};
$('#f1 #b1').click(function(event){
event.preventDefault();
Error = $("#f1").JsFormCheck();
if(Error === false){
null;
//Do Something
};
});
</script>
</body>
<pre>
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<pre>
This is loop.
I want to get input value when i click quantity up & down button each time. There are multiple elements.
How to find input value in javascript by clicking button up & down.
You can add onClick event with parents feature to detect the inputs near to the button.
$(document).on('click','.quantity-up',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)+1);
});
$(document).on('click','.quantity-down',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)-1);
});
.quantity {
padding: 10px;
}
.quantity-nav{
display: inline-block;
}
.quantity-button {
display: inline-block;
padding: 5px;
background-color: #c7c5c5;
border: 1px solid #585353;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
</div>
Thanks :-)
Actually your problem is quite easy to solve.
Try to add this script at the end of your <body>.
I suggest you to make some modifications in your html too: use <button> or <input type="button"or even <a> tags for your controls.
I added some logic about the min/max/step attributes you can set on a <input type="number"> but this is optional. It's up to you to change this.
document.addEventListener("DOMContentLoaded", function() {
const qtyWraps = document.getElementsByClassName('quantity');
for (let i = 0; i < qtyWraps.length; i++) {
const qtyWrap = qtyWraps.item(i);
const input = qtyWrap.querySelector('.form-qty');
const up = qtyWrap.querySelector('.qty-up');
const down = qtyWrap.querySelector('.qty-down');
const output = qtyWrap.querySelector('.output');
up.addEventListener('click', function(e) {
e.preventDefault();
addValue(1);
});
down.addEventListener('click', function(e) {
e.preventDefault();
addValue(-1);
});
input.addEventListener('input', function() {
output.textContent = input.value
});
const addValue = function(value) {
const current = parseInt(input.value);
const min = input.getAttribute('min') || -Infinity;
const max = input.getAttribute('max') || Infinity;
const step = input.getAttribute('step') || 1;
const newValue = Math.min(max, Math.max(min, current + value * step));
input.value = newValue;
if (newValue <= min) down.setAttribute('disabled', 'disabled');
else down.removeAttribute('disabled');
if (newValue >= max) up.setAttribute('disabled', 'disabled');
else up.removeAttribute('disabled');
input.dispatchEvent(new Event('input'));
}
addValue(0)
}
});
.quantity {
display: block;
width: 500px;
margin: auto;
text-align: center;
}
.quantity .form-qty {
display: inline-block;
}
.quantity .quantity-nav {
display: inline-block;
}
.quantity .output {
background: yellow;
width: 500px;
margin: 1em auto 0;
}
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<button class="quantity-button quantity-up qty-up">+</button>
<button class="quantity-button quantity-down qty-down">-</button>
</div>
<!-- I put it here to show the output result -->
<div class="output">1</div>
</div>
You can use localStorage to store the value of your quantity, this would make the data persistent.
Please check the below code snippet:
const down = document.querySelector('.down');
const up = document.querySelector('.up');
const input = document.querySelector('.quantity');
// store utility function
const store = {
existsIn: function(key) {
return this.getFromKey(key) !== null;
},
getFromKey: function(key) {
return window.localStorage.getItem(key);
},
add: function(key, value) {
const storeSource = window.localStorage.setItem(key, value);
}
}
const quantity = Object.create(store);
quantity.exists = function() {
return this.existsIn('quantity');
}
quantity.increase = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
storedQuantity = storedQuantity + 1;
this.add('quantity', storedQuantity);
}
quantity.decrease = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
if(storedQuantity > 0) {
storedQuantity = storedQuantity - 1;
}
this.add('quantity', storedQuantity);
}
quantity.show = function() {
return this.exists() ? this.getFromKey('quantity') : 0;
}
// event listeners for up and down buttons
up.addEventListener('click', function() {
quantity.increase();
// update input on button click
input.value = quantity.show();
})
down.addEventListener('click', function() {
quantity.decrease();
// update input on button click
input.value = quantity.show();
})
// update input on page load
input.value = quantity.show();
There you can find a working fiddle:
https://jsbin.com/tavalocoti/5/edit?html,js,console,output
****UPDATE****
I was able to have below issue work with the help of #JasonB.
In addition, I also have another 3 textareas on the same form that will only show when its checkbox is clicked. How will I add that on my current script? I tried grouping it the same way as TextBoxesGroup but just giving another id but when I hit submit, even if I didn't clicked the checkbox, values inside are being submitted. Thank you so much in advance. I'm really new to programming and I'm trying to learn the basics.
HERE'S MY CODE for the checkbox
<textarea id="text" >NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text1">NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text2">NAME-
ADDRESS-
ETC-</textarea>
<input type="checkbox" id="myCheck" onclick="myFunction()">DETAILS
<input type="checkbox" id="myCheck1" onclick="myFunction1()">DETAILS
<input type="checkbox" id="myCheck2" onclick="myFunction2()">OTHERS
<script>
function myFunction() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myFunction1() {
var checkBox1 = document.getElementById("myCheck1");
var text1 = document.getElementById("text1");
if (checkBox1.checked == true){
text1.style.display = "block";
} else {
text1.style.display = "none";
}
}
function myFunction2() {
var checkBox2 = document.getElementById("myCheck2");
var text2 = document.getElementById("text2");
if (checkBox2.checked == true){
text2.style.display = "block";
} else {
text2.style.display = "none";
}
}
</script>
PREVIOUS QUESTION
I have a form with multiple textareas. I'm not familiar with any databases so instead of using one, I prefer using or saving the values/inputs of my textarea to another textarea on submit. I was able to make it work but with those textareas being added dynamically, I only get the first textarea.
here's my script
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 15) {
alert("Only 15 textboxes allowed");
return false;
}
$('<div/>',{'id':'TextBoxDiv' + counter}).html(
$('<textarea/>',{'id':'myTextArea' + counter ,'class':'myTextArea'}).html( 'STEP ' + counter + ' : ' )
)
.appendTo( '#TextBoxesGroup' )
$("#myTextArea" + counter).each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
$(document).ready(function() {
$("#btn-primary").click(function() {
e=1;
var text55 = $('#textarea55').val();
var text56 = $('#textarea56').val();
var text57 = $('#textarea57').val();
var text58 = $('#textarea58').val();
var text59 = $('#textarea59').val();
var text60 = $('#textarea60').val();
var text61 = $('#textarea61').val();
var text62 = $('#textarea62').val();
var myTextArea = $('#myTextArea'+e).val();
$('#inputTextToSave').val( $('#inputTextToSave').val()+text55+'\n'+text56+'\n'+text57+'\n'+'TROUBLESHOOTING NOTES'+'\n'+myTextArea+'\n'+text58+'\n'+text59+'\n'+text60+'\n'+text61+'\n'+text62+'\n');
e++;
});
here's my html
<textarea id="textarea55" name="caller"></textarea><br>
<textarea id="textarea56" name="auth"></textarea><br>
<textarea id="textarea57" name="issue"></textarea><br>
<label>TROUBLESHOOTING NOTES:</label><br>
<body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv"></div></div>
<input type='button' value='ADD TS STEPS' id='addButton' class="bubbly-button">
<input type='button' value='REMOVE TS' id='removeButton' class="bubbly-button"><br><\body>
<textarea id="textarea58" name="acct"></textarea><br>
<textarea id="textarea59" name="tid"></textarea><br
<textarea id="textarea60" name="resolution"></textarea><br>
<textarea id="textarea61" name="case"></textarea><br>
<textarea id="textarea62" rows="1" disabled>YANA</textarea>
<input type='button' value='SUBMIT' id='btn-primary' class="bubbly-button"><br>
my css
div {
padding: 1px;
}
textarea {
outline: none;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
}
.myTextArea {
width: 535px;
min-height: 14px;
overflow-y: hidden;
font-size: 14px;
border: 3px solid orange;
background-color:white;color:mediumvioletred;
display: block;
}
body{
font-size: 14px;
font-family: 'tempus sans ITC', 'Arial';
color: mediumvioletred;
text-align: center;
background-color: pink;
}
Your dynamically created textareas are all in #TextBoxesGroup.
To select them all at the time of submission, you can call $('#TextBoxesGroup textarea'). To append their contents into a string with '\n' characters separating them you can use jQuery's .map function to get the text of each element in an array wrapped in a jQuery object, .get to get the underlying array, and .join to concatenate the strings with '\n' as the glue.
var contents = $('#TextBoxesGroup textarea')
.map(function() {
return $(this).text();
})
.get()
.join('\n');
console.log( contents );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="TextBoxesGroup">
<div><textarea>One</textarea></div>
<div><textarea>Two</textarea></div>
<div><textarea>Three</textarea></div>
</div>
I have a form with a text area as well as javascript counter that counts how many characters you type into the text area. I need a button that resets both whats typed into the text area AND the counter.
This is my form code:
<script type="text/javascript">
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len -
el.value.length;
return true;
}
</script>
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2" maxLength="60" onkeyup="change(this);"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" value="reset title" />
</form>
The javascript below resets the text entered into the textarea but it does not reset the counter within the span "left_char_cnt"
<script>
function myFunction() {
document.getElementById("title").reset();
}
</script>
What javascript is needed to reset both?
You cannot "reset" the text / HTML of an element if you haven't saved it somehow. reset() only works for form inputs.
So what you have to do is rewrite the HTML content of your element.
<script>
function myFunction() {
document.getElementById("title").reset();
document.getElementById("left_char_cnt").innerHTML = '<b>0</b>';
}
</script>
your script to count words in text is not working but, i made a script to clear textarea & count
function myfun(){
document.getElementById('txtarea').value=' ';
document.getElementById('count').innerHTML='0';
}
<form id="title">
<textarea id="txtarea" style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2"></textarea>You've typed <span id="left_char_cnt"><b id=count>123</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b >lots</b></span> more
<input class="btn btn-primary" type="button" onclick="myfun()" value="reset title" />
</form>
<script type="text/javascript">
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len -
el.value.length;
return true;
}
</script>
The simplest way is to reuse the code you already have, and allow the change event handler to set the values correctly. That way, if you ever change the behavior of that function then the reset will also change to match it.
I also modified your code slightly to make it update as the text is changing, rather than when you leave the textarea.
Try this...
function change (el) {
var max_len = el.name == 'left' ? 60 : 320;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
}
document.getElementById(el.name + '_char_cnt').innerHTML = el.value.length;
document.getElementById(el.name + '_chars_left').innerHTML = max_len - el.value.length;
return true;
}
var textarea = document.querySelector("#title textarea");
textarea.addEventListener("keyup", function() { change(this); });
document.querySelector("#reset-button").addEventListener("click", function() {
textarea.value = "";
change(textarea);
});
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" id="reset-button" value="reset title" />
</form>
var t = document.getElementsByTagName('textarea')[0];
var a = document.getElementById('left_char_cnt');
var b = document.getElementById('left_chars_left')
t.addEventListener('keyup',function(){
var value = t.value.length;
var maxval = 60;
a.innerHTML = value
b.innerHTML = (maxval- value)
if(value == 60){ a.maxLength = maxval}
})
function resetVal(){
t.value = null;
a.innerHTML = '<b>0</b>'
b.innerHTML = '<b>lots</b>'
}
<h2 style="background-color: #eee; padding: 10px 20px 10px 20px; margin-
bottom: 20px;">Enter meta title tag</h2>
<form id="title">
<textarea style="border: 1px solid #eb008b;" cols="100" name="left"
rows="2" maxlength="60"></textarea>You've typed <span id="left_char_cnt"><b>0</b></span>
character(s) out of a possible 60. You are allowed <span
id="left_chars_left"><b>lots</b></span> more
<input class="btn btn-primary" type="button" onclick='resetVal()' value="reset title"/>
</form>
Use this function, by replacing your 'myFunction()'
<script>
function myFunction() {
document.getElementById("title").reset(); // reset your form
document.getElementById("left_char_cnt").innerHTML = '<b>0</b>'; //reset your span counter
}
</script>
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>