Add input forms dinamically trough AJAX and JQUERY - javascript

The problem I'm having right now is that the content I want to append now is too to just creating it inside the main JavaScript file.
Is there a way that I can put this content inside some other HTML file and then call it with AJAX in the JavaScript file and append this content maybe in a loop to append it the number of times chosen from a select input tag?
Here is the select input code:
<label for="beneficiarios">Cantidad de beneficiarios</label>
<select name="beneficiarios" id="beneficiarios">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Here is the content I want to append:
<div class="row beneficiario-info">
<div class="col-md-6">
<div class="form-group w-75">
<label for="bene-nombreyapellido">Nombre y Apellido</label>
<input type="text" name="bene-nombreyapellido" id="bene-nombreyapellido" class="form-control">
</div>
<!-- form group -->
<div class="form-group w-75">
<label for="bene-ci-numero">Cedula de identidad</label>
<div class="input-group">
<div class="input-group-prepend">
<select name="bene-ci-tipo" id="bene-ci-tipo" class="custom-select">
<option value="VE">V</option>
<option value="EX">E</option>
</select>
</div>
<!-- cedula tipo prepend -->
<input type="text" name="bene-ci-numero" id="bene-ci-numero" class="form-control" maxlength="8">
</div>
<!-- input group -->
</div>
<!-- form group -->
</div>
<!-- col -->
<div class="col-md-6">
<div class="form-group w-75">
<label for="parentezco">Parentezco</label>
<select name="parentezco" id="parentezco" class="custom-select">
<option value="">---------</option>
<option value="hijo">Hijo</option>
<option value="padre">Padre</option>
<option value="hermano">Hermano o Hermana</option>
<option value="conyugue">Conyugue</option>
</select>
</div>
<div class="form-group">
<label for="servicioadicional">Servicios Adicionales</label>
<select name="servicios_beneficiario" class="custom-select" id="servicios_beneficiario" multiple="multiple">
<option value="medico">Médico</option>
<option value="odontologico">Odontológico</option>
<option value="funerario">Funerario</option>
<option value="vial">Víal</option>
</select>
</div>
</div>
<!-- col -->
</div>
<!-- row beneficiario -->
Here is the JavaScript code:
var number = 0;
$('#ctd-beneficiarios').on('change', function() {
numero = $(this).val();
beneficiarios_wrapper.html('');
for (var i = 0; i < numero; i++) {
}
});
beneficiarios_wrapper is the div where I want to append the content to.

