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

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();
}
}

Related

JavaScript-limited click count

I've got a problem with limited click counter using JavaScript. I have tried suggestions below but it seems like my problem might be somewhere else.
HTML/Javascript Button Click Counter
Basically I want to count clicks x times, which is provided from <input type="number"> field. It looks like the script is not recognizing this item in counting function.
Below I'd like to share example code:
function myFunction() {
var count = 0;
var number = document.getElementById("amount").value;
var btn = document.getElementById("clickme");
var disp = document.getElementById("clicked");
btn.onclick = function() {
count++;
disp.innerHTML = count;
}
if (count > number) {
btn.disabled = true;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" onclick="myFunction()">Click me</button>
<script>
</script>
</body>
</html>
Just remove the surrounding function and the onclick attribute.
Also, move the value retrieval and the disabled logic inside the listener, and convert the value to a number:
let count = 0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
const amount = document.getElementById("amount");
btn.onclick = function () {
count++;
disp.innerHTML = count;
const number = +amount.value;
if (count > number) {
btn.disabled = true;
}
}
<input type="number" id="amount" >
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme">Click me</button>
You can simply your solution using the snippet below.
let count = 0;
const inp = document.getElementById("amount");
const countEl = document.getElementById("clicked");
function myFunction(e) {
if (++count >= Number(inp.value)) e.target.disabled = true;
}
<input type="number" id="amount">
<p>How many times button should be clicked</p>
<p>Click the button.</p>
<button id="clickme" onclick="myFunction(event)">Click me</button>
I would recommend something like this. The limit can be increased or decreased at any time to allow for more or less clicks. Once it reaches 0, the button will stop adding to the count -
const f =
document.forms.myapp
function update (event) {
const limit = Number(f.limit.value)
if (limit <= 0) return
f.limit.value = limit - 1
f.count.value = Number(f.count.value) + 1
}
f.mybutton.addEventListener("click", update)
<form id="myapp">
<input type="number" name="limit" value="10">
<button type="button" name="mybutton">click me</button>
<output name="count">0</output>
</form>
I have managed to count the click events with the limit provided by <input type="number"> field and adding data to the array. Additioanlly, I am trying to decrease dynamically the amount of click events and remove last records from array using another button. Basically I have NAN value when I try to get counter value to decrease it.
It looks like this:
HTML code:
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p> Add question</p> <input type="text" id="question">
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" >add me</button>
<button id="delme">
delete me
</button>
</body>
</html>
JS code:
var count = 0;
var i=0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
var amount = document.getElementById("amount");
var question = document.getElementById("question");
var tab;
btn.onclick = function () {
count++;
disp.innerHTML = count;
var number = +amount.value;
tab=new Array(number);
tab[i]=question.value;
console.log(tab[i] + i);
question.value=" ";
i++;
if (count == number) {
btn.disabled = true;
}
}
var delbtn=document.getElementById("delme");
var countdown = parseInt(document.getElementById("clicked"));
delbtn.onclick = function () {
console.log(countdown);
countdown--;
disp.innerHTML = countdown;
if (countdown == 0) {
btn.disabled = true;
}
}

not able to use animation for typing game

I was trying to build a game, but I am not able to setInterval properly. The word is not getting printed on the screen when I click on the start game button, after 5seconds it directly shows GAME OVER.
var btn= document.querySelector('#btn');
btn.addEventListener("click", myMove);
function myMove() {
var word = document.querySelector('#word');
var input=document.querySelector('#written');
var words=['xylophone', 'cat', 'bat', 'chollima'];
var i=0;
var id = setInterval(frame, 5000);
function frame() {
word.innerHTML=words[i];
i = (i < 3) ?( i+1) : 0;
if (input.innerHTML== word.innerHTML) {
clearInterval(id);
} else {
word.innerHTML='GAME OVER';
}
}
}
<div id="heading">TYPING GAME</div>
<label>
<div id="word"></div>
<br>
<input type="text" id="written">
</label>
<button id="btn">START</button>
</body>
Actually, there are some issues with your current solution.
First of all, you are changing the word.innerHTML for the first time after the 5 second interval, so it will instantly get replaced by GAME OVER, so with a difference of some millisecond the innerHTML will be change and you won't be able to see the desired output.
Then you are using input.innerHTML for your condition where innerHTML only uses for HTML elements which are containing some content within them (got opening and closing tags) whilst for taking input value you should use input.value.
Thus, in order to make your code work, you should replace the innerHTML in the very first place before executing the setInterval. Then after calling the interval if the condition met you should increment the i value and then call your interval again recursively.
So your final code should be something like this:
var btn = document.querySelector('#btn');
btn.addEventListener("click", myMove);
function myMove() {
var word = document.querySelector('#word');
var input = document.querySelector('#written');
var words = ['xylophone', 'cat', 'bat', 'chollima'];
var i = 0;
word.innerHTML = words[i];
var id = setInterval(frame, 5000);
function frame() {
if (input.value == word.innerHTML) {
clearInterval(id);
i = (i < 3) ? (i + 1) : 0;
word.innerHTML = words[i];
id = setInterval(frame, 5000)
} else {
word.innerHTML = 'GAME OVER';
}
}
}
<div id="heading">TYPING GAME</div>
<label>
<div id="word"></div>
<br>
<input type="text" id="written">
</label>
<button id="btn">START</button>
Don't use input.innerHTML, use input.value instead:
var btn= document.querySelector('#btn');
btn.addEventListener("click", myMove);
function myMove() {
var word = document.querySelector('#word');
var input=document.querySelector('#written');
var words=['xylophone', 'cat', 'bat', 'chollima'];
var i=0;
var id = setInterval(frame, 5000);
function frame() {
word.innerHTML=words[i];
i = (i < 3) ?( i+1) : 0;
if (input.value == word.innerHTML) {
clearInterval(id);
} else {
word.innerHTML='GAME OVER';
}
}
}
<div id="heading">TYPING GAME</div>
<label>
<div id="word"></div>
<br>
<input type="text" id="written">
</label>
<button id="btn">START</button>
</body>

How to filling table cells with random numbers through button in JavaScript

[User may enter number of rows and columns, then chess board appears after clicking enter button.][The problem is I cannot fill the table cells with random numbers using Fill button]
So far the code of JavaScript is
var a, b, tableElem, rowElem, colElem;
function createTable() {
a = document.getElementById('row').value;
b = document.getElementById('column').value;
if (a == "" || b == "") {
alert("Enter a number");
} else {
tableElem = document.createElement('table');
for (var i = 0; i < a; i++) {
rowElem = document.createElement('tr');
for (var j = 0; j < b; j++) {
colElem = document.createElement('td');
rowElem.appendChild(colElem);
if (i % 2 == j % 2) {
colElem.className = "white";
} else {
colElem.className = "black";
}
}
tableElem.appendChild(rowElem);
}
document.body.appendChild(tableElem);
}
}
and Html is
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="row" placeholder="Row">
</div>
<div class="form-group">
<input type="text" class="form-control" id="column" placeholder="Column">
</div>
<button type="button" class="btn btn-primary" onclick="createTable()">
Enter
</button>
<button onclick="fillTable()" id="btn" type="button" class="btn btn-info">
Fill
I used jQuery
$(document).ready(function () {
$('#btn').click(function () {
$(colElem).append(1);
});
});
but with this code only bottom right corner is filled. Please can you give info how to fill all cells of the table with random number via Fill button
$(colElem) selector pointing to the last cell of the table... you need to select each and every cell and assign the random number... look into the below code (it will add random number between 0 to 99) to solve the issue... remove onclick="fillTable()" from the button..
$('#btn').click(function () {
$(tableElem).find("td").each(function(){
$(this).html(Math.floor(Math.random() * 100));
});
});

How to Check Password validation dynamically using jquery/javascript?

Kindly read my question fully before assign my one as duplicate.
Hi I tried to verify password dynamically during keypress. Actually it is working for me while enter the password. But When I delete the password only 2 conditions satisfies. My code and images below:
My password box html code is
<div class="form-group has-feedback">
<input class="form-control" id="NewPassword" placeholder="New Password" onkeypress="EnterPassword()" onkeydown="DeletePassword()" type="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
I used glyphicon-remove infront of each conditions for the password. When I enter the password each icon change to glyphicon-ok if the condition satisfies.
These are my password conditions with icon:
Lets assume my password as Password#123, it contains all my required things, so all the icons changed to ok.
But when I delete the password only 2 of the conditions satisfied.
Codes for the function below:
<script type="text/javascript" >
function EnterPassword() {
$("#NewPassword").keyup(function () {
var regex1 = new Array();
var regex2 = new Array();
var regex3 = new Array();
var regex4 = new Array();
regex1.push("[A-Z]"); //Uppercase Alphabet.
regex2.push("[a-z]"); //Lowercase Alphabet.
regex3.push("[0-9]"); //Digit.
regex4.push("[!###$%^&*]"); //Special Character.
if ($(this).val().length>6) {
$("#Length").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
for (var i = 0; i < regex1.length; i++) {
if (new RegExp(regex1[i]).test($(this).val())) {
$("#UpperCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex2.length; i++) {
if (new RegExp(regex2[i]).test($(this).val())) {
$("#LowerCase").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex3.length; i++) {
if (new RegExp(regex3[i]).test($(this).val())) {
$("#Numbers").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
for (var i = 0; i < regex4.length; i++) {
if (new RegExp(regex4[i]).test($(this).val())) {
$("#Symbols").removeClass("glyphicon glyphicon-remove").addClass("glyphicon glyphicon-ok");
}
}
});
}
function DeletePassword() {
$("#NewPassword").keyup(function () {
var regex1 = new Array();
var regex2 = new Array();
var regex3 = new Array();
var regex4 = new Array();
regex1.push("[A-Z]"); //Uppercase Alphabet.
regex2.push("[a-z]"); //Lowercase Alphabet.
regex3.push("[0-9]"); //Digit.
regex4.push("[!###$%^&*]"); //Special Character.
var thisVal =$(this).val();
if ($(this).val().length<6) {
$("#Length").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
for (var i = 0; i < regex1.length; i++) {
if (new RegExp(regex1[i]).test(!thisVal)) {
$("#UpperCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex2.length; i++) {
if (new RegExp(regex2[i]).test(!thisVal)) {
$("#LowerCase").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex3.length; i++) {
if (new RegExp(regex3[i]).test(!thisVal)) {
$("#Numbers").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
for (var i = 0; i < regex4.length; i++) {
if (new RegExp(regex4[i]).test(!thisVal)) {
$("#Symbols").removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-remove");
}
}
});
}
</script>
NOTE: UpperCase,LowerCase,Numbers,Symbols are the Id name that I gave to the tag where I used the glyphicon remove icon.
If my codes not working completely means my question may comes under duplicate. But Its Partially working, So kindly let me know if there is any mistake I did on my code.
Thanks in Advance
We can simplify your code a lot.
For a start instead of using inline event handlers we will use jQuery's .on to bind the event.
Next we'll consolidate your rules into a JSON object array with the rules target.
We then iterate the Regex based rules adding and removing classes as required
/*Actual validation function*/
function ValidatePassword() {
/*Array of rules and the information target*/
var rules = [{
Pattern: "[A-Z]",
Target: "UpperCase"
},
{
Pattern: "[a-z]",
Target: "LowerCase"
},
{
Pattern: "[0-9]",
Target: "Numbers"
},
{
Pattern: "[!###$%^&*]",
Target: "Symbols"
}
];
//Just grab the password once
var password = $(this).val();
/*Length Check, add and remove class could be chained*/
/*I've left them seperate here so you can see what is going on */
/*Note the Ternary operators ? : to select the classes*/
$("#Length").removeClass(password.length > 6 ? "glyphicon-remove" : "glyphicon-ok");
$("#Length").addClass(password.length > 6 ? "glyphicon-ok" : "glyphicon-remove");
/*Iterate our remaining rules. The logic is the same as for Length*/
for (var i = 0; i < rules.length; i++) {
$("#" + rules[i].Target).removeClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-remove" : "glyphicon-ok");
$("#" + rules[i].Target).addClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-ok" : "glyphicon-remove");
}
}
/*Bind our event to key up for the field. It doesn't matter if it's delete or not*/
$(document).ready(function() {
$("#NewPassword").on('keyup', ValidatePassword)
});
.glyphicon-remove {
color: red;
}
.glyphicon-ok {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group has-feedback">
<input class="form-control" id="NewPassword" placeholder="New Password" type="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div id="Length" class="glyphicon glyphicon-remove">Must be at least 7 charcters</div>
<div id="UpperCase" class="glyphicon glyphicon-remove">Must have atleast 1 upper case character</div>
<div id="LowerCase" class="glyphicon glyphicon-remove">Must have atleast 1 lower case character</div>
<div id="Numbers" class="glyphicon glyphicon-remove">Must have atleast 1 numeric character</div>
<div id="Symbols" class="glyphicon glyphicon-remove">Must have atleast 1 special character</div>
i give you simple example.
Html
<!DOCTYPE HTML>
<html>
<head>
<title>Password strength checker in jQuery</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><!-- jQuery Library-->
<link rel="stylesheet" href="css/passwordscheck.css" /><!-- Include Your CSS file here-->
<script src="js/passwordscheck.js"></script><!-- Include Your jQUery file here-->
</head>
<body>
<div id="container">
<div id="header">
<h2>Password Strength Checking with jQuery</h2>
<hr>
</div>
<div id="content">
<form id="register">
<label for="password"><b>Password : </b></label>
<input name="password" id="password" type="password" placeholder="Type Your Password here"/>
<span id="result"></span>
</form>
</div>
</div>
</body>
</html>
JS
$(document).ready(function() {
$('#password').keyup(function() {
$('#result').html(checkStrength($('#password').val()))
})
function checkStrength(password) {
var strength = 0
if (password.length < 6) {
$('#result').removeClass()
$('#result').addClass('short')
return 'Too short'
}
if (password.length > 7) strength += 1
// If password contains both lower and uppercase characters, increase strength value.
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
// If it has numbers and characters, increase strength value.
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
// If it has one special character, increase strength value.
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// If it has two special characters, increase strength value.
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 1
// Calculated strength value, we can return messages
// If value is less than 2
if (strength < 2) {
$('#result').removeClass()
$('#result').addClass('weak')
return 'Weak'
} else if (strength == 2) {
$('#result').removeClass()
$('#result').addClass('good')
return 'Good'
} else {
$('#result').removeClass()
$('#result').addClass('strong')
return 'Strong'
}
}
});
Reference : Link
one of the best example for you
i hope you understand.

submitting form via email with dynamic fields

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.

Categories

Resources