submitting form via email with dynamic fields - javascript

Thank you in advance.
The code now works exactly as I need it too but I'm not sure how to go about passing each new line to my .asp mail handler if all the input names are the same. Where exactly in my code would I index the input boxes so that I can call them uniquely during submission and email themwith .asp mail handler?
Thank you to the stackoverflow community for helping me troubleshoot the code I've written thus far!
HTML
<form role="form" action="/wohoo" method="POST">
<label>Item</label>
<div class="catalog-fieldset">
<div class="catalog-wrapper">
<div class="catalog-items">
<ul>
<li>Quantity:
<input type="text" size="5" name="Qty[]">
</li>
<li>Width:
<input type="text" size="5" name="Width[]">
</li>
<li>Height:
<input type="text" size="5" name="Height[]">
</li>
</ul>
<button type="button" class="remove-line">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add More...</button>
</div>
</form>
CSS
ul {
list-style: none;
display:inline-block;
margin:0 0 5px;
}
ul li {
display: inline-block;
}
.remove-line {
display:inline-block;
}
I have this code set up http://jsfiddle.net/KeithDickens/afqh4a5o/2/
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var x = 1; //initlal text box count
$('.catalog-fieldset').each(function () {
var $wrapper = $('.catalog-wrapper', this);
$(".add-field", $(this)).click(function (e) {
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$('.catalog-items:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
}
});
$('.catalog-items .remove-line', $wrapper).click(function () {
x = x - 1; //initlal text box count
if ($('.catalog-items', $wrapper).length > 1) $(this).parent('.catalog-items').remove();
});
});
});

Reading values given your current setup would simply be based on position. This is terribly brittle since if you change the position you break the code but if you were to add a
<button type="button" class="summarise">Summarise</button>
beneath your existing Add More button and swap out your javascript for what's below it should give you more than a start. Validation etc will need to be applied.
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var x = 1; //initlal text box count
function LineItemViewModel() {
var self = this;
self.Qty = 0;
self.Width = 0;
self.Height = 0;
}
function CollectionViewModel() {
var self = this;
self.Items = [];
}
var collection = new CollectionViewModel();
$('.catalog-fieldset').each(function () {
var $wrapper = $('.catalog-wrapper', this);
$(".add-field", $(this)).click(function (e) {
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$('.catalog-items:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
}
});
$(".summarise", $(this)).click(function (e) {
var txts = $('.catalog-fieldset input[type=text]');
var item = new LineItemViewModel();
txts.each(function () {
switch($(this).attr("name")){
case "Qty[]":
item.Qty = $(this).val();
break;
case "Width[]":
item.Width = $(this).val();
break;
case "Height[]":
item.Height = $(this).val();
collection.Items.push(item);
item = new LineItemViewModel();
break;
}
});
alert(collection.Items.length);
});
$('.catalog-items .remove-line', $wrapper).click(function () {
x = x - 1; //initlal text box count
if ($('.catalog-items', $wrapper).length > 1) $(this).parent('.catalog-items').remove();
});
});
});
There are cleaner / shorter / more concise ways to do the above but this way should be very self explanatory.

Related

How to limit the amount of times an element can be created

Is there a way to limit the amount of times a user can click a button to create an element? This is what I have managed to put together so far. Thank you.
JavaScript
var ClickCount = 0;
function countClicks() {
var clickLimit = 8 ; //Max number of clicks
if(ClickCount<=clickLimit) {
populateTipItem();
}
else if(ClickCount > clickLimit)
{
return;
}
}
// TIP LIST
function populateTipItem() {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("class", "form-control mt-1 tip-item");
x.setAttribute("placeholder", "Another Tip Item! ... 250tks");
document.getElementById("tipList").appendChild(x);
}
HTML
<div id="tipList" class="form-group mt-5">
<label for="tips">Your Tip Menu Items</label>
<small class="form-text text-muted">Max 10 items.</small>
<input type="text" name="tips" class="form-control mt-1 tip-item" placeholder="Tip Item! ... 10tks"/>
</div>
<button class="btn btn-secondary" onclick="return countClicks()">Add Tip Item</button>
You're almost completed. The main change is to add ClickCount++ so you'll know how much elements were created.
var ClickCount = 0;
var clickLimit = 8 ; //Max number of clicks
function countClicks() {
if(ClickCount<=clickLimit) {
ClickCount++;
populateTipItem();
}
else if(ClickCount > clickLimit) {
return;
}
}
alternatively you can count the number of elements created:
var clickLimit = 8;
var tipList = document.getElementById('tipList');
function countClicks() {
if (tipsList.children.length < clickLimit) {
populateTipItem();
}
}

dynamically count textarea symbols in a simple input

