Limit number of javascript automated generated checkbox - javascript

kinda worried with following code that should automatically generate checkbox content AND limit up to 3 the number of checked boxes.
Separately both codes work fine, the issue occurs when they are combined:
Fiddle
$('input[type=checkbox]').change(function(e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
}
})
var skills = ["centres", "tirs", "dribbles", "passes", "vitesse"]
var skillContainer = $("#skillsContainer");
skills.forEach(skill => skillContainer.append('<li> <input type=\"checkbox\" id=\"' + skill + '\" value=\"' + skill + '\"> <label for=\"' + skill + '\"> ' + skill + ' </label> </li>'));
$("#skillsContainer").append(checkboxElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="competencies" action="algo.php" method="POST">
<div class="container">
<ul class="ks-cboxtags" id="skillsContainer">
<input class="button" type="submit" value="Valider">
</ul>
</div>
</form>

You mean this?
You need to delegate when you create dynamic elements
OR add the event handler after the generation
$('#skillsContainer').on("change", 'input[type=checkbox]', function(e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
}
})
var skills = ["centres", "tirs", "dribbles", "passes", "vitesse"]
$("#skillsContainer").html(skills.map(skill => '<li> <input type=\"checkbox\" id=\"' + skill + '\" value=\"' + skill + '\"> <label for=\"' + skill + '\"> ' + skill + ' </label> </li>').join(""));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="competencies" action="algo.php" method="POST">
<div class="container">
<ul class="ks-cboxtags" id="skillsContainer">
<input class="button" type="submit" value="Valider">
</ul>
</div>
</form>

Pure javascript to check checked checkbox length
var eLength = element.length;
var i = 0;
var checkedCheck;
checkbox.forEach(checkBox => {
checkBox.addEventListener('click',function(){
if(this.checked){
i++;
if(i > 3){
checkBox.disabled = true;
alert('Limit reached');
}
}
});
});

Related

on plus icon dynamic textbox is not getting generated in jquery

