I written this code for creating new input fields, and i need to somehow modify it so i can remove the fields. I tought about adding var counter to mySpan and then i make$(#removeBox).click(function() and there i can get an id of the input field i need to delete. But i cannot make span clickable, and when I try to do it with like this <a class="deleteBox' + counter'"><span class="glyphicon glyphicon-remove"></span></a> It says that I am missing ). I know there are some solutions on this problem here, but i wanted to make mine work.
var counter = 2;
$("#addTextField").click(function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'textboxdiv'+counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter + '" placeholder="Category" /><span id="mySpan" class="glyphicon glyphicon-remove"></span>');
newTextBoxDiv.appendTo("#textboxgroup");
counter++;
});
try like this: The trick is to remove the element you clicked on which you can get with $(this) inside the click
var counter = 0;
$("#addTextField").on('click', function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'textboxdiv'+counter);
newTextBoxDiv.after().html('<div class="wrapper">' + counter + '<input type="text" name="textbox' + counter + '" placeholder="Category" /><span class="glyphicon glyphicon-remove">remove</span></div>');
newTextBoxDiv.appendTo("#textboxgroup");
counter++;
});
$('body').on('click', '.glyphicon-remove', function(){
$(this).closest('.wrapper').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addTextField">click to add</div>
<div id="textboxgroup"></div>
In your code you added an ID <span id="mySpan" on every click which is bad cause an ID should always be unique. So if you add it more than once it is not unique anymore. Better use classes instead...
try this:
var counter = 0;
$('#add').click(function() {
$('#target').append('<span>New Input: <input type="text"><button id="remove' + counter + '">Remove</button><br></span>');
$('#remove' + counter).click(function() {
$(this).parent().html('');
counter--;
});
counter++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="add">Add</button>
<div id="target"></div>
Related
I have an html form. Whenever i click add button another copy of it appends. Whenever i click add button, id of my elements increases such as username_0, username_1, username_2... There are 2 radio buttons on my form that whenever i choose second radio button, a hidden textarea appears. Problem is i'm having problem with choosing my dynamic id's of radio buttons. I made a function but its only working for first element since i can't get dynamic id's
<label for="evetKontrol_0">Evet</label>
<input type="radio" id="evetKontrol_0" name="uygun_0" onclick="javascript:yesnoCheck();" value="uygun" checked>
<label for="hayirKontrol_0">Hayır</label>
<input type="radio" id="hayirKontrol_0" name="uygun_0" onclick="javascript:yesnoCheck();" value="uygunDegil">
<div id="ifNo_0" style="visibility:hidden">
<strong>Uygun Olmama Sebebi:</strong> <input type="textarea" id="hayirSebep_0" name="hayirSebep" style="height: 75px"><br>
</div>
function yesnoCheck() {
if (document.getElementById('evetKontrol_0').checked) {
document.getElementById('ifNo_0').style.visibility = 'hidden';
}
else document.getElementById('ifNo_0').style.visibility = 'visible';
}
I need to be able to get my evetKontrol_#somenumber for my function for every copy of my form.
JSfiddle/ all of my code
I tried to use jQuery( "[attribute*='value']" ) but i couldn't manage to work it out.
Consider the following.
Working Example: https://jsfiddle.net/Twisty/sonvakq2/21/
JavaScript
$(function() {
function addElement(tObj) {
var counter = $("[id^='ogrenci']", tObj).length;
var html = '<div class="col-auto" id="ogrenci_' + counter + '"><label for="ad">Ad</label><input type="text" name="ad[]" class="form-control" id="ad_' + counter + '" placeholder="Öğrencinin Adı"/><label for="soyad">Soyad</label><input type="text" name="soyad[]" class="form-control" id="soyad_' + counter + '" placeholder="Öğrencinin Soyadı"/><label for="no">No</label><input type="text" name="numara[]" class="form-control" id="no_' + counter + '" placeholder="Öğrencinin Numarası"><label for="course">Bölümü</label><input type="text" name="bolum[]" class="form-control" id="course_' + counter + '" placeholder="Öğrencinin Bölümü"><label for="alKredi">Almak İstediği Kredi</label><input type="text" name="alKredi[]" class="form-control" id="alKredi_' + counter + '" placeholder="Almak İstediği Kredi"><label for="verKredi">Alabileceği Kredi</label><input type="text" name="verKredi[]" class="form-control" id="verKredi_' + counter + '" placeholder="Alabileceği Kredi"><label for=""><strong>Uygun mu?</strong> </label><br><label for="evetKontrol_' + counter + '">Evet</label><input type="radio" id="evetKontrol_' + counter + '" name="uygun_' + counter + '" value="uygun" checked><label for="hayirKontrol_' + counter + '">Hayır</label><input type="radio" id="hayirKontrol_' + counter + '" name="uygun_' + counter + '" value="uygunDegil"><div id="ifNo_' + counter + '" style="visibility:hidden"><strong>Uygun Olmama Sebebi:</strong> <input type="textarea" id="hayirSebep_' + counter + '" name="hayirSebep" style="height: 75px"><br></div><div class="input-group-addon"><span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</div></div>';
tObj.append(html);
}
function showHidden() {
$("[id^='evetKontrol']").each(function(i, el) {
var rel = $("#ifNo_" + i);
if ($(el).is(":checked")) {
rel.show();
} else {
rel.hide();
}
});
}
//add more fields group
$("#add").click(function() {
addElement($("#container"));
});
//remove fields group
$('#container').on('click', "a[id^='remove']", function() {
$(this).parents('div.col-auto').remove();
});
$("#container").on("click", "input[type='radio']", showHidden);
});
Your fiddle wasn't configured properly, so I addressed that first. I moved a lot of the repeatable items into Functions. Switched it all the jQuery and removed any of the local javascript calls.
You can see examples of how to use the Attribute selector in a relative manner to select items you want.
See More: https://api.jquery.com/category/selectors/attribute-selectors/
You shouldn't need to use IDs for this. Just capture the onclick event and pass a boolean to determine if the hidden input should be shown. If you have multiple inputs to show and hide separately, you could pass the ID of the input along with the boolean.
function yesnoCheck(show) {
var ta = document.getElementById('hiddenTA');
if (show) {
ta.style.visibility = 'visible';
} else {
ta.style.visibility = 'hidden';
}
}
<label for="user1_0">User 1</label>
<input type="radio" name="users" id="user1_0" onclick="yesnoCheck(false)" checked />
<label for="user2_0">User 2</label>
<input type="radio" name="users" id="user2_0" onclick="yesnoCheck(true)" />
<input style="visibility:hidden" id="hiddenTA" />
In order to get the evetKontrol_#somenumber, pass that number in the onclick function.
In your JSfiddle, this would mean concatenating the counter variable into the function parameters like
... onclick="javascript:yesnoCheck(' + counter + ');" ...
Then update the function to use that value:
function yesnoCheck(counter) {
if (document.getElementById('evetKontrol_' + counter).checked) {
document.getElementById('ifNo_' + counter).style.visibility = 'hidden';
} else {
document.getElementById('ifNo_' + counter).style.visibility = 'visible';
}
I'm trying to make a button that when clicked displays only one div. If the user chooses they can click on the remove button and the data in any fields will be cleared and the text inside the div deleted. If a user chooses they can click the button again to bring back the div but cannot create the div more than once. I can make the initial div appear like its suppose to but beyond that I'm stuck.
Here is a list of things I've tried
$(document).on('click', '.remove', function(){
$document.getElementById("demo") .remove('.innerHTML');
$(document).on('click', '.empty', function(){
$('#demo').empty();
});
});
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = '<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>';
}
$(document).on('click', '.empty', function() {
$('#demo').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Add Renters</button>
<p id="demo"></p>
</body>
</html>
You're close check those steps to achieve what you want :
Add type="button" to your button to prevent the submit when you click.
Remove the inline onClick attribute and attach the click event from the JS code.
Check inside myFunction() function if the demo is empty or not before adding the content.
Attach another click event using event delegation on() (since the element was added dynamically to the DOM) to the button with .remove class to remove the content.
NOTE : Since you're using jQuery prevent the mix with vanillaJS like this line :
document.getElementById("demo").innerHTML = ...
Will be better to be :
demo.html(...)
$('button').on('click', myFunction);
$('body').on('click', '.remove', function() {
$('#demo').empty();
});
function myFunction() {
var demo = $('#demo');
if (!demo.html().length) {
demo.html('<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button type="button">Add Renters</button>
<p id="demo"></p>
</body>
</html>
I'm creating a set of textboxes and some drop downs using jQuery. The add function is working with out any issues.
My problem is with the delete function function works nicely as long as the user deletes one after the other but if the user delete from some where else the number sequence get messed up. Which breaks the 1,2,3,4 ... etc and sets the number which was deleted last.
As an example if the user deletes number 4 out of 7 errors the functions sets the last number as 4 when the user clicks the add button the next number generated will be 5 not the correct last number. I want to rest the rest of the numbers when something get removed from the middle.
I'm storing the last number in a hidden filed called stValue which is getting reset when deleting.
My problem is here I can't get my head around to think of way to reset this when deleting from some where else and then reset the entire error number row numbers when something get removed from the middle. Can you guys help me with this below is my code.
jsFiddle will help to understand better
JQuery:
//Add and remove function for the error text boxes
$(document).ready(function () {
$(document).on('click','.addRow',function () {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/);//Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_'+btnId).prop("disabled", true);//Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function () {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
alert(errNoList);
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_'+errNoList).prop('disabled',false);// Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
});
});
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1)+2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="'+genNum+'" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_'+genNum+'" data-bid="addRow_'+genNum+'" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_'+genNum+'" data-bid="delRow_'+genNum+'" value="Delete"/><br />'
}
HTML:
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%"/>
<input type="hidden" value="1" id="stValue"/>
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add"/>
</div>
</div>
</div>
**UPDATE:**Completely changed the code now it's much more simpler adding the solved answer here so it might help some one in the future.
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var btnId = $("#stValue").val(); //Read the value of stValue
btnId = btnId - 1; //Deduct 1 from the value to get the last ID
//Enables the 1st add button if the value equals 1
if (btnId === 1) {
$('#addRow_' + btnId).prop('disabled', false);
}
$(this).parent().remove(); //Remove the text row from the list.
resetErrorNo(); //Calls the reset function
});
});
//Reset the entire error count number index
function resetErrorNo() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
$("#stValue").val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>
Try with whenever, you delete any row, update all input with new number.
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
Full Code
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_' + errNoList).prop('disabled', false); // Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
rearrange();
});
});
function rearrange() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>
I have a form where users have 10 text fields. But initially only 1 text field is shown. If the user needs to enter more data they can click on the add one button and then displays the next text field from the maximum of 10.
like so:
Im working with angular.js so I thought about using ng-show to hide & show fields.
<div class="form-group">
<input type="text" class="form-control" name="pointOne" ng-show="pointOne">
<input type="text" class="form-control" name="pointTwo" ng-show="pointTwo">
<input type="text" class="form-control" name="pointThree" ng-show="pointThree">
<span><button ng-click="addOne()">Add One</button></span>
</div>
I am unable to figure out the most effective way to doing this. Any hints, help or suggestions would be great.
Haven't tested it but this is how I would do it:
<div class="form-group" >
<input ng-repeat="i in getNumber(number)" type="text" class="form-control" name="point{{i}}" ng-show="$index<=counter">
<span><button ng-click="addOne()">Add One</button></span>
</div>
And in your controller just add something like this:
$scope.number = 10;
$scope.getNumber = function(num) {
return new Array(num);
}
$scope.counter=0;
$scope.addOne= function() {
$scope.counter++;
}
You could easily add elements to the DOM:
function createPetField() {
var input = document.createElement('input');
input.type = 'text';
input.name = 'pet[]';
return input;
}
var form = document.getElementById('myForm');
document.getElementById('addPet').addEventListener('click', function(e) {
form.appendChild(createPetField());
});
To go the Angular route, I'd suggest using ng-repeat. Here's a fiddle that might not be exactly what you're looking for, but it shows how to use ng-repeat and you can modify as needed:
Fiddle: https://jsfiddle.net/jvsnao97/5/
<body ng-app="myApp" ng-controller="myController">
<button ng-click="add_input()">Add Input</button>
<br/><br/>
<input type="text" class="form-control" ng-repeat="x in random_array" name="point{{$index}}">
</body>
var app = angular.module("myApp", []);
app.controller("myController", ["$scope", function($scope) {
$scope.random_array = [0]
$scope.add_input = function() {
var i = $scope.random_array.length
$scope.random_array.push(i)
}
}]);
When you want a new <input>, you simply push a new element to $scope.random_array.
Probably good way is to make array of input fields and then ng-repeat them. When user clicks on AddOne, then just push input field in array, and it will be there.
<html>
<head>
<title>jQuery add / remove textbox</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").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>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>
JQuery can be used to add inputs in your addOne() method.
Like so:
var maxInputs = 10;
var currentInput = 0;
function addOne() {
currentInput++;
if (currentInput > maxInputs) {
currentInput = maxInputs;
return;
}
var name = "point" + currentInput;
var $input = $("<input type='text' class='form-control' name='" + name + "' ng-show='" + name + "'>");
$(".form-group").append($input);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<span><button onclick="addOne()">Add One</button></span>
</div>
I'm trying to add dynamically input fields in Codeigniter when the user clicks the link but it doesn't seem to work. It will be really helpful if someone can figure it out.
My JS code is:
<script src="js/jquery.js" type="text/javascript">
var count = 1;
jQuery(document).ready(function() {
$('p#add_field').click(function(){
count += 1;
$('#language').append(
'<strong>Language #' + count + '</strong><br />'
+ '<input id="language' + count + '"name="languages[]' + '" type="text" /><br />' );\
});
});
</script>
And my form code is:
<div id="container">
some code
<div id="body">
some more code
<div id="language">
<p id="add_field">Προσθηκη Γλώσσας</p>
</div>
</div>
</div>
var count = 1;
$('p#add_field').click(function(){
count += 1;
var html='<strong>Language #'+ count +'</strong><br />'+'<input id="language'+ count +'"name="languages[]'+'" type="text" /><br />';
$('#language').prepend(html);
});
remove all the spaces in appending html . javascript gives Unterminated String literal errors
fiddle