Good day everyone
I have a simple textarea on a page,and I need to dynamically count number of symbols, show how much is left under the form,and limit number of characters should be 350.
Thanks in advance.
What i exactly need is to display how many symbols are left to type
function limit(element)
{
var max_chars = 350;
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
<textarea onkeydown="limit(this);" onkeyup="limit(this);"></textarea>
var max_chars = 5;
var charsLeftDisplay = document.getElementById("charsLeft");
function limit(element) {
if (element.value.length > max_chars) {
element.value = element.value.slice(0, -1);
return false;
}
charsLeftDisplay.innerHTML = (max_chars - element.value.length) + " characters left...";
}
<textarea onkeyup="limit(this)"></textarea>
<p id="charsLeft"></p>
I think the best way to do this would be to use JQuery
here's the html
<textarea id="textareaID" rows="4" cols="50" maxlength="50"></textarea>
<p id="numberOfChars"><strong>Character typed:</strong> 0</p>
<p><strong>Max Character:</strong> 50</p>
and here's the jquery code
$('#textareaID').bind('input propertychange', function() {
if(this.value.length){
$("#numberOfChars").html("<strong>Character typed:</strong> "+this.value.length);
}
});
and here's a working fiddle as well https://jsfiddle.net/Visrozar/zbw7j64j/
Here is a simple solution,
just display the leftCharacters in a placeholder;
<script>
$(function() {
var $textarea = $('textarea');
var $input = $('input[name="spaces"]');
var maxLength = $textarea.attr('maxlength');
$input.val(maxLength);
$textarea.on('input', function() {
var currentLength = $textarea.val().length;
var leftCharacters = (maxLength - currentLength);
$input.val(leftCharacters);
});
});
</script>
<textarea name=test" maxlength="350"></textarea>
<input name="spaces" disabled />
This solution really works very well:
1 - Insert a div with id="textarea_count" for example in the place you want to show remaining characters, in your HTML file, near your textarea element (above or under):
<div class="form-group">
<label asp-for="DescCompetencia" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="DescCompetencia" class="form-control" rows="5"></textarea>
<span asp-validation-for="DescCompetencia" class="text-danger"></span>
<div id="textarea_count"></div>
</div>
</div>
2 - Insert in your javascript file or after /html element in the page you are editing the textarea element:
$(document).ready(function () {
var text_max = 500; //change by your max desired characters
var text_min = 7; //change to your min desired characters (or to zero, if field can be blank))
if ($('#DescCompetencia').length) {
var texto_disponivel = text_max - $('#DescCompetencia').val().length;
}
$('#textarea_count').html(texto_disponivel + ' caracteres disponíveis para digitar');
$('#DescCompetencia').keyup(function () {
var text_length = $('#DescCompetencia').val().length;
var text_remaining = text_max - text_length;
if (text_length <= text_min) {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes. Digite ' + text_min + ' ou mais caracteres.');
}
else {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes');
}
}); });
Must have Jquery already loaded before calling the above function.

Add one every time click ADD button

NEED HELP!
How to add one every time I click "Add" button?
The number will increase every time I click.
It's start from 0, after I click it's will plus 1 become 1, then 2 and etc.
HTML:
<div id="add_form">
<div class="form-field">
<div class="field">
<div class="no">0</div>
</div>
</div>
</div>
Add
<p><br /></p>
JQuery:
$(document).ready(function() {
var MaxInputs = 8;
var InputsWrapper = $("#add_form");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=1;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<div class="field"><div class="no">1</div></div>');
x++;
}
return false;
});
});
My JQuery quite poor, need some help from you guys.
Also, here is the jsfiddle link.
http://jsfiddle.net/fzs77/
Really appreciate your help.
You have 1 hardcoded, so it can't change. Do it like this:
$(InputsWrapper).append('<div class="field"><div class="no">' + x + '</div></div>');
Check this JSFiddle with working demo.
You have to out the variable that holds the number inside of the html that you append. Also move the increscent of the FieldCount variable to below the append function call to render the correct result.
Like so:
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
$(InputsWrapper).append('<div class="field"><div class="no">' + FieldCount + '</div></div>');
x++;
FieldCount++;
}
return false;
});
Try this jsfiddle:
http://jsfiddle.net/fzs77/7/
<div id="add_form">
<div class="form-field">
<div class="field">
<div class="no">0</div>
</div>
</div>
</div>
Add
<p><br /></p>
JS file
$(document).ready(function() {
var MaxInputs = 8;
var InputsWrapper = $("#add_form");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=0;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<div class="field"><div class="no">' + FieldCount + '</div></div>');
}
return false;
});
});
Try this if you want to increment it while on the same line.
http://jsfiddle.net/sdMCH/
$(document).ready(function() {
$('#add_field').click(function (e) {
var x=$(".no");
x[0].innerHTML = (parseInt(x[0].innerHTML,10)+1);
}
);
});

Add and Remove Input Field

