Cannot create multiple text box with different id using JavaScript and jQuery - javascript

I am unable create multiple text field dynamically using JavaScript and jQuery. My code is below:
<div class="col-md-3">
<div class="form-group">
<label for="ques">No of questions</label>
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" type="text">
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Questions</label>
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();">
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>
<div class="text-left" id="intro-add" style="display:none">
<input type="button" name="" class="btn btn-sm btn-info" value="Add">
</div>
</div>
</div>
<div id="container">
<div class="form-group" style="margin-top:5px;display:block" id="introBox0" >
<div>
<input type="text" style="width: 77.5%;float:left; margin-bottom:5px; margin-right:5px;" class="form-control inptbox0" id="scaleans00" name="labelname" placeholder="Answer" value="">
<input type="button" style="line-height:13px; margin-right:2px; margin-top:5px; float:left;" class="btn btn-danger btn-sm" name="labelminus" id="labelminus" value="-">
<div class="text-left" id="intro-add" style="display:block">
<input type="button" name="" class="btn btn-sm btn-info" value="Add" onclick="addMore(0,0)">
</div>
</div>
</div>
<hr>
</div>
Here user will create multiple question section and each question section user has to create multiple field using add button and will delete using minus button . Each question field should unique id.Suppose in section one there are 3 input field then its ids should be like this scaleans00,scaleans01,scaleans02... and for section two these should be scaleans10,scaleans11,scaleans12... and so on.
Here is my JavaScript code:
<script>
function addQuestionField() {
var get = $("#ques").val();
for (var i = 1; i < get; i++) {
$('#container').append('<div class="form-group dyn" style="margin-top:5px;display:block" id="introBox'+i+'"><div><input type="text" style="width: 77.5%;float:left; margin-bottom:5px; margin-right:5px;" class="form-control inptbox'+i+'" id="scaleans'+i+'0" name="labelname" placeholder="Answer" value=""><input type="button" style="line-height:13px; margin-right:2px; margin-top:5px; float:left;" class="btn btn-danger btn-sm" name="labelminus" id="labelminus" value="-"><div class="text-left" id="intro-add" style="display:block"><input type="button" name="" class="btn btn-sm btn-info" value="Add" onclick="addMore('+i+',0)"></div></div></div><hr>');
}
}
function deleteQuestionField() {
var textareas = $('#container .dyn');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
function addMore(parent,child){
var mainDiv='#introBox'+parent;
$(mainDiv).append('<div><input type="text" style="width: 77.5%;float:left; margin-bottom:5px; margin-right:5px;" class="form-control inptbox'+parent+'" id="scaleans" name="labelname" placeholder="Answer" value="">'+'<input type="button" style="line-height:13px; margin-right:2px; margin-top:5px; float:left;" class="btn btn-danger btn-sm" name="labelminus" id="labelminus" value="-"></div>');
repopulate(parent);
}
function repopulate(k){
var mainId='.inptbox'+k;
var j=0;
$(mainId).each(function(i, e) {
if(i==0){
$(this).attr('id', 'scaleans' + i+j);
$(this).next().attr('onClick', function(old, n) {
return 'removeThis(' + i + ','+j+')';
})
$(this).next().attr('id', function(old, n) {
return 'labelminus' + i+j;
});
}else{
$(this).attr('id', 'scaleans' + i+(j+1));
$(this).next().attr('onClick', function(old, n) {
return 'removeThis(' + i + ','+(j+1)+')';
})
$(this).next().attr('id', function(old, n) {
return 'labelminus' + i+(j+1);
});
}
})
}
function removeThis(r,t) {
$("#scaleans" + r+t).remove();
$("#labelminus" + r+t).remove();
repopulate();
}
</script>
Here I can not create as per my requirement. Here is my full code.

I will be explaining to you what is going on with the current code you have put in Plunker
function addQuestionField() {
var get = $("#ques").val();
for (var i = 1; i < get; i++) {
In Your method addQuestionFiled(), the value retrieved into get variable is not truthy, if you are not entering any value into the
number of questions
textfield. Hence the html will not get appended
Fill in the number of question as 2, and then click add it will keeping on appending the html to container div as the 'var get' will have the value 2 and 'var i' is less than 'var get'

Related

Multiple inputs with same name to write to database

I have a form and with several fields with the same name, I need to get this data in Django view and write to the database. For now, I am just trying to get the HTML data and render in the view but only the last value of the HTML form is displayed.
View
def agenda_padrao(request):
inicio = request.POST['inicio']
fim = request.POST['fim']
idempresa = request.POST['id']
if request.POST:
for i in inicio:
print(i)
return render(request, 'core/agenda.html')
agenda.html
<form method="POST" action="/agenda/padrao/">{% csrf_token %}
<div class="modal-body">
<div class="row ">
<h3>Horários</h3><br/>
<a class="btn btn-success" href="javascript:void(0)" id="addInput">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</a>
</div>
<div id="dynamicDiv">
<div class="row col-12">
<input type="time" class="form-control form-control" id="inicio" name="inicio[]" style="width: 150px; margin-right: 10px;">
<input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px;">
<input type="hidden" name="id" value="{{ user.id_empresa }}">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Confirmar Horário Padrão</button>
</div>
</form>
Javascript adding the fields
$(function () {
var scntDiv = $('#dynamicDiv');
$(document).on('click', '#addInput', function () {
$('<p>'+
'<input type="time" class="form-control form-control" id="inicio" name="inicio" style="width: 150px; margin-right: 10px;">'+
'<input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px; margin-right: 10px;">' +
'<a class="btn btn-danger" href="javascript:void(0)" id="remInput">' +
'<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>' +
'</a><br/>'+
'</p>').appendTo(scntDiv);
return false;
});
$(document).on('click', '#remInput', function () {
$(this).parents('p').remove();
});
});
You can get a list of values of inputs in views:
inicio = request.POST.getlist('inicio[]')

Find Value of textarea from closest row of table

I have a button Update in One td I want to fetch value of both textarea of td from same tr.
There are lots of tr so I have to use closest() method to find element. I have tried to find element but it's not working.
HTML :-
<tr>
<td>
<div class="agenda-date">
<div class="dayofmonth color_font_date">2017-05-31</div>
<div class="dayofweek">
Wednesday
</div>
</div>
</td>
<td>
<div class="row margin_two_planner">
<button type="button" class="btn btn-sm btn-primary">AM </button>
<a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="3" name="" class="number_planner"></a>
<label class="control-label"> 6 </label>
</div>
<div class="row margin_two_planner">
<button type="button" class="btn btn-sm btn-primary">PM </button>
<a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="4" name="" class="number_planner"></a>
<label class="control-label"> 2 </label>
</div>
</td>
<td style="width: 20%;">
<textarea id="" class="form-control initial_cap appointment_note" required="required" rows="3" name="appointment_note" cols="50" aria-required="true" disabled=""> APT -1 </textarea>
</td>
<td style="width: 20%;">
<textarea id="" class="form-control initial_cap holiday_note" required="required" rows="3" name="holiday_note" cols="50" aria-required="true" disabled=""> Holiday - 1 </textarea>
</td>
<td>
<div class="text-right">
<button type="button" id="" class="btn btn-primary appointment_edit_button">Edit </button>
<button type="button" id="" onclick="planner_note_edit(1)" class="btn btn-md btn-primary appointment_update_button" style="display:none"> Update </button>
<button type="button" id="" class="btn btn-md btn-cancel appointment_cancel_button" style="display:none">Cancel </button>
</div>
</td>
</tr>
Jquery :-
function planner_note_edit(planner_note_id)
{
appointment_note = $(this).closest('td').find(".holiday_note").val();
alert(appointment_note);
}
But I'm not able to fetch value of textarea from closest td.
You should get the textarea from current row.
So, please use .closest('tr')
appointment_note = $(this).closest('tr').find(".holiday_note").val();
Also, you have to pass the clicked button object. this in your function is a reference to the window object.
function planner_note_edit(planner_note_id,event)
{
appointment_note = $(event.target).closest('td').find(".holiday_note").val();
alert(appointment_note);
}
HTML
<button type="button" id="" onclick="planner_note_edit(1,event)" class="btn btn-md btn-primary appointment_update_button" style="display:none"> Update </button>

Get the id of button to Remove a input field on click of minus button

I have an option field with by default 2 option. I have a button "Add more Option", this will add a input field (containing minus button to remove) dynamically.
I want to remove the particular input field when user clicks minus button.
<div class="col-sm-4 col-sm-offset-4">
<form class="form-horizontal" action="index" method="post">
<div id="optionsList"class="form-group">
<label for="options">Options</label>
<input type="text" class="form-control" id="option1" placeholder="M S Dhoni">
<input type="text" class="form-control" id="option2" placeholder="Virat Kohli">
</div>
<div class="form-group">
<button type="button" class="btn btn-lg btn-default" id="moreOptions">Add More Options</button>
</div>
</form>
</div>
Here is the script -
$(document).ready(function(){
var optionNo = 2;
$("#moreOptions").click(function(){
optionNo = optionNo + 1;
$("#optionsList").append
('<div class="input-group" id="inputField' + optionNo +'"><input type="text" class="form-control" placeholder="New option field" id="option' + optionNo +'"><i class="input-group-btn"><button class="btn btn-danger" type="button" id="removeBtn' + optionNo +'"><i class="glyphicon glyphicon-minus"></i></button></i></div>');
});
// here i want to write code to remove that input field
});
I tried this -
$(".input-group").click(function(){
const id = this.id;
$("#id").remove();
});
Please suggest. Any other way to do this will also be fine.
Use classes instead of worrying about incrementing ID's. That approach gets too complicated to manage sometimes and it isn't needed at all
Simplified append html with new class remove-btn instead of id on button:
$("#optionsList").append
('<div class="input-group"><input><button class="btn btn-danger remove-btn" type="button"></button></div>');
Delegated event listener for any .remove-btn added to dom in future
$(document).on('click', '.remove-btn', function(){
// "this" is current button event occurs on
$(this).closest('.input-group').remove()
})
Firstly don't use id's in dynamically created elements if you are not going to change it's value and end up with multiple elements with the same ID instead use classes. ie.
class="removeBtn'
Next for dynamically created elements use event bubbling to attach events
$("body").on("click", ".removeBtn", function(){
$(this).closest(".input-group").remove();
});
Because you add on the fly the new button you need to delegate the click event to the document:
$(document).on('click', ".input-group button", function(e) {
$(this).closest('.input-group').remove();
});
This part: ".input-group button" means: listen for click event related to button element inside an input-group
The closest used to get the parent div to be removed.
The snippet:
$(document).ready(function(){
var optionNo = 2;
$("#moreOptions").on('click', function(e) {
optionNo = optionNo + 1;
$("#optionsList").append
('<div class="input-group" id="inputField' + optionNo +
'"><input type="text" class="form-control" placeholder="New option field" id="option' + optionNo +
'"><i class="input-group-btn"><button class="btn btn-danger" type="button" id="removeBtn' + optionNo +
'"><i class="glyphicon glyphicon-minus"></i></button></i></div>');
});
// here i want to write code to remove that input field
$(document).on('click', ".input-group button", function(e) {
$(this).closest('.input-group').remove();
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-sm-4 col-sm-offset-4">
<form class="form-horizontal" action="index" method="post">
<div id="optionsList"class="form-group">
<label>Options</label>
<input type="text" class="form-control" id="option1" placeholder="M S Dhoni">
<input type="text" class="form-control" id="option2" placeholder="Virat Kohli">
</div>
<div class="form-group">
<button type="button" class="btn btn-lg btn-default" id="moreOptions">Add More Options</button>
</div>
<div class="form-group">
<button type="submit" class="btn btn-lg btn-success" name="button">Submit</button>
</div>
</form>
</div>
Try with the below code. Hope it helps.
var counter = 1;
$(document).on('click', 'button#moreOptions', function(){
$("#optionsList").append
('<div class="input-group" style="padding:5px;"><input type="text" class="form-control" placeholder="New option field '+ counter +'"><i class="input-group-btn"><button class="btn btn-danger btn-minus" type="button"><i class="glyphicon glyphicon-minus"></i></button></i></div>');
counter++;
});
$(document).on('click', 'button.btn-minus', function(){
$(this).parents('div.input-group').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-sm-4 col-sm-offset-4">
<form class="form-horizontal" action="index" method="post">
<div id="optionsList"class="form-group">
<label>Options</label>
<input type="text" class="form-control" id="option1" placeholder="M S Dhoni">
<input type="text" class="form-control" id="option2" placeholder="Virat Kohli">
</div>
<div class="form-group">
<button type="button" class="btn btn-lg btn-default" id="moreOptions">Add More Options</button>
</div>
</form>
</div>
Add a onclick handler when you generate your button as following :
$("#removeBtn" + optionNo + "").click(function()
{
$("#inputField" + optionNo + "").remove();
});

Logic on total sum of input values

I have created 4 input boxes with plus and minus to increase and decrease the value. I want to make a logic that as soon as the sum of all 4 values adds up to 5, it should disable the plus buttons and do not allow the user to add more.
This is the HTML:
<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>
<div id="field2">field 3
<button type="button" id="sub3" class="sub">-</button>
<input type="text" id="3" value="0" class="field" />
<button type="button" id="add3" class="add">+</button>
</div>
<div id="field2">field 4
<button type="button" id="sub4" class="sub">-</button>
<input type="text" id="4" value="0" class="field" />
<button type="button" id="add4" class="add">+</button>
</div>
This is the jQuery I am using to increase/decrease the values:
$("input").prop('disabled', true);
$('.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);
});
This should work
$('.add').click(function () {
var value1 = $('#field1').find('input').val();
var value2 = $('#field2').find('input').val();
var value3 = $('#field3').find('input').val();
var value4 = $('#field4').find('input').val();
if ( value1 + value2 + value3 + value4 >= 5){
$('.add').prop('disabled', true);
} else {
$(this).prev().val(+$(this).prev().val() + 1);
}
});

Cannot delete the radio button input field dynamically using JavaScript/jQuery

I am creating multiple text area, radio button field and drop down list by click on a plus button. Here I need when user will click on minus button the last all 3 type item should delete but it's not happening like that.
Here is my code:
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" type="text">
<label>Questions</label>
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();">
<input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
<div id="container">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
</div>
<div class="col-md-9">
<div style="margin-top:37px;">
<div style="float:left; margin-right:10px;">
<input type="radio" name="answer_type0" id="answer_type0" onClick="selectScale(this.value,'0');">
</div>
<div style="float:left; margin-top:-10px;display:none;" id="scaleid0">
<select class="form-control" id="nscale0" name="noofscale0">
<option value="">Select Answer Type</option>
<option value="1">Cuttuck</option>
<option value="1">BBSR</option>
</select>
</div>
</div>
</div>
The JavaScript code is given below.
function addQuestionField(){
var get =$("#ques").val();
if(get===null || get===''){
alert('Please add no of questions');
}else{
for(var i=1;i<get;i++){
$('#container').append('<div class="row"><div class="col-md-3"><div class="form-group"><textarea class="form-control" name="questions'+ i +'" id="questions'+ i +'" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div> <div class="col-md-9" ><div style="margin-top:37px;"><div style="float:left; margin-right:10px;"> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');"></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="1" >Cuttuck</option><?php } ?></select></div><div style="clear:both;"></div></div></div><div>');
}
}
}
function deleteQuestionField(){
var get =$("#ques").val();
var textareas = $('#container textarea');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
Here when I am clicking - button only the last text area is removing. But I need to delete the respective radio button and drop down list(if exist) with text area. Here the total plunkr code is present.
Add a wrapper class for the input set all together and remove it on delete, always in templating, try to use wrapper selector to isolate blocks of html code
$('#container').append('<div class="row dyn">
https://plnkr.co/edit/kBWcs6zUmMndB3RwXMcF?p=preview
Try this and please close your div properly i think You forgot to put one div closing tag.
function deleteQuestionField(){
var get =$("#ques").val();
var textareas = $('#container').find('textarea');
if (textareas.length !== 0) {
$('#container div.row:last-child').remove();
$('#ques').val(textareas.length - 1);
}
}
you can delete the last row which you added dynamically and which contains the textarea, radio button and dropdown list.
function deleteQuestionField(){
$("#container>row").last().remove();
}
This worked for me,
HTML :
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" type="text">
<label>Questions</label>
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+">
<input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-">
<div id="container">
</div>
JS (jQuery) :
$(document).ready(function(){
$('#plus').click(function(){
var get =$("#ques").val();
if(get===null || get===''){
alert('Please add no of questions');
}else{
for(var i=1;i<=get;i++){
$('#container').append('<div class="row"> <div class="col-md-9" ><div style="margin-top:37px;"><div style="float:left; margin-right:10px;"> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');"></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="1" >Cuttuck</option><?php } ?></select></div><div class="col-md-3"><div class="form-group"><textarea class="form-control" name="questions'+ i +'" id="questions'+ i +'" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div><div style="clear:both;"></div></div></div><div>');
}
}
});
$('#minus').click(function(){
var get =$("#ques").val();
var textareas = $('#container textarea');
var radiobtns = $('#container input');
if (textareas.length !== 0) {
textareas.last().remove();
radiobtns.last().remove();
$('#ques').val(textareas.length - 1);
}
});
});
See the jsfiddle

Categories

Resources