Rather than storing it in a separate file and retrieving it via AJAX, use a
hidden template like so:
$main = $('#main');
for(var i=0;i<5;i++){
var $template = $('.template').clone();
$template.removeClass('template');
$template.find('.mainText').text("Template "+i);
$main.append($template);
$template.show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div class="template" style="display:none;">
<span class ="mainText"></span>
</div>
</div>
Or, as J. Titus has suggested:
$main = $('#main');
for(var i=0;i<5;i++){
var template = document.getElementById('template').innerHTML;
var $template = $(template)
$template.find('.mainText').text('Template '+i)
$main.append($template);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="template" type="text/template">
<div>
<div class="test">
<span class="mainText">test</span>
</div>
</div>
</script>
<div id="main">
</div>

Related

Change select options based on a select from within multiple iterations

I had a select which, depending on the selected option, affected the options from two other selects (which also affected each other between themselves). So far, this was working fine. Here is the code I had:
HTML
<div id="sel" class="sel-val">
<div class="row">
<div class="col">
<select class="tipo" name="tipo">
<option selected>Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="col">
<select class="num-a" name="num-a">
<option value="0" selected>0</option>
</select>
</div>
<div class="col">
<select class="custom-select num-n" name="num-n">
<option value="0" selected>0</option>
</select>
</div>
</div>
</div>
JS
$('.tipo').on("change", function() {
var val = $(this).val();
$(".num-a").html(options1[val]);
$(".num-n").html(options2[val]);
if (val == 1) {
$('.num-a').on("change", function() {
var vara = $(this).val();
$(".num-n").html(optionsIn[vara]);
});
$('.num-n').on("change", function() {
var varn = $(this).val();
$(".num-a").html(optionsIn[varn]);
});
}
if (val == 2) {
// same with different arrays
}
if (val == 3) {
// same with different arrays
}
if (val == 4) {
// same with different arrays
}
});
var options1 = [
array with options 1
];
var options2 = [
array with options 2
];
etc ...
I had to change it, so that instead of only one time, I will have this same code repeated X number of times (depending on an input set by the user), all of which will have the same three selects inside, which will have the same options. So it now looks something like this:
<div id="sel-1" class="sel-val">
<div class="row">
<div class="col">
<select class="tipo" name="tipo-1">
options...
</select>
</div>
<div class="col">
<select class="num-a" name="num-a-1">
<option value="0" selected>0</option>
</select>
</div>
<div class="col">
<select class="custom-select num-n" name="num-n-1">
<option value="0" selected>0</option>
</select>
</div>
</div>
</div>
...
<div id="sel-X" class="sel-val">
<div class="row">
<div class="col">
<select class="tipo" name="tipo-X">
options...
</select>
</div>
<div class="col">
<select class="num-a" name="num-a-X">
<option value="0" selected>0</option>
</select>
</div>
<div class="col">
<select class="custom-select num-n" name="num-n-X">
<option value="0" selected>0</option>
</select>
</div>
</div>
</div>
The problem is that with the code I have, whenever I set any of the .tipo options, it affects all of the X .num-a and .num-n selects (also changing any of the .num-a affects all of the .num-n and viceversa), when it should only affect the options of the corresponding nth selects.
I had to chang the first on("change") to $(document).on('change') for the selects to be recognized (found it on another user answer), so the first line of the script is now:
$(document).on('change','.tipo-habitacion-sel', function() {
I'm not very good with js, so this may be something obvious, but I tried several things and can't make it work.
As there mutiple selects in your html code so to refer only the required selects you can use .closest() this will get the closest div eg : sel-val and then use .find method to find select-box where you need append new options
Demo Code :
$(document).on('change', '.tipo', function() {
var val = $(this).val();
//get closest div with class sel-val
var selector = $(this).closest(".sel-val")
//then use find to get required select refernce
selector.find(".num-a").html("<option>0</option><option value='1' >1</option>");
selector.find(".num-n").html(" <option>0</option><option value='1' >1</option>");
//other codes.
});
$(document).on('change', '.num-a', function() {
var vara = $(this).val();
var selector = $(this).closest(".sel-val")
// $(".num-n").html(optionsIn[vara]);
selector.find(".num-n").html("<option>0</option><option value='2'>2</option>");
});
$(document).on('change', '.num-n', function() {
var varn = $(this).val();
var selector = $(this).closest(".sel-val")
//$(".num-a").html(optionsIn[varn]);
selector.find(".num-a").html("<option>0</option><option value='3'>3</option>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sel-1" class="sel-val">
<div class="row">
<div class="col">
<select class="tipo" name="tipo-1">
<option value="0">0</option>
<option value="4">4</option>
</select>
</div>
<div class="col">
<select class="num-a" name="num-a-1">
<option value="0" selected>0</option>
</select>
</div>
<div class="col">
<select class="custom-select num-n" name="num-n-1">
<option value="0" selected>0</option>
</select>
</div>
</div>
</div>
<hr>
<div id="sel-X" class="sel-val">
<div class="row">
<div class="col">
<select class="tipo" name="tipo-X">
<option value="0">0</option>
<option value="4">4</option>
</select>
</div>
<div class="col">
<select class="num-a" name="num-a-X">
<option value="0" selected>0</option>
</select>
</div>
<div class="col">
<select class="custom-select num-n" name="num-n-X">
<option value="0" selected>0</option>
</select>
</div>
</div>
</div>

To get the selected index for multiple dropdowns of the same class

I have multiple dropdowns with the same class but different values. On change of a dropdown selected value, I need to know the index. Below is my following code:
$("body").on("change", ".ddlFruit", function () {
var fruitIndex = $(".ddlFruit option:selected").index();
alert(fruitIndex);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Apple</option>
<option value="2">Bannana</option>
<option value="3">Mango</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Water Melon</option>
<option value="2">Kiwi</option>
<option value="3">Peach</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Strawberry</option>
<option value="2">Papaya</option>
<option value="3">Grapes</option>
</select>
</div>
</div>
The issue with this is it always gives the index of the first dropdown even if I change values in second or third dropdown. I tried something like
var fruitIndex = $("this option:selected").index();
but that does not work. How do I figure out the right index in Jquery without having to change anything in the html?
Use the this context as the second argument in the jQuery function.
var fruitIndex = $("option:selected", this).index();
$("body").on("change", ".ddlFruit", function () {
var fruitIndex = $("option:selected", this).index();
alert(fruitIndex);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Apple</option>
<option value="2">Bannana</option>
<option value="3">Mango</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Water Melon</option>
<option value="2">Kiwi</option>
<option value="3">Peach</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Strawberry</option>
<option value="2">Papaya</option>
<option value="3">Grapes</option>
</select>
</div>
</div>
Or use find() method to get element within this context.
var fruitIndex = $(this).find("option:selected").index();
$("body").on("change", ".ddlFruit", function () {
var fruitIndex = $(this).find("option:selected").index();
alert(fruitIndex);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Apple</option>
<option value="2">Bannana</option>
<option value="3">Mango</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Water Melon</option>
<option value="2">Kiwi</option>
<option value="3">Peach</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="col-xs-3">
<select class="form-control ddlFruit">
<option value="1">Strawberry</option>
<option value="2">Papaya</option>
<option value="3">Grapes</option>
</select>
</div>
</div>

Get value from select and clone form number of times

I have a select box , i want user to select value and then after getting value forms are to be added in page according to selected value , like if user selects "1" 1 form is to be added and if user select "10" 10 forms. also if nothing is given or not selected no form to display . It seems to be problem in my js , it does add forms but add other more forms too which i dont expect.
<div class="form-group">
<label>Number of travellers</label>
<select class="form-control" id="travellersNumber">
<option value="0">Select Numbers Of Travellers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div class=bookForm>
<div class=col-xs-12>
<h3 class=bookForm-heading>Submit your details</h3>
</div>
<div class="col-xs-12 col-md-3">
<div class=form-group>
<label>First Name</label>
<input class=form-control name=firstName>
</div>
</div>
</div>
.bookForm{
display:none;
}
function bookFormToggle(){
var traveller = $("#travellersNumber");
var form = $(".bookForm");
var heading = $('.bookForm-heading');
function unhideForm(){
var travellerValue = parseInt(traveller.val());
for(i=0;i<travellerValue;i++){
heading = heading.html('Traveller '+ (i+1) +' Information');
form.clone().insertAfter(form);
}
}
traveller.on("change",unhideForm);
unhideForm();
}
bookFormToggle();
Hope this is what you want.
$(function () {
$("#travellersNumber").on('change', function () {
var traveller = $(this);
var form = $("#original");
var heading = $('.bookForm-heading');
var travellerValue = parseInt(traveller.val());
$("#original").hide();
$("[id*='original_']").not("#original").remove(); //Remove all forms except original form
for (i = 0; i < travellerValue; i++) {
if (i == 0) {
heading = heading.html('Traveller 1 Information');
$("#original").show();
}
else
{
var cloneDiv = form.clone().prop("id", "original_" + i).appendTo("#travellersDetail");
cloneDiv.find(".bookForm-heading").html('Traveller ' + (i + 1) + ' Information');
}
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.bookForm {
display: none;
}
</style>
<div class="form-group">
<label>Number of travellers</label>
<select class="form-control" id="travellersNumber">
<option value="0">Select Numbers Of Travellers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div class="bookForm" id="original">
<div class=col-xs-12>
<h3 class="bookForm-heading">Submit your details</h3>
</div>
<div class="col-xs-12 col-md-3">
<div class=form-group>
<label>First Name</label>
<input class=form-control name=firstName>
</div>
</div>
</div>
<div id="travellersDetail"></div>
The problem is that you are not removing the old forms that you have added.
$(document).ready(function(){
var traveller = $('select[name="trav"]');
traveller.change(function(){
$('.bookForm').not('.bookForm:first').remove();
var travellerValue = traveller.val();
var form = $('.bookForm:first');
for(i=travellerValue;i>1;i--){
var newAdd = form.clone().insertAfter(form);
newAdd.find('.bookForm-heading').html('Traveller'+ (i)+' Information');
}
$('.bookForm').show();
});
});
.bookForm{
background-color:green;
padding:5px;
margin:5px;
}
#travellersNumber{
width:150px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label>Number of travellers</label>
<select class="form-control" id="travellersNumber" name="trav">
<option value="0">Select Numbers Of Travellers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div class="bookForm row">
<div class="col-xs-12">
<h3 class="bookForm-heading">Submit your details</h3>
</div>
<div class="col-xs-12">
<div class="form-group">
<label>First Name</label>
<input class="form-control" name="firstName">
</div>
</div>
</div>
<select id='populate' onchange='populate();'></select>
<div id='myform'></div>
function populate()
{
var forms=$("#populate").val();
if (forms!=0)
{
var formelements='';
for (i=1; i<=forms; i++)
{
var formelements .= "<div class=bookForm>" +i+ "</div>";
}
$("#myform").html(formelements);
}
}

Recursive read div contents and post via AJAX

I created a function that reads the content of some divs and puts them into an array. My divs are organized as such:
<div class="row clearfix" id="moltiplicandum1">
<div class="column third">
<select id="test_set" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="set1">set1</option>
<option value="set2">set2</option>
</select>
</div>
<div class="column third">
<select id="avail_cat" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="cat1">cat1</option>
<option value="cat2">cat2</option>
</select>
</div>
<div class="column third">
<select id="avail_class" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="class1">class1</option>
<option value="class2">class2</option>
</select>
</div>
</div>
<div class="row clearfix" id="moltiplicandum#">...</div>
From moltiplicandum1 to an arbitrary montiplicandum# (all created via js using a button). So, the function that is going to read the contents of all "select" for each "moltiplicandum" returns an error:
TypeError: div is null
on the line var divs = div.getElementsByTagName('select');. Here the function:
var divArray = [];
for(var i = 1; i < 10; i++) {
var div = document.getElementById("moltiplicandum"+i);
var divs = div.getElementsByTagName('select');
for (var j = 0; j < divs.length; j += 1) {
divArray.push($(divs[j]).val());
}
}
If I comment the external for, defining var i = 1, it works (only for "moltiplicandum1").
Could someone help me to figure out the problem? Thank you1
if you are using jquery why don't you simply use the selector? like this:
selectArray = Array.prototype.map.call($(".moltiplicandum select"),(function(el){
return el.value;
});
I'm not sure what any of the code you've shown has to do with either recursion or AJAX, however given your goal of building an array of all the values from the select elements you can simply use jQuery's map() method.
You can also add a common class to the moltiplicandumN elements so that you can genericise the logic. Try this:
$('.moltiplicandum select').change(function() {
var selectArray = $('.moltiplicandum select').map(function() {
return this.value;
}).get();
console.log(selectArray)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row clearfix moltiplicandum" id="moltiplicandum1">
<div class="column third">
<select id="test_set1" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="set1">set1</option>
<option value="set2">set2</option>
</select>
</div>
<div class="column third">
<select id="avail_cat1" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="cat1">cat1</option>
<option value="cat2">cat2</option>
</select>
</div>
<div class="column third">
<select id="avail_class1" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="class1">class1</option>
<option value="class2">class2</option>
</select>
</div>
</div>
<div class="row clearfix moltiplicandum" id="moltiplicandum2">
<div class="column third">
<select id="test_set2" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="set1">set1</option>
<option value="set2">set2</option>
</select>
</div>
<div class="column third">
<select id="avail_cat2" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="cat1">cat1</option>
<option value="cat2">cat2</option>
</select>
</div>
<div class="column third">
<select id="avail_class2" type="text" style="width:100%">
<option selected disabled value="">Select...</option>
<option value="class1">class1</option>
<option value="class2">class2</option>
</select>
</div>
</div>
Also, be careful of duplicating id attributes. I added a numerical value to the id of the repeated select controls in the HTML above.

change select to input in cart

I'm trying to change a select list to a text input (an example is amazon cart) based on a value of 10. What I have works for 1 row but I want to add multiple rows. I need some help changing the jquery to only change 1 row at a time.
$(function() {
$('.dropdown-change').on('change', function() {
var dropdownValue = $(this).val();
if (dropdownValue == 10) {
$('.dropdown-control').hide();
$('.input-control').show();
} else {
$('.dropdown-control').show();
$('.input-control').hide();
}
return false;
});
});
.input-control {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row dropdown-row">
<div class="col-xs-2 col sm-2 col-md-2">
<label for="quantity">Qty</label>
</div>
<div class="col-xs-8 col-sm-8 col-md-8">
<div class="dropdown-control">
<div class="col-xs-12 col-sm-12 col-md-6 no-pad-left">
<select name="quantity" class="form-control dropdown-change">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10+</option>
</select>
</div>
</div>
<div class="input-control">
<div class="col-md-6 no-pad-left">
<input type="text" value="10" size="10" name="quantity" id="quantity" class="form-control" />
</div>
<div class="col-md-6 no-pad-left">
<button class="btn btn-primary btn-xs">update</button>
</div>
</div>
</div>
</div>
I fixed this by changing my HTML around and using $(this).closest() and $(this).next()

Categories

Resources