I'm having a big problem in trying to get the value of these inputs and associates them to the object "book" when you click " Book Now! "
No matter where I declare the object in js , it just does not work.
It was for the object like this:
$scope.book = {
bday_i : new date(day, month, year),
bday_f : book(bday_i),
bfrom : getHours(bday_i),
buntil : getHours(bday_i),
bresource : "Small meeting room ",
bmember : "Lucas Gabriel da Costa",
busercredit : ("4 hours left of", book(bresource)),
bcoment : "Test"
}
And i try to get the values and assign them to variables like this:
$scope.book.bday_i = myForm.day_i.value;
$scope.book.bday_f = myForm.day_f.value;
$scope.book.bfrom = myForm.from.value;
$scope.book.buntil = myForm.until.value;
$scope.book.bresource = myForm.resource.value;
$scope.book.bmember = myForm.member.value;
$scope.book.busercredit = myForm.usercredit.value;
$scope.book.bcoment = myForm.coment.value;
$modalInstance.close(result);
$scope.dayClick = function (date, jsEvent, view, value) {
$scope.newEventDate = date;
var
t =
'<div class="modal-header">' +
'<h5>New booking</h5>' +
'</div>' +
'<form ng-model="myForm" name="myForm" id="myForm">'+
'<div class="modal-body" name="box" >' +
'<p>Time: ' + ' ' + '<pre >' + ' Initial date:' +
'<input id="day_i" class="form-control" type="date" name="day_i" ng-model="day_i" type="text" min = "dia_hj" value="dia_hj" required /> ' +
' Final date:' +
'<input id="day_f" class="form-control" type="date" name="day_f" ng-model="day_f" type="text" min = "day_i" value="dia_hj" required /> ' +
' From:' +
' <input id="from" class="form-control" name="from" ng-model="from" type="time" min = "getHours()" value="" required />' +
' Until' +
' <input id="until" class="form-control" name="until" ng-model="until" type="time" min = "myForm.from.value" value="" required /> </pre></p>' +
'<p> Resource:' +
' <pre><input id="resource" class="form-control" name="resource" ng-model="resource" type="text" placeholder ="Ex: Small Meeting Room" value="" required /></pre></p> ' +
'<p> Member: ' +
' <pre><input id="member" class="form-control " name="member" ng-model="member" type="text" placeholder="Ex: Lucas Gabriel da Costa" value="" required /> </pre></p> ' +
'<p> User credit:' +
' <pre><input id="usercredit" class="form-control" name="usercredit" ng-model="usercredit" type="text" placeholder="Ex: 4 hours included(Small meeting Room)" value="" required /></pre></p>' +
'Note:' +
'<pre><textarea id="coment" ng-model = "coment" name="coment" rows="4" cols="46" placeholder="Insert ur comment"></textarea></pre></form>' +
// validação:
'<div ng-hide= " myForm.day_i.$pristine">' +
'<span ng-show="myForm.day_i.$error.required " class="alert alert-danger"> The INITIAL DATE camp is required. Or a invalid value was inserted <br/><br/> </span></div> ' +
'<div ng-hide= " myForm.day_f.$pristine">' +
'<span ng-show="myForm.day_f.$error.required || (myForm.day_f.value <= myForm.day_i.value)" class="alert alert-danger"> The FINAL DATE camp is required. Or a invalid value was inserted <br/><br/> </span></div> ' +
'<div ng-hide =" myForm.from.$pristine">' +
'<span ng-show="myForm.from.$error.required " class="alert alert-danger"> The FROM camp is required. Or a invalid value was inserted <br/><br/> </span></div> ' +
'<div ng-hide =" myForm.until.$pristine">' +
'<span ng-show="myForm.until.$error.required || myForm.until.value < myForm.from.value" class="alert alert-danger"> The UNTIL camp is required. Or a invalid value was inserted <br/><br/> </span></div> ' +
'<div ng-hide=" myForm.resource.$pristine ">' +
'<span ng-show="myForm.resource.$error.required " class="alert alert-danger"> The RESOURCE camp is required. Or a invalid value was inserted <br/><br/> </span></div> ' +
'<div ng-hide= " myForm.member.$pristine">' +
'<span ng-show="myForm.member.$error.required " class="alert alert-danger"> The MEMBER camp is required. Or a invalid value was inserted <br/><br/> </span></div> ' +
'<div ng-hide=" myForm.usercredit.$pristine">' +
'<span ng-show="myForm.usercredit.$error.required " class="alert alert-danger"> The CREDIT camp is required. Or a invalid value was inserted <br/><br/> </span> </div> ' +
'</div>' +
'<div class="modal-footer">' +
'<button ng-click="close(result)" id="b1" ng-model="b1" name="b1" class="btn btn-danger " >Close</button>' + //botão de fechar
'<button ng-click="close2(okay) " id="b2" ng-model="b2" name="b2" class="btn btn-success" ng-disabled="myForm.usercredit.$pristine || myForm.day.$pristine || myForm.from.$pristine || myForm.until.$pristine || myForm.resource.$pristine || myForm.member.$pristine "> Book Now! </button>' +
'</div>';
var
modalInstance = $modal.open({
template: t,
controller: 'TestDialogController',
backdrop: "true",
resolve: {
event: function () {
return $scope.newEventDate;
},
stage: function () {
return $scope.stage;
}
}
});
modalInstance.okay.then(
function () {
alert('');
;
});
modalInstance.result.then(
function (result) {
//console.log('called $modalInstance.close()');
alert(result);
$scope.addEvent();
},
function (result) {
//console.log('called $modalInstance.dismiss()');
$scope.addEvent();
}
);
};
app.controller('TestDialogController', function ($scope, $modalInstance) {
$scope.close = function (result) {
alert(result);
$modalInstance.close(result);
}});
<div class="container pad-35">
<div class="row">
<!-- Space Header -->
<venue-header title="{{ venue_title }}" nav="header"></venue-header>
<!-- Dashboard -->
<div class="col-md-12 pull-left" ng-cloak>
<section id="directives-calendar" ng-controller="CalendarCtrl">
<div class="well">
<div class="row-fluid">
<div class="span8">
<tabset>
<tab select="renderCalender('myCalendar1');">
<tab-heading>
<i class="glyphicon glyphicon-bell"></i> Calendar One
</tab-heading>
<div class="btn-toolbar">
<center><p class="pull-right lead">Calendar One View Options</p></center>
<div class="btn-group">
<button class="btn btn-success" ng-click="changeView('agendaDay', 'myCalendar1')">AgendaDay</button>
<button class="btn btn-success" ng-click="changeView('agendaWeek', 'myCalendar1')">AgendaWeek</button>
<button class="btn btn-success" ng-click="changeView('month', 'myCalendar1')">Month</button>
<!--select para definir o resource a ser usado no controler js-->
</div>
<p class="textalign1">
<center>
<select id="select-lucas" class="dropdown-toggle btn btn-success " ng-model="model.id" convert-to-number>
<option value="" selected="selected" onclick="">small meeting room</option>
<option value="1" selected="selected" onclick="">medium meeting room</option>
<option value="2" selected="selected" onclick="">Big meeting room</option>
<option value="3" selected="selected" onclick="">Giant meeting room</option>
</select>
</center>
</p>
</div>
<div class="calendar ng-model="eventSources" calendar="myCalendar1" ui-calendar="uiConfig.calendar"></div>
</tab>
</tabset>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
The result is this pop up:
Your form is defined in the modal which have his own controller and his own scope.
So when you do
ng-model="until"
In your input, this is binding a variable "until" ont eh scope modal's controller.
so if you want to build an object you ave to do like this in the modal controller :
var book = {};
book.buntil = $scope.until;
Same for every fields.
After if you want to display that books to the main view you could use an event that is emitted and listen on the $rootscope.
I don't know which modal library you use so i can't say if the scope generated if a child of the other.
Related
When I append div one by one, it's working properly. but when I delete the first one or any from the previous one, it's not deleting properly. And if once again I want to append another div div-number is not maintaining sequence. Actually, I want to build a system where users can add products and also can delete the product during invoice generation. so please help me with how these kinds of stuff can be maintained. Also, I need to calculate the subtotal amount of individual products with individual div. Here is my code:
<script type="text/javascript">
let divCount = 0;
$(function() {
$('#btnAddtoList').on('click', function(){
divCount++;
const div_title = divCount;
var newDiv = $(
`<div class=item-wrapper-${div_title}>` +
'<div class="container rounded bg-white mt-3 mb-3">' +
'<div class="row">' +
'<div class="col-md-12">' +
'<div class="row mt-3">' +
'<span><strong>পণ্যের বিবরণ #</strong></span>'+ div_title +
'</div>' +
'<div class="row mt-1 text-center">' +
'<select class="product_option form-control" id="product">' +
'<option disabled selected> -- পণ্য পছন্দ করুন (পণ্যের নাম | বিক্রয় মূল্য |
অ্যাভেলেবল আছে) --
</option>' +
'</select>' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">পণ্যের নাম</label>
<input type="text" class="form-control" id="productName">' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">বিক্রয় মূল্য</label>
<input type="number" class="form-control" id="sellPrice">' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">পণ্য মজুদ আছে </label>
<input type="text" class="form-control" id="amount" ">' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">পরিমাণ</label>
<input type="number" class="form-control quantity_pro" id="quantity" ">' +
'</div>' +
`<div class="mt-3 d-flex flex-column align-items-center text-center">
<button class="btn btn-danger deleteItem" id=del-${div_title}
type="button">মুছুন
</button>
</div>` +
'</div>' +
'</div>' +
'</div>' +
'</div>');
$('.productDiv').append(newDiv);
console.log(div_title);
$(".item-wrapper-" + div_title).find(".product_option").select2({
theme: "classic"
});
firebase.auth().onAuthStateChanged(function(user) {
console.log(user);
if (user) {
var user_id = user.uid;
firebase.database().ref('Products/').child(user_id).once('value')
.then(function(snapshot){
snapshot.forEach(function(childSnapshot) {
var product_name = childSnapshot.child("product_name").val();
var selling_price = childSnapshot.child("selling_price").val();
var amount = childSnapshot.child("product_quantity").val();
{#console.log(amount)#}
var total = product_name + " | " + selling_price + " | " + amount;
console.log(total);
$(".item-wrapper-" + div_title).find(".product_option").append('<option>'
+ total + '</option');
$(document).on("change", ".product_option", function () {
const valArr = $(`.item-wrapper-${div_title} .product_option
option:selected`).text().split(" | ");
$(`div.item-wrapper-${div_title} #productName`).val(valArr[0]);
$(`div.item-wrapper-${div_title} #sellPrice`).val(valArr[1]);
$(`div.item-wrapper-${div_title} #amount`).val(valArr[2]);
});
});
})
}
else{
window.location.href="{% url 'login' %}";
}
});
});
$("#subTotal").on('click', function (e) {
var subTotalAmount = 0;
for (var i = 1; i<=divCount; i++){
var getProductName = $(`div.item-wrapper-${i} #productName`).val();
var getSellingPrice = $(`div.item-wrapper-${i} #sellPrice`).val();
var getAmount = $(`div.item-wrapper-${i} #amount`).val();
var getQuantity = $(`div.item-wrapper-${i} #quantity`).val();
subTotalAmount += getSellingPrice*getQuantity;
}
var SellingPriceFloat = parseFloat(getSellingPrice);
var amountFloat = parseFloat(getAmount);
console.log(amountFloat)
var quantityFloat = parseFloat(getQuantity);
console.log(quantityFloat);
console.log(subTotalAmount)
if (quantityFloat>amountFloat){
alert("পর্যাপ্ত পরিমান পণ্য নেই ।");
}
else {
// executes only once
var subDiv = $(
'<div class="item-wrapper">' +
'<div class="container rounded bg-white mt-3 mb-3">' +
'<div class="row">' +
'<div class="col-md-12">' +
'<div class="row mt-3">' +
'<span class="col-md-12">সাব টোটালঃ</strong></span>'
+subTotalAmount +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">ডিসকাউন্ট(%)
</label><input type="text" class="form-control" id="productName">' +
'</div>' +
'<div class="row mt-3">' +
'<label class="labels" style="font-size: 16px">ভ্যাট(%)
</label><input type="text" class="form-control" id="sellPrice">' +
'</div>' +
'<div class="row mt-3">' +
'<span class="col-md-12"><strong>মোটঃ</strong></span>'+
'</div>' +
'<div class="mt-3 d-flex flex-column align-items-center text- center">
<button class="btn btn-info" type="button">মোট</button></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>');
$('.subTotalDiv').html(subDiv);
}
});
$(document).on("click", ".deleteItem", function() {
$(this).closest(`.item-wrapper-${divCount}`).remove();
divCount-=1;
});
});
</script>
here is my html:
<div class="productDiv"></div>
<div class="mt-3 text-center">
<button class="btn profile-button" style="color: white" type="button"
id="btnAddtoList">পণ্য যোগ করুন</button>
</div>
<div class="mt-3 text-center">
<button class="btn profile-button" style="color: white" type="button"
id="subTotal" >সাব টোটাল</button>
</div>
<div class="subTotalDiv"></div>
You can see that two div with the same div number:
Thanks in advance.
You have many important issues in that code.
You are creating some dynamic elements having always the same id.
An id must be unique. NEVER use an id in a loop or in an event handler that appends elements.Use a class instead.
When you have more than one or two lines of HTML concatenated in a string for some appending... Better use the .clone() method on a "template" hidden in the HTML.
That makes your code more readable and maintainable, since the "template" to clone will appear as regular HTML in your code editor, so you can see typos right away.
And the JS is then more concise.
The main advantage of using jQuery is its ease to "traverse" the DOM using easy and short methods.
From a user action (like from a event triggered on a <select> element)... Use the wide set of method like .parent(), .closest(), .find(), .siblings(), etc... to target the elements you want.
Reminder for your future coding: Every time you have to add a number to a class to make it unique... Take it as a symptom of a bad coding. While an id must be unique to target ONE element, a class must be "generic" to target a set of similar elements.
I COMPLETELY removed your "concept" of having the divCount an div_title variable in the below snippet.
Your issue was NOT about how to correctly use it... But how to NOT use it. ;)
Function nesting.
You used event delegation: $(document).on("change", ".product_option", function () {...}
Nice! But that is inside the Firebase callback.
And the Firebase request is inside the btnAddtoList click handler.
So every times the user click on the পণ্য যোগ করুন (Add products) button, there is a request made to the database (most probably with the same result). And an additional delegated handler for all .product_option select in the page is setted.
It does not looks too good right?
And that was due to your (failed) attempt to use some "unique" item-wrapper-* classes...
So below is your code changed a lot. I did not dive into your Firebase request because I really don't know the structure of the response. I "assumed" a response with the snapshot array of objects. You may have something quite different.
Have a close look at the code and all the comments.
console.clear();
$(function () {
// Add a cloned div
$("#btnAddtoList").on("click", function () {
// Clone the template and toggle some classes
let newDiv = $(".item-wrapper_template")
.clone()
.toggleClass("item-wrapper_template item-wrapper");
// Append
newDiv.find(".number").text($(".item-wrapper").length + 1);
$(".productDiv").append(newDiv);
// Instantiate Select2
newDiv.find(".product_option").select2({
theme: "classic"
});
});
// Delete a cloned div
$(document).on("click", ".deleteItem", function () {
// Remove the whole wrapper div that holds the .deleteItem button
$(this).closest(".item-wrapper").remove();
// Update the numbers of the other items
$(".item-wrapper").each(function (num) {
$(this)
.find(".number")
.text(num + 1);
});
});
// Calculate the sub total
$("#subTotal").on("click", function (e) {
// At each click event, start the calculation at zero
let subTotalAmount = 0;
// How many items now?
let itemCount = $(".item-wrapper").length;
// A flag to know if we break the loop
let loopBreak = false;
// Looping all the items
for (let i = 0; i < itemCount; i++) {
let getSellingPrice = parseFloat(
$(".item-wrapper").eq(i).find(".sellPrice").val()
);
let getAmount = parseFloat(
$(".item-wrapper").eq(i).find(".amount").val()
);
let getQuantity =
parseFloat($(".item-wrapper").eq(i).find(".quantity").val()) || 0;
// A condition check which may break the loop
if (getQuantity > getAmount) {
alert("পর্যাপ্ত পরিমান পণ্য নেই ।"); // There are not enough products.
loopBreak = true;
break;
} else {
subTotalAmount += getSellingPrice * getQuantity;
console.log("subTotalAmount", subTotalAmount);
}
} // END for loop
// If the loop was not broken
if (!loopBreak) {
$(".subTotalDiv").find(".subTotalAmount").text(subTotalAmount);
$(".subTotalDiv").show();
}
});
// Option change handler for ALL select element present on the page
$(document).on("change", ".product_option", function () {
const valArr = $(this).find("option:selected").text().split(" | ");
$(this).closest(".item-wrapper").find(".productName").val(valArr[0]);
$(this).closest(".item-wrapper").find(".sellPrice").val(valArr[1]);
$(this).closest(".item-wrapper").find(".amount").val(valArr[2]);
});
// =====
// Simulating the firebase database request
// Let assume some data to make this example working
let snapshot = [
{
product_name: "First Product",
selling_price: 10.57,
product_quantity: 42
},
{
product_name: "Second Product",
selling_price: 28.72,
product_quantity: 17
},
{
product_name: "Third Product",
selling_price: 11.48,
product_quantity: 8
}
];
/*
firebase.auth().onAuthStateChanged(function(user) {
console.log(user);
if (user) {
var user_id = user.uid;
firebase.database().ref('Products/').child(user_id).once('value')
.then(function(snapshot){
snapshot.forEach(function(childSnapshot) {
var product_name = childSnapshot.child("product_name").val();
var selling_price = childSnapshot.child("selling_price").val();
var amount = childSnapshot.child("product_quantity").val();
{#console.log(amount)#}
var total = product_name + " | " + selling_price + " | " + amount;
console.log(total);
$(".item-wrapper-" + div_title).find(".product_option").append('<option>'
+ total + '</option');
});
*/
// Here, I am simulating the option appending from the simulated snapshot array above
// Notice I append it to the template!
snapshot.forEach(function (item, index) {
// Format the text of the option
let optionText =
item.product_name +
" | " +
item.selling_price +
" | " +
item.product_quantity;
// Create the option and append
let option = $("<option>").text(optionText);
$(".item-wrapper_template").find(".product_option").append(option);
});
/*
})
}
else{
window.location.href="{% url 'login' %}";
}
});
*/
});
.item-wrapper_template{
display: none;
}
.subTotalDiv{
display: none;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<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.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="productDiv"></div>
<!-- That is a TEMPLATE -->
<div class=item-wrapper_template>
<div class="container rounded bg-white mt-3 mb-3">
<div class="row">
<div class="col-md-12">
<div class="row mt-3">
<span><strong>পণ্যের বিবরণ (Product Description) #</strong></span><span class="number">0</span>
</div>
<div class="row mt-1 text-center">
<select class="product_option form-control">
<option disabled selected> -- পণ্য পছন্দ করুন (পণ্যের নাম | বিক্রয় মূল্য | অ্যাভেলেবল আছে) -- </option>
<option disabled> -- Choose Product (Product Name | Sale Price | Available) -- </option>
</select>
</div>
<div class="row mt-3">
<label class="labels" style="font-size: 16px">পণ্যের নাম (Product name)</label> <input type="text" class="form-control productName">
</div>
<div class="row mt-3">
<label class="labels" style="font-size: 16px">বিক্রয় মূল্য (Sale price)</label> <input type="number" class="form-control sellPrice">
</div>
<div class="row mt-3">
<label class="labels" style="font-size: 16px">পণ্য মজুদ আছে (There are stockpiles of products)</label> <input type="text" class="form-control amount">
</div>
<div class="row mt-3">
<label class="labels" style="font-size: 16px">পরিমাণ (Amount)</label> <input type="number" class="form-control quantity_pro quantity">
</div>
<div class="mt-3 d-flex flex-column align-items-center text-center"> <button class="btn btn-danger deleteItem" type="button">মুছুন (Delete)</button> </div>
</div>
</div>
</div>
</div>
<!-- That is your "normal" HTML -->
<div class="mt-3 text-center">
<button id="btnAddtoList" class="btn profile-button" type="button">পণ্য যোগ করুন (Add products)</button>
</div>
<div class="mt-3 text-center">
<button id="subTotal" class="btn profile-button" type="button">সাব টোটাল (Sub Total)</button>
</div>
<!-- That is hidden by CSS but shown by JS -->
<div class="subTotalDiv">
<div class="container rounded bg-white mt-3 mb-3">
<div class="row">
<div class="col-md-12">
<div class="row mt-3">
<span class="col-md-12">সাব টোটালঃ (Sub Total:)</strong></span><span class="subTotalAmount">0</span>
</div>
<div class="row mt-3">
<label class="labels" style="font-size: 16px">ডিসকাউন্ট(%) (Discount (%))</label><input type="text" class="form-control">
</div>
<div class="row mt-3">
<label class="labels" style="font-size: 16px">ভ্যাট(%) (VAT (%))</label><input type="text" class="form-control sellPrice">
</div>
<div class="row mt-3">
<span class="col-md-12"><strong>মোটঃ (Total:)</strong></span>
</div>
<div class="mt-3 d-flex flex-column align-items-center text- center"> <button class="btn btn-info" type="button">মোট (Total)</button></div>
</div>
</div>
</div>
</div>
CodePen
I want to make dynamically text remaining, the code for row 1 is work. But not for the next row.
var str = getStringForm(typeNarrative, nomor); // my str is equal of my text area html code
$('#Scores').append(str);
(function($) {
'use strict';
$.fn.remainingCharsCounter = function() {
return this.on('focus keyup', function() {
var remainingChars = $(this).attr('maxlength') - $(this).val().length;
$(this).next('.remainingChars').text(remainingChars).focus();;
});
};
})(jQuery);
jQuery(document).ready(function() {
'use strict';
$('textarea.char-textarea').remainingCharsCounter().css('border', '1px solid #0000004f');
});
**getStringForm**
my string from here
function getStringForm(typeNarrative, nomor) {
var str;
if (typeNarrative == "subtest" || typeNarrative == "SUBTEST") {
str = `<div class="row NarrativeField" id="label` + nomor + `" style="text-align:center;margin-top:15px;">
<div class="col-xs-2">
<textarea id="NarrativeLong`+ nomor + `" class="k-textbox char-textarea" maxlength="2000" name="NarrativeLong` + nomor + `" data-bind="value:Narrative[` + nomor + `].NarrativeLong` + nomor + `" style="width:70%"></textarea>
Remaining chars: <span class="remainingChars" style="font-size:8pt; font-weight:bold;"></span>
</div>
<i class="fas fa-trash-alt"></i>
</div>`;
} else if (typeNarrative == "IQ") {
str = `<div class="row NarrativeField-IQ" id="label` + nomor + `" style="text-align:center;margin-top:15px;">
<div class="col-xs-2">
<input type="number" class="k-textbox char-textarea" maxlength="2000" id="Score`+ nomor + `" name="Score` + nomor + `" value="` + nomor + `" style="width:40%" readonly="readonly" />
Remaining chars: <span class="remainingChars" style="font-size:8pt; font-weight:bold;"></span>
</div>
<div class="col-xs-8">
<textarea id="NarrativeIQ`+ nomor + `" class="k-textbox char-textarea" maxlength="2000" name="NarrativeIQ` + nomor + `" style="width:70%"></textarea>
Remaining chars: <span class="remainingChars" style="font-size:8pt; font-weight:bold;"></span>
</div>
<i class="fas fa-trash-alt"></i>
</div>`;
} else {
str = "";
}
return str;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="Score entered" id="label1">
<textarea id="NarrativeLong1" class="char-textarea" name="NarrativeLong1" style="width:70%" maxlength="100"></textarea> Remaining chars: <span class="remainingChars" style="font-size:8pt; font-weight:bold;"></span>
</div>
i think keyup can't detect my new row field. Please help if there are any solution, thank you !
I am new to Ajax and Jquery.
1)I am trying to add a new user using post method via a form which is in HTML Modal. On clicking Submit button the Modal isn't closing on its own and I have to hit refresh for seeing whether user got added or not. What changes should I do?
2)After checking whether the email and passwords match for a particular user during login how can I display the user details on successful login?
Here is my JS code:
$(document).ready(function(){
$("#retrieve").click(function(){
$('#retrieve').css("display","none");
// $('#uploadimageform').css("display","none");
$('#tabledata').css("display","block");
$('#signupbtn').css("display","block");
$('#loginbtn').css("display","none");
});
});
$(document).ready(function(){
$("#backbutton").click(function(){
$('#retrieve').css("display","block");
// $('#uploadimageform').css("display","block");
$('#tabledata').css("display","none");
$('#signupbtn').css("display","block");
$('#loginbtn').css("display","block");
});
});
// $(document).ready(function(){
// $("#addbutton").click(function(){
// $('#myModal').css("display","none");
// });
// });
$(function () {
var $orders = $('#orders');
var $fname = $('#first');
var $lname = $('#last');
var $contact = $('#contact');
var $addr1 = $('#addr1');
var $addr2 = $('#addr2');
var $strt = $('#strt');
var $strt1 = $('#strt1');
var $city = $('#city');
var $statee = $('#statee');
var $cntry = $('#cntry');
var $email = $('#email');
var $paswrd = $('#paswrd');
var $gndr = $('#gndr');
// Getting the user from backend. Method is "GET".
$.ajax({
type:'GET',
url:'http://13.229.164.32/users.json',
success:function(orders){
orders = orders.sort(function(a, b){
return a.id-b.id
})
$.each(orders,function(id,order){
$orders.append('<tr><td>'+ order.id +
'</td><td>' + '<span class="noedit firstname">' + order.firstname + '</span><input value=' + order.firstname + ' name="firstname" class="edit firstname_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit lastname">' + order.lastname+ '</span><input value=' + order.lastname + ' name="lastname" class="edit lastname_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit contact_number">' + order.contact_number + '</span><input value=' + order.contact_number + ' name="contact_number" class="edit contact_number_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit address1">' + order.address1 + '</span><input value=' + order.address1 + ' name="address1" class="edit address1_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit address2">' + order.address2 + '</span><input value=' + order.address2 + ' name="address2" class="edit address2_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit street">' + order.street + '</span><input value=' + order.street + ' name="street" class="edit street_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit street1">' + order.street1 + '</span><input value=' + order.street1 + ' name="street1" class="edit street1_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit city">' + order.city + '</span><input value=' + order.city + ' name="city" class="edit city_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit state">' + order.state + '</span><input value=' + order.state + ' name="state" class="edit state_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit country">' + order.country + '</span><input value=' + order.country + ' name="country" class="edit country_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit email">' + order.email + '</span><input type="email" value=' + order.email + ' name="email" class="edit email_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit password">' + order.password + '</span><input type="password" value=' + order.password + ' name="password" class="edit password_'+order.id+'"/>' +
'</td><td>' + '<span class="noedit gender">' + order.gender + '</span><input value=' + order.gender + ' name="gender" class="edit gender_'+order.id+'"/>' +
'</td><td>' + order.created_at +
'</td><td>' + order.updated_at +
'</td>' +
'<td><button class="remove" data-id=' + order.id + '>X</button></td>' +
'<td><button class="editOrder noedit">Edit</button></td>' +
'<td><button class="saveEdit edit" data-id=' + order.id + '>Save</button></td>' +
'<td><button class="cancelEdit edit">Cncl</button>' +
'</td><td>' + '<input type="file"/ name="user_photo" class="edit user_photo">' +
'<img src="http://13.229.164.32/users/user_photo?id='+order.id+'" class="noedit user_photo_' +
order.id + '" height="80" width="80" >' +
'</td></tr>');
});
},
error:function(){
alert('error in testing');
}
});
// Creating the user and method is "POST"
$('#addbutton').on('click',function(){
var myForm = document.getElementById("uploadimageform");
var data = new FormData(myForm);
$.ajax({
type: "POST",
data: data,
processData:false,
contentType:false,
dataType:"json",
url: 'http://13.229.164.32/users.json',
success: function(nData){
alert('user added');
}.bind(this),
error: function() {
alert('There is a problem with server in saving records');
}
});
});
$orders.delegate('.remove','click',function(){
var $tr = $(this).closest('tr');
var self = this;
var checkstr = confirm('are you sure you want to delete this?');
if(checkstr == true){
$.ajax({
type:'GET',
url: 'http://13.229.164.32/users/user_delete.json?id=' + $(this).attr('data-id') ,
success: function(){
//add delete pop up
$tr.fadeOut(300, function(){
$(this).remove();
});
}
});
}else
{
return false;
}
});
$orders.delegate('.editOrder','click',function(){
var $tr = $(this).closest('tr');
$tr.addClass('edit');
})
$orders.delegate('.cancelEdit','click',function(){
var $tr = $(this).closest('tr').removeClass('edit');
})
$orders.delegate('.saveEdit', 'click', function(){
var $tr = $(this).closest('tr');
var self = this;
var user_id = $(this).attr('data-id');
var formData = new FormData();
var totalFiles = document.getElementById("user_photo").files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("user_photo").files[i];
formData.append("user_photo", file);
}
alert(user_id);
console.log(formData);
formData.append("user[firstname]", $(".firstname_"+user_id).val());
formData.append("user[lastname]", $(".lastname_"+user_id).val());
formData.append("user[gender]", $(".gender_"+user_id).val());
formData.append("user[address1]", $(".address1_"+user_id).val());
formData.append("user[address2]", $(".address2_"+user_id).val());
formData.append("user[street]", $(".street_"+user_id).val());
formData.append("user[street1]", $(".street1_"+user_id).val());
formData.append("user[contact_number]", $(".contact_number_"+user_id).val());
formData.append("user[email]", $(".email_"+user_id).val());
formData.append("user[password]", $(".password_"+user_id).val());
formData.append("user[city]", $(".city_"+user_id).val());
formData.append("user[state]", $(".state_"+user_id).val());
formData.append("user[country]", $(".country_"+user_id).val());
console.log(formData);
$.ajax({
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// },
type: 'POST',
url: 'http://13.229.164.32/users/user_update.json?id=' + $(this).attr('data-id') ,
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(nData){
$tr.find('span.firstname').html(formData.firstname);
$tr.find('span.lastname').html(formData.lastname);
$tr.find('span.gender').html(formData.gender);
$tr.find('span.address1').html(formData.address1);
$tr.find('span.address2').html(formData.address2);
$tr.find('span.street').html(formData.street);
$tr.find('span.street1').html(formData.street1);
$tr.find('span.contact_number').html(formData.contact_number);
$tr.find('span.email').html(formData.email);
$tr.find('span.password').html(formData.password);
$tr.find('span.city').html(formData.city);
$tr.find('span.state').html(formData.state);
$tr.find('span.country').html(formData.country);
$tr.find('span.user_photo').html(formData.user_photo);
// addUser1(newUser);
// console.log(newUser);
$tr.removeClass('edit');
},
error:function(){
alert('error saving user');
}
});
});
$('#checkbutton').on('click',function(){
var self = this;
var email = $('#emailer').val();
var txtpaswrd = $('#paswrder').val();
$.ajax({
type: "GET",
// data: data,
processData:false,
contentType:false,
dataType:"json",
url: 'http://13.229.164.32/users/user_check.json?email=' + email,
success: function(nData){
alert(nData.password);
alert(nData.email);
if(email == nData.email && txtpaswrd == nData.password ){
alert('user details matched ');
}else{
alert('Password Error');
}
}
});
});
});
// });
// });
Here is my CSS code:
.container{
margin:50px;
}
table,tr,th,td{
border: 1px solid grey;
padding: 5px;
text-align: center;
font-size: 10px;
}
tr .edit{
display: none;
}
tr.edit .edit{
display: initial;
}
tr.edit .noedit{
display: none;
}
.btn{
padding-bottom: 10px;
margin-top: 10px;
margin-left: 10px;
border: 1px solid black;
}
#loginhere{
margin-bottom: 20px;
}
p.sign{
margin-left: 50%;
}
select, input{
width:50%;
box-sizing:border-box;
}
input#user_photo{
width:50%;
box-sizing:border-box;
}
#signupbtn{
display: none;
}
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery.ajax()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="api2.css">
</head>
<body>
<!-- For making a modal for pop up displaying the form for adding users.-->
<div class="container">
<!-- For Signup button-->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" id="signupbtn" >Sign Up</button>
<!-- For Login button-->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModall" id="loginbtn" >Login</button><br>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sign Up</h4>
</div>
<div class="modal-body">
<!-- Form for adding user details.-->
<form id="uploadimageform" method="post" enctype="multipart/form-data">
<input type="text" placeholder="first name" id="first" maxlength="15" name="user[firstname]" /><br />
<input type="text" placeholder="last name" id="last" maxlength="15" name="user[lastname]" /><br />
<input type="number" maxlength="10" placeholder="contact no." id="contact" name="user[contact_number]" /><br />
<input type="address" placeholder="address1" id="addr1" name="user[address1]"/><br />
<input type="address" placeholder="address2" id="addr2" name="user[address2]"/><br />
<input type="address" placeholder="street" id="strt" name="user[street]"/><br />
<input type="address" placeholder="street1" id="strt1" name="user[street1]"/><br />
<input type="address" placeholder="city" id="city" name="user[city]"/><br />
<input type="address" placeholder="state" id="statee" name="user[state]"/><br />
<input type="address" placeholder="country" id="cntry" name="user[country]" /><br />
<input type="email" placeholder="email" id="email" name="user[email]" /><br />
<input type="password" placeholder="password" id="paswrd" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" name="user[password]" /><br />
<!-- select for gender -->
<!-- <input type="text" placeholder="gender" id="gndr" name="user[gender]" required/><br>-->
<!-- <label id="gndr" name="user[gender]" required>Gender
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Others">Other</option>
</label>
<label id="gndr" name="user[gender]" required>
<input type="radio" name="gender" value="Male" checked> Male<br>
<input type="radio" name="gender" value="Female"> Female<br>
<input type="radio" name="gender" value="Other"> Other
</label>
-
<input type="file" id="image" placeholder="Upload Image"/><br>-->
<select name="user[gender]" id="gndr">
<option>Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br />
<input type="file" name="user_photo" id="user_photo" /><br>
<div class="btn btn-primary" type="submit" id="addbutton" onclick="">Submit </div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<!--add the form into a modal-->
<div class="modal fade" id="myModall" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<form id="uploadimageformm">
<input type="email" placeholder="email" id="emailer" name="user[email]" />
<input type="password" placeholder="password" id="paswrder" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" name="user[password]" />
<div class="btn btn-primary" type="submit" id="checkbutton" onclick="">Login </div>
</form>
<div id="ack"></div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div style="display:none;" id="tabledata">
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact No.</th>
<th>Address1</th>
<th>Address2</th>
<th>Street</th>
<th>Street1</th>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Email</th>
<th>Passowrd</th>
<th>Gender</th>
<th>Created At</th>
<th>Updated At</th>
<th>Remove Row</th>
<th>Edit</th>
<th>Save</th>
<th>Cancel</th>
<th>User Pic</th>
</tr>
</thead>
<tbody id="orders"></tbody>
</table>
</div>
<button class="btn btn-primary" id="retrieve" onclick="">Retrieve List</button>
<button class="btn btn-primary" id="backbutton" onclick="">Back</button>
</div>
<script type="text/javascript" src="ajaxfetching.js"></script>
</body>
</html>
1/ Use on of the jQuery ajax callback to handle your modal close once your ajax call is done.
And then you need to refresh your page content to show the user created. I think the part of your code displaying user is the part with the Ajax call to "url:'http://13.229.164.32/users.json'". You need to call this again after you closed the modal, to rebuild your Page Content with the new content.
$('#addbutton').on('click',function(){
var myForm = document.getElementById("uploadimageform");
var data = new FormData(myForm);
$.ajax({...}).complete(... // handle your modal close + content reload here)
See jQuery Ajax documentation to use the proper callback.
2/ If your Authentication endpoints send user informations on successful login you could directly use them. If not, you will have to create an endpoint to get a specific user. Or alternatively, you could find the user in your "users.json" if you don't have hand on the API.
To reach an optimal result there are a lot of other optimizations to perform, but this should do the job in the first time. You are using $(document).ready(...) twice, then $(function(){...}) which is also similar.
Like stated in the comment you will need to have a method to catch the submit handler, like prevent default. If you want to build your own button component that will fire the ajax method you may also do that.
Since your using jQuery, you may do the following;
$("#formId").submit(function (event) {
e.preventDefault();
// Run client validation,
$.ajax({...options})
.done(function(data){
// do something with the data, like closing the modal
})
.fail(function(jqXHR, textStatus){
// should the method fail, present error in the modal?
});
}
What you do in the button handler is up to you.
Jquery Ajax Documentation
You may also set up your own button, and button click event, but since your using a form, when a user presses the enter key they will submit the form, and you must prevent that event from happening, should you go that route.
i would like to append a new html code, buy clicking a button. however in the append there are a looping to show the html code.
<script>
var day_left = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
$(".add_schedule").click(function () {
if ($('.day-part').is(':empty')){
alert("You have limit schedule time!")
}else{
var stack = $(this).parent().find('#stack').val();
alert("form-schedule-"+stack);
$(this).before('<div class="form-schedule" id="form-schedule-'+stack+'">' +
'<div class="col-md-4">' +
'<label>Start Time</label><input type="time" placeholder="ex : 00:00" name="time['+stack+'][open_time]" class="open_time form-control" id="open_time'+stack+'">' +
'</div>' +
'<div class="col-md-4">' +
'<label>End Time</label><input type="time" placeholder="ex : 21:00" name="time['+stack+'][close_time]" class="close_time form-control" id="close_time"></div>' +
'<div class="col-md-4">' +
'<label>Pilih Hari</label> ' +
'<div class="dropdown dropdown-payment">' +
'<button class="btn btn-primary btn-sm dropdown-toggle" type="button" data-toggle="dropdown">Select Date <span class="caret"></span></button> ' +
'<div class="dropdown-menu"><div class="everyday-part">' +
'<li> <label> ' +
'<input type="checkbox" id="everyday" class="everyday_check_box form form-control" name="time['+stack+'][everyday]" value="7"> Everyday </label>' +
'</li>' +
'</div>' +
'<div class="day-part">'+
// The Problem is Started From Here
$.each(day_left,function (i,val) {
$('<li><label><input type="checkbox" checked="checked" id="date_check_box" class="form form-control" name="time[' + stack + '][date][]" value="' + i + '">'+val+'</label> </li>');
})+'</div> </div> </div> </div></div><div class="clearfix"></div><br> ');
// End Of the Problem
stack = parseInt(stack)+1;
$(this).parent().find('#stack').val(stack);
}
});
</script>
actually i could append the html. But there is a bug in my $.each(day_left,function(i,val)){});
its only return the value of day_left which they are like sunday,monday,.... The code doesn't show the html code
My expected is it would be returned like this
but my code is only return :
Please make a function like this
function makeString(day_left,stack){
var str = '';
for(var i = 0; i <= day_left.length ; i++ ){
str += '<li><label><input type="checkbox" checked="checked" id="date_check_box" class="form form-control" name="time[' + stack + '][date][]" value="' + i + '">'+day_left[i]+'</label> </li>';
}
return str;
}
and change as following
$(this).before('<div class="form-schedule" id="form-schedule-'+stack+'">' +
'<div class="col-md-4">' +
'<label>Start Time</label><input type="time" placeholder="ex : 00:00" name="time['+stack+'][open_time]" class="open_time form-control" id="open_time'+stack+'">' +
'</div>' +
'<div class="col-md-4">' +
'<label>End Time</label><input type="time" placeholder="ex : 21:00" name="time['+stack+'][close_time]" class="close_time form-control" id="close_time"></div>' +
'<div class="col-md-4">' +
'<label>Pilih Hari</label> ' +
'<div class="dropdown dropdown-payment">' +
'<button class="btn btn-primary btn-sm dropdown-toggle" type="button" data-toggle="dropdown">Select Date <span class="caret"></span></button> ' +
'<div class="dropdown-menu"><div class="everyday-part">' +
'<li> <label> ' +
'<input type="checkbox" id="everyday" class="everyday_check_box form form-control" name="time['+stack+'][everyday]" value="7"> Everyday </label>' +
'</li>' +
'</div>' +
'<div class="day-part">'+
// The Problem is Started From Here
makeString(day_left,stack)+'</div> </div> </div> </div></div><div class="clearfix"></div><br> ');
plnkr https://plnkr.co/edit/aBLj49Yv2g4EakeKjlqI?p=preview
you can do like that......
just use return function or make you iteration returnable.
<script>
var day_left = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
$(".add_schedule").click(function () {
if ($('.day-part').is(':empty')){
alert("You have limit schedule time!")
}else{
var stack = $(this).parent().find('#stack').val();
alert("form-schedule-"+stack);
$(this).before('<div class="form-schedule" id="form-schedule-'+stack+'">' +
'<div class="col-md-4">' +
'<label>Start Time</label><input type="time" placeholder="ex : 00:00" name="time['+stack+'][open_time]" class="open_time form-control" id="open_time'+stack+'">' +
'</div>' +
'<div class="col-md-4">' +
'<label>End Time</label><input type="time" placeholder="ex : 21:00" name="time['+stack+'][close_time]" class="close_time form-control" id="close_time"></div>' +
'<div class="col-md-4">' +
'<label>Pilih Hari</label> ' +
'<div class="dropdown dropdown-payment">' +
'<button class="btn btn-primary btn-sm dropdown-toggle" type="button" data-toggle="dropdown">Select Date <span class="caret"></span></button> ' +
'<div class="dropdown-menu"><div class="everyday-part">' +
'<li> <label> ' +
'<input type="checkbox" id="everyday" class="everyday_check_box form form-control" name="time['+stack+'][everyday]" value="7"> Everyday </label>' +
'</li>' +
'</div>' +
'<div class="day-part">'+
// The Problem is Solved
function(){var s='';
$.each(day_left,function (i,val) {
s += '<li><label><input type="checkbox" checked="checked" id="date_check_box" class="form form-control" name="time[' + stack + '][date][]" value="' + i + '">'+val+'</label> </li>';
});
return s;}
+'</div> </div> </div> </div></div><div class="clearfix"></div><br> ');
// End Of the Problem
stack = parseInt(stack)+1;
$(this).parent().find('#stack').val(stack);
}
});
</script>
HTML
<input class="form-check-input" type="checkbox" id="hotels" value=""> HOTELS
<div id="hebergement"></div>
jQuery I make input id ="nbchambre"
$(document).ready(function (){
$('#hotels').on('change', function() {
if ($('#hotels').is(":checked"))
{
var hotels = $('#hotels:checked').val()
//alert( hotels ); // or $(this).val()
$('#hebergement div').empty();
var i,ch='';
for(i=0;i<<?php echo $ln; ?>;i++) {
ch += "<option value='"+ arrayregime[i] +"'>"+arrayregime[i]+"</option>";
}
//alert(test);
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'divhotel');
newTextBoxDiv.after().html('<hr/><center> <h4 style="color: #3385c0;"> VOTRE DESTINATION</h4></center>' +
' <div class="row"> <div class="col-md-3"> '+
' <label>Date depart</label> '+
'<div class="input-group">'+
'<div class="input-group-addon">'+
' <i class="fa fa-calendar"></i> '+
'</div> <input class="form-control" name="datedepart" id="datedepart" placeholder="MM/DD/YYYY" type="date" >'+
' </div>'+
' </div>'+
' <div class="col-md-3"> '+
' <label>Date retour</label> '+
'<div class="input-group">'+
'<div class="input-group-addon">'+
' <i class="fa fa-calendar"></i> '+
'</div> <input class="form-control" name="dateretour" id="dateretour" placeholder="MM/DD/YYYY" type="date" >'+
' </div>'+
' </div> </div>'+
'<div class="form-group row" ><label class="col-xs-2 col-form-label">Categorie hotels</label> <div class="col-xs-2"><select name="categ" class="form-control"><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> </select> </div> '+
'<label class="col-xs-2 col-form-label">Pention hotels</label> <div class="col-xs-2"><select name="categ" class="form-control"> '+ch+' </select> </div></div> '+
'<input class="form-control" type="number" name="nbchambre" id="nbchambre" value="0" /><div id="typechambre"> </div>'+
' ');
newTextBoxDiv.appendTo("#hebergement");
}
else{
$('#hebergement div').empty();
}
});
});
Action with input nbchambre
<script type="text/javascript">
$(document).ready(function (){
$('#nbchambre').on('change', function() {
//alert( this.value ); // or $(this).val()
var test = parseInt($("#nbchambre").val(), 10);
//alert(test);
$('#typechambre div').empty();
var i,ch='';
ch = "<option value='single'>Single</option><option value='double'>Double</option><option value='triple'>Triple</option><option value='quadruple'>Quadruple</option><option value='appartement'>Appartement</option>";
for(i=1;i<=test;i++) {
//$( "#TextBoxesGroup" ).remove();
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'chambre' + i);
newTextBoxDiv.after().html('<label class="col-xs-2 col-form-label">Chambre '+ i + ' : </label> <div class="col-xs-1">' +
'<select class="form-control" name="enfants[]" >'+ch+'</select>' );
newTextBoxDiv.appendTo("#typechambre");
}
});
});
Question
Why does the action not apply the input?
Change in your input which you are binding run time.
<input class="form-control" type="number" name="nbchambre" id="nbchambre" value="0" />
change to
<input class="form-control nbchambre" type="number" name="nbchambre" id="nbchambre" value="0" />
Now write your change event as follow
$(document).on('change', '.nbchambre', function() {
//alert( this.value ); // or $(this).val()
var test = parseInt($("#nbchambre").val(), 10);
//alert(test);
$('#typechambre div').empty();
var i,ch='';
ch = "<option value='single'>Single</option><option value='double'>Double</option><option value='triple'>Triple</option><option value='quadruple'>Quadruple</option><option value='appartement'>Appartement</option>";
for(i=1;i<=test;i++) {
//$( "#TextBoxesGroup" ).remove();
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'chambre' + i);
newTextBoxDiv.after().html('<label class="col-xs-2 col-form-label">Chambre '+ i + ' : </label> <div class="col-xs-1">' +
'<select class="form-control" name="enfants[]" >'+ch+'</select>' );
newTextBoxDiv.appendTo("#typechambre");
}
});
Hope it will be helpful for you.
Delegate the change event to #hebergement because #nbchambre is added after the page load.
$('#hebergement').on('change', 'input[name=nbchambre]', function(){
...
...
});
Info: Understanding Event Delegation
Side note: don't repeat the same ID for multiple elements (id="nbchambre")