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.
Related
How to add input fields on button click where this is the answer given i would like to add this to my form which this scenario
Here my snippet code
$('.add1').on('click', add);
$('.remove1').on('click','.remove1', remove);
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
var new_input = "<input type='text' id='new_" + new_chq_no + "'><input class='remove1' id='newbutton" + new_chq_no + "' type='button' value='x'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
}
function remove() {
var last_chq_no = $('#total_chq').val();
if (last_chq_no > 1) {
$('#new_' + last_chq_no).remove();
$('#total_chq').val(last_chq_no - 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact Name:</label>
<div class="col-4" id="contactContainername">
<div class="flex contactname" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required>
<input style="border-radius: 5px;" type="button" class="add1 btn-primary" value="Add More Field" style="cursor: pointer;">
<input type="button" class="remove1" value="x"><label style="cursor: pointer; padding-top: 5px;">
<i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label"></label>
<div class="col-4" id="contactContainername">
<div id="new_chq" class="flex contactname" style="margin-bottom:10px;">
<input type="hidden" value="1" id="total_chq" style="margin-right: 10px; width: 200px;" name="contactname" class="form-control" placeholder="Name" required>
</div>
</div>
</div>
I would like that when press more fields a new input appear with the button x where u are able to click and remove the new input
Here the image of what i mean
How can i do it ?
You could do one of two things either change your on click to search for your class everytime you click or attach an clicklistener to your element to change your onclick you could do
$('body').on('click','.remove1', remove);
or to attach to your element
var new_input = $("<input type='text' id='new_" + new_chq_no + "'><input class='remove1' id='newbutton" + new_chq_no + "' type='button' value='x'>");
new_input.on('click',remove)
But to get your code running correctly you have to fix your remove function aswell, here's an example of how it could look
$('.add1').on('click', add);
$('body').on('click','.remove1', remove);
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
var new_input = "<label><input type='text' id='new_" + new_chq_no + "'><input class='remove1' id='newbutton" + new_chq_no + "' type='button' value='x'></label>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
}
function remove() {
var last_chq_no = $('#total_chq').val();
$(this).closest('label').remove()
$('#total_chq' + '.remove1').val(last_chq_no - 1);
}
I am cloning four field (sl no,stationery type ,quantity, Remove ) of a form by using java script.I can very well append or remove these field
I am not able to generate the serial no on the first column and if I delete any row in between this should also adjust the serial no.How can i achieve this My code is below
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
$(document).on('keypress', '.number_only', function(e) {
return isNumbers(e, this);
});
function isNumbers(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<br />
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;>
<div class=" row ">
<div class="col-md-4 ">
</div>
<div class="col-sm-12 ">
<h4 align="center "><b><u>Add Stationery Stock<b></u></h4>
<br />
<form method="post " id="insert_form ">
<div class="col-sm-6 ">
<input type="text " name="Order No. " class="form-control " placeholder="Order NO "/>
</div>
<div class="col-sm-6 ">
<input type="date " name="Date " class="form-control " placeholder="Date " />
</div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center "><b><u>Stationery Details<b></u></h4>
<div> </div>
<div class="table-repsonsive ">
<span id="error "></span>
<table class="table table-bordered " id="item_table ">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button " name="add " class="btn btn-success btn-sm add "><span class="glyphicon glyphicon-plus "></span></button></th>
</tr>
</table>
<div align="center ">
<input type="submit " name="submit " class="btn btn-info "style="margin-bottom:20px " value="Insert " />
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Using
html += '<td><input type="text" name="item_name[]" class="form-control item_name"></td>';
you can do
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
when needed
I fixed your invalid HTML (u and b not correctly closed and a missing quote on the first inline style)
I ALSO remove the name="submit" - you never want to have name="submit" on a form you plan to submit using script
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
$(function() {
$("#item_table").on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
renum()
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
renum()
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;">
<div class="row">
<div class="col-md-4"></div>
<div class="col-sm-12">
<h4 align="center"><b><u>Add Stationery Stock</u></b></h4>
<form method="post" id="insert_form">
<div class="col-sm-6"><input type="text" name="Order No." class="form-control" placeholder="Order NO " /></div>
<div class="col-sm-6"><input type="date" name="Date" class="form-control" placeholder="Date" /></div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center"><b><u>Stationery Details</u></b></h4>
<div> </div>
<div class="table-repsonsive"><span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center"><input type="submit" class="btn btn-info" style="margin-bottom:20px" value="Insert" /></div>
</div>
</form>
</div>
</div>
</div>
I have an issue in showing filenanme to its corresponding field.
Now,
When i browse a file in the appended div,then it's file name is shown in the parent div instead of dynamically appended div.
Form
<!-- start other_docx -->
<div class="img_field">
<div class="j-row ">
<label class="j-label">Other Documents</label>
<div class="j-span9 j-unit">
<label class="j-input j-append-small-btn">
<label class="j-icon-left" for="files[]">
<i class="fa fa-download"></i>
</label>
<div class="j-file-button">
Browse
<!-- <input type="file" name="files[]" onchange="document.getElementById('files[]').value=this.value;"> -->
<input type="file" name="files[]" onchange="setfilename(this.value);">
</div>
<input type="text" id="files[]" readonly="" placeholder="No file selected">
<span class="j-hint">Only: jpg / png / Pdf</span>
</label>
</div>
<div class="j-span3 j-unit">
<div class="" style="margin-top:5px">
<button style="" class="btn btn-sm btn-primary add_more_button">Add more</button>
</div>
</div>
</div>
</div>
<!-- end other_docx -->
setfilename()
<script>
function setfilename(val)
{
var fileName = val.substr(val.lastIndexOf("\\")+1, val.length);
document.getElementById("files[]").value = fileName;
}
</script>
js
$(document).ready(function() {
var max_fields_limit = 10; //set limit for maximum input fields
var x = 1; //initialize counter for text box
$('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
e.preventDefault();
if(x < max_fields_limit){ //check conditions
x++; //counter increment
// $('.img_field').append('<div><input type="file" name="files[]" class="form-control"/>Remove</div>'); //add input field
// var name="document.getElementById('files[]').value=this.value;";
$('.img_field').append('<div class="j-row">' +
'<div class="j-span9 j-unit">' +
'<label class="j-input j-append-small-btn">' +
'<label class="j-icon-left" for="files[]">' +
'<i class="fa fa-download"></i>' +
'</label>' +
'<div class="j-file-button"> Browse' +
'<input type="file" name="files[]" onchange="setfilename(this.value);">' +
// '<input type="file" name="files[]" onchange="'+name+'">' +
'</div>' +
'<input type="text" id="files[]" readonly="" placeholder="No file selected">' +
'<span class="j-hint">Only: jpg / png</span>' +
'</label>' +
'</div>' +
'<div class="j-span3 j-unit">' +
'<div class="" style="margin-top:5px">' +
'<button style="" class="btn btn-sm btn-danger remove_field">Remove</button>' +
'</div>' +
'</div>' +
'</div>');
}
});
$('.img_field').on("click",".remove_field", function(e){ //user click on remove text links
e.preventDefault();
// $(this).parent('div').remove();
$(this).closest("div.j-row").remove();
x--;
})
});
and this is what my form looks like..
enter image description here
I'm kinda new to jquery.. any help will be greatly appreciated.
Thank you in advance.!
//Edit
working fine now.I just replaced the id 'files[]' with a unique id for each dynamically created element.
Thanks to Ouroborus for mentioning the mistake.
I have used orders.append in my GET AJAX method to display the user details stored in API. In here I have used 2 buttons save and cancel respectively with class "saveEdit edit" to edit the details. When the edit button is hit a modal pop-up to display the form to edit. On hitting save the details ain't getting saved jus the page refreshes. Save goes with the cancel button. Can you help me out?
My Bootstrap modal:
<div class="modal fade" id="myModallp" 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">Edit</h4>
</div>
<div class="modal-body">
<!-- Form for editing details.-->
<form id="uploadimageformm">
<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="text" maxlength="10" placeholder="contact no." id="contact" name="user[contact_number]" onkeypress="return isNumberKey(event)" /><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 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>
<button class="saveEdit edit" data-id=' + order.id + ' type="submit" onclick="">Save</button>
<button class="cancelEdit edit">Cncl</button>
</form>
<div id="ack"></div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
My GET method of Ajax:
$.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" data-toggle="modal" data-target="#myModallp">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" id="user_photo_'+order.id+'" 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');
}
});
My edit jquery method:
$orders.delegate('.editOrder','click',function(){
var $tr = $(this).closest('tr');
$tr.addClass('edit');
})
My cancel jquery method:
$orders.delegate('.cancelEdit','click',function(){
var $tr = $(this).closest('tr').removeClass('edit');
})
And lastly my saveEdit method:
$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_"+user_id).files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("user_photo_"+user_id).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');
}
});
});
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.