I find two bugs at here:
The number will not continue counting, like will be 4 in next input value. Currently when add new input, the value is 1.
The remove button not working if have 3 input field there. But the remove button working if add one more input field. Anyway, only one can be delete.
HTML
<div id="add_form">
<table>
<tr>
<td><input type="text" value="1"/></td>
<td><div class="remove">Remove</div></td>
</tr>
<tr>
<td><input type="text" value="2"/></td>
<td><div class="remove">Remove</div></td>
</tr>
<tr>
<td><input type="text" value="3"/></td>
<td><div class="remove">Remove</div></td>
</tr>
</table>
</div>
Add
JQuery
$(document).ready(function() {
var MaxInputs = 99;
var InputsWrapper = $("#add_form table");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=1;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<tr><td><input type="text" value="' + x + '"/></td><td><div class="remove">Remove</div></td></tr>');
x++;
}
return false;
});
$("body").on("click",".removeclass", function(e) {
if( x > 1 ) {
$(this).closest('tr').remove();
x--;
}
return false;
})
});
http://jsfiddle.net/hxbc7/
I have updated the fiddle that you created. http://jsfiddle.net/hxbc7/12/
There was a mistake in your code that I rectified.
Instead of this line
var InputsWrapper = $("#add_form table");
it should be
var InputsWrapper = $("#add_form table tr");
Try this: Count the FieldCount value and append to the textbox.
$(document).ready(function() {
var MaxInputs = 99;
var InputsWrapper = $("#add_form table");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=3;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<tr><td><input type="text" value="' + FieldCount + '"/></td><td><div class="remove">Remove</div></td></tr>');
x++;
}
return false;
});
$("body").on("click",".removeclass", function(e) {
if( x > 1 ) {
FieldCount--;
$(this).closest('tr').remove();
x--;
}
return false;
})
});
change the code like this
$(document).ready(function() {
var MaxInputs = 99;
var InputsWrapper = $("#add_form table");
var AddButton = $("#add_field");
var x = $("input[type=text]").length;
var FieldCount=1;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
x++;
$(InputsWrapper).append('<tr><td><input type="text" value="' + x + '"/></td><td><div class="remove">Remove</div></td></tr>');
}
return false;
});
$("body").on("click",".removeclass", function(e) {
if( x >= 1 ) {
$(this).closest('tr').remove();
x--;
}
return false;
})
});

Count textarea characters

I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
$(document).ready(function() {
var tel1 = document.forms["form"].elements.tel1;
var tel2 = document.forms["form"].elements.tel2;
var textarea = document.forms["form"].elements.textarea;
var clock = document.getElementById("clock");
var count = document.getElementById("count");
tel1.addEventListener("keyup", function (e){
checkTel(tel1.value, tel2);
});
tel2.addEventListener("keyup", function (e){
checkTel(tel2.value, tel3);
});
/*$("#textarea").keyup(function(){
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
console.log("Characters left: " + charactersLeft);
});​*/
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});
function checkTel(input, nextField) {
if (input.length == 3) {
nextField.focus();
} else if (input.length > 0) {
clock.style.display = "block";
}
}
function textareaLengthCheck(textarea) {
var length = textarea.length;
var charactersLeft = 500 - length;
count.innerHTML = "Characters left: " + charactersLeft;
}
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks #Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
⚠️ The accepted solution is outdated.
Here are two scenarios where the keyup event will not get fired:
The user drags text into the textarea.
The user copy-paste text in the textarea with a right click (contextual menu).
Use the HTML5 input event instead for a more robust solution:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Here is simple code. Hope it help you
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>
I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.
$(function() {
$("#myTextArea").on("input propertychange", function(event) {
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
$("#counter").html(curlen);
});
});
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />
For those wanting a simple solution without jQuery, here's a way.
textarea and message container to put in your form:
<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>
JavaScript:
<script>
function count_it() {
document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>
The script counts the characters initially and then for every keystroke and puts the number in the counter span.
Martin
They say IE has issues with the input event but other than that, the solution is rather straightforward.
ta = document.querySelector("textarea");
count = document.querySelector("label");
ta.addEventListener("input", function (e) {
count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>
var maxchar = 10;
$('#message').after('<span id="count" class="counter"></span>');
$('#count').html(maxchar+' of '+maxchar);
$('#message').attr('maxlength', maxchar);
$('#message').parent().addClass('wrap-text');
$('#message').on("keydown", function(e){
var len = $('#message').val().length;
if (len >= maxchar && e.keyCode != 8)
e.preventDefault();
else if(len <= maxchar && e.keyCode == 8){
if(len <= maxchar && len != 0)
$('#count').html(maxchar+' of '+(maxchar - len +1));
else if(len == 0)
$('#count').html(maxchar+' of '+(maxchar - len));
}else
$('#count').html(maxchar+' of '+(maxchar - len-1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="message" name="text"></textarea>
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
This solution will respond to keyboard and mouse events, and apply to initial text.
$(document).ready(function () {
$('textarea').bind('input propertychange', function () {
atualizaTextoContador($(this));
});
$('textarea').each(function () {
atualizaTextoContador($(this));
});
});
function atualizaTextoContador(textarea) {
var spanContador = textarea.next('span.contador');
var maxlength = textarea.attr('maxlength');
if (!spanContador || !maxlength)
return;
var numCaracteres = textarea.val().length;
spanContador.html(numCaracteres + ' / ' + maxlength);
}
span.contador {
display: block;
margin-top: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>

Categories

Resources