What I want is, I want to generate a new input type = text whenever a plus icon is getting clicked. SO I have written below code for the same.
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
alert(numItems);
if (numItems != 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.substr(13, lastfieldsid.length));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata1" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata1" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'></i></div></td></tr>"
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
</div>
Couple of problem in your code.
Use slice(-1) to get last character of id. It's remove your dependency using hardcode substr(13,... and you can use that value to increase new generated id by +1 .
Check length for input using $('.form-group').find('input').length < 5 which check the length of input inside form-group class and user only able to add 5 inputs.
Finally don't forgot to append your generated element on form-group class using $('.form-group').append(tr); .
I also add example to delete added tr using minus class.
Example:
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
if ($('.form-group').find('input').length < 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.slice(-1));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'>Remove</i></div></td></tr>";
}
$('#yourid').append(tr);
} else {
alert("warning........")
}
}
$(document).on('click', 'div.minus', function() {
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group" id="yourid">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true">icon</i>
</div>
</div>
Assuming that you are going to add new input field in div#dvDVRdata1. You need to append the HTMLcontent to that div as following:
$('#dvDVRdata1').append(tr);
The thing is you need to append the element, which you did not do in the code in your question.
As for remove, you also have not done it in your question yet. Here's the example of add and remove.
$(document).ready(function(){
$('.add').on('click', function () {
addDynamicTextbox();
});
$('.del').click(function (e) {
deleteDynamicTextbox(e);
});
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems != 5) {
var formGroup = $('.form-group');
var elem = `<div class="dvDVRdata" id="dvDVRdata${numItems+1}">
<label for="txtDVRAddress${numItems+1}">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress${numItems+1}" runat="server" />
</div>`;
formGroup.append(elem);
}
}
function deleteDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems > 1) {
$(`#dvDVRdata${numItems}`).remove();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/js/all.min.js" integrity="sha512-rpLlll167T5LJHwp0waJCh3ZRf7pO6IT1+LZOhAyP6phAirwchClbTZV3iqL3BMrVxIYRbzGTpli4rfxsCK6Vw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<div class="dvDVRdata" id="dvDVRdata1">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" />
</div>
</div>
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
<div class="del">
<i class="fa fa-minus" aria-hidden="true"></i>
</div>

User can add new input field with click on button - how to limit/set max fields?

The user can add a new input-field with a click on "Add". My problem is that there is no limit but I want to limit the max. input-fields to 50. Im not that good with js but I think it could done with:
if id or input-field = 50
than disable Add-button. And enable if id or input-field is under 50.
This is my code so far:
function addFormField() {
var id = document.getElementById("id").value;
$("#divTxt").append(
"<p id='row" +
id +
"'><label for='txt" +
id +
"'>Field " +
id +
" <input type='text' size='20' name='txt[]' id='txt" +
id +
"'> &nbsp<a href='#' onClick='removeFormField(\"#row" +
id +
"\"); return false;'>Remove</a><p>"
);
id = id - 1 + 2;
document.getElementById("id").value = id;
}
function removeFormField(id) {
$(id).remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Add</p>
<form action="#" method="get" id="form1">
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
<p><input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset"></p>
</form>
Thank you
You can set a variable and add 1 to it until the count reaches 50 like this
let currentCount = 0;
function addFormField() {
if(currentCount < 50){
currentCount+= 1;
var id = document.getElementById("id").value;
$("#divTxt").append(
"<p id='row" +
id +
"'><label for='txt" +
id +
"'>Field " +
id +
" <input type='text' size='20' name='txt[]' id='txt" +
id +
"'> &nbsp<a href='#' onClick='removeFormField(\"#row" +
id +
"\"); return false;'>Remove</a><p>"
);
id = id - 1 + 2;
document.getElementById("id").value = id;
}else{
alert('You can not add more then 50')
}
}
function removeFormField(id) {
$(id).remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Add</p>
<form action="#" method="get" id="form1">
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
<p><input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset"></p>
</form>
You have to check for the length of child p tags of your div like this:
if($("#divTxt > p").length) < 50 ){
var id = document.getElementById("id").value;
$("#divTxt").append(
"<p id='row" +
id +
"'><label for='txt" +
id +
"'>Field " +
id +
" <input type='text' size='20' name='txt[]' id='txt" +
id +
"'> &nbsp<a href='#' onClick='removeFormField(\"#row" +
id +
"\"); return false;'>Remove</a><p>"
);
id = id - 1 + 2;
document.getElementById("id").value = id;
}

How to add new input to html document on input typing using jquery?

I want to add dynamic input.
I have one input already created and if someone write something into it, it will add new input below it and if again some one write something into newly created input, it will call the same jquery and generate another input below and so on. ( same like google's contact form for address and email )
How can I do this.
I have tried this but it is giving me for each keypress new input and also for newly created input it is not working
var counter = 2;
$("input[id^='textbox']").keypress(function () {
if (counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label>
<input type='textbox' id='textbox1' >
</div>
</div>
You should use .on() to attach event handler to new input. Also check if parent of typing text is last-child, then add new row.
$(document).on("keyup change", "input[id^='textbox']", function(){
if ($(this).parent().is(":last-child") && $(this).val() != ""){
var index = $(this).parent().index() + 2;
$("#TextBoxesGroup").append('<div id="TextBoxDiv'+index+'"><label>Textbox #'+index+' : </label><input type="textbox" id="textbox'+index+'" ></div>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label>
<input type='textbox' id='textbox1' >
</div>
</div>

How do I create a search against JSON data with input and radio buttons?

So far I am able to display the data in an HTML page. However I am stuck when it comes to searching against the Description field and also filtering this data according to Location radio buttons selected.
HTML:
<form>
<input id="searchterm" type="search" name="query" placeholder="Search">
<input type="radio" name="location" value="houston">
<label for="houston">Houston</label>
<input type="radio" name="location" value="austin">
<label for="austin">Austin</label>
<input type="button" name="searchbutton" value="search" onclick=search();>
</form>
JSON data:
[
{
Description: A bunch of text from which I need to search against
Location: This will be selected by a radio button
}
]
Here is what I have tried:
JS CODE:
function search() {
var $searchField = $('#searchterm');
var query = $searchField.val();
$.getJSON("API LINK HERE", function(data) {
var output="<ul>";
$.each( data, function (i, item) {
output+="<li class='results'><div class='title'><div class='mainCat'>" + data[i].MainCategoryName + "</div>";
output+="<div class='AdID'>" + data[i].AdID + "</div></div>";
if(data[i].PhotoUrl !== null){
output+="<img class='image' src=" + " ' " + data[i].PhotoUrl + " ' " + "></img>";
}
output+="<div class='description'>" + data[i].Description + "</div>";
output+="<button type='submit' class='goToAd' formaction=" + data[i].AdUrl + ">Go To Ad </button> </li>" ;
});
output+="</ul>";
$("#content").html(output);
});
}

How to post variable from field in page 1 to page 2

My code is trying to allow user to add new text field by clicking the add button. I want to post all the text fields the user had added (be it 2, 3, 4 or more) to the next page so I can retrieve the data that the user had entered.
P/S: Added new requirement: Retrieve data and print the data that the user had entered.
Here is my code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var counter = 2;
$("#addMenuTab").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Menu Tab #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeMenuTab").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
<form name="basicInfo" action="contents.php" method="post">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Menu Tab #1 : </label>
<input type='text' id='textbox1' >
</div>
</div>
<br/>
<input type='button' value=' Add Menu Tab ' id='addMenuTab' />
<input type='button' value=' Remove Menu Tab ' id='removeMenuTab' />
</form>
</body>
</html>
You can get all these fields and their values on contents.php under $_POST global array.
For example:
<?php
echo "<pre>";
print_R($_POST);
echo "</pre>";
?>
I have a simple solution for your problem.
Use one counter to count the number of textfields.
We can later pass this variable to html.
Modify your javascript:-
<script>
$(document).ready(function(){
var counter = 2;
$("#count").val(counter-1);
$("#addMenuTab").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Menu Tab #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$("#count").val(counter);
counter++;
});
$("#removeMenuTab").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#count").val(counter-1);
});
});
</script>
Now add one hidden field in your html form. The value of this hidden field will be the total number of texfields.
<input type='hidden' id='count' name='counter' value=''/>
In your contents.php add the below given code.
$count=$_POST['counter'];
for($i=1;$i<=$count;$i++)
{
echo "value from textbox$i is".$_POST["textbox$i"]."<br/>";
}
Here you will get the total number of textfields in the variable $count
Since the name of your texfields are like textbox1,textbox2..etc You can use a loop for getting all the data from your previous page using the POST method.
Also add name attribute to your initial textbox to get this work.
<input type='text' id='textbox1' name="textbox1" >
I don' understand what is your question. If you add some inputs like textbox10, you will be able to read textbox10 without problems on your server.

Categories

Resources