In laravel 5.7 / jquery 3 app looking at the snippet https://bootsnipp.com/snippets/ykXa
I made similar, but having several input/select elements.
I add new row with input/select elements code :
$(document).on('click', '.todo-btn-add', function(e)
{
e.preventDefault();
var todos_count= parseInt($("#todos_count").val())+1
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
var modifiedHidden= newEntry.find('input');
modifiedHidden.val('1');
modifiedHidden.attr('id','todo_modified_'+todos_count);
modifiedHidden.attr('name','todo_modified_'+todos_count);
var todo_text_input= modifiedHidden.next( "input" )
todo_text_input.val('');
todo_text_input.attr('id','todo_text_'+todos_count);
todo_text_input.attr('name','todo_text_'+todos_count);
var todo_select_priority= newEntry.find( "select" )
todo_select_priority.val('');
todo_select_priority.attr('id','todo_priority_'+todos_count);
todo_select_priority.attr('name','todo_priority_'+todos_count);
var todo_select_completed= todo_select_priority.find( "select" )
todo_select_completed.val('');
todo_select_completed.attr('id','todo_completed_'+todos_count);
todo_select_completed.attr('name','todo_completed_'+todos_count);
controlForm.find('.entry:not(:last) .todo-btn-add')
.removeClass('todo-btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="fa fa-minus"></span>');
$("#todos_count").val( todos_count )
}).on('click', '.btn-remove', function(e)
{
$(this).parents('.entry:first').remove();
$("#todos_count").val( parseInt($("#todos_count").val())-1 )
e.preventDefault();
return false;
});
But problem that saving the form I collect all data in 1 array to save it on server with:
function saveTodoDialog( csrf_token ) {
let todos_count= $("#todos_count").val()
let todosList= [];
for(let i= 0; i< todos_count; i++) {
let todoItem = {
todo_id: $("#todo_id_" + i).val(),
todo_modified: $("#todo_modified_" + i).val(),
todo_text: $("#todo_text_" + i).val(),
todo_priority: $("#todo_priority_" + i).val(),
todo_completed: $("#todo_completed_" + i).val()
}; //Object initialiser
alert("todos_count::"+todos_count+ " i::"+i+"todoItem::"+var_dump(todoItem) )
todosList.push(todoItem);
}
console.log("todosList::")
console.log( todosList )
let href = "/admin/save-todo-page";
$.ajax({
type: "POST",
dataType: "json",
url: href,
data: { "_token": csrf_token, "todosList" : todosList },
success: function (response) {
popupAlert("Todo items were saved successfully !", 'success')
},
error: function (error) {
popupErrorMessage(error.responseJSON.message)
}
});
But checking data for any row I see that all data for newly added rows has undefined value.
How to fix it ?
Thanks!
If the error is happening because you are getting undefined from your inputs, I suggest adjusting your saveTodoDialog() method.
function saveTodoDialog( csrf_token ) {
let todoList = Array.prototype.slice
.call( document.querySelectorAll('input.form-control') )
.map( (todo, index) => {
// Create Individual TODO object
});
// Make server request
}
Related
Here's the workflow of my form:
Display form with input and select elements >> all of the select elements have a button to add new data via a modal window that performs a database insert via ajax and closes the modal window >> on modal close, I fire the refreshData() function which pulls in the new data from json into the select elements of the form.
All of the above is working great, but how do I mark the correct option (last added via modal window) in the refreshSelect() function below? For example: I add a new supplier to my database via modal window, it inserts correctly to the DB, but how do I mark that new supplier as selected after modal window close?
Here's a sample of the json data I'm working with:
{"suppliers":{"1":"Amazon","2":"Lenovo"},"manufacturers":{"1":"Apple","2":"Lenovo"},"categories":{"2":"Tablet"},"status":{"1":"Ready to Deploy","2":"Deployed","3":"Damaged"}}
jQuery function that will pull data from json via ajax and refresh the select elements on the page:
$(document).ready(function() {
// Initial load
refreshData();
});
function refreshData(newId) {
$.ajax({
url: '/json/collection.json',
type: 'GET',
dataType: 'json',
success: function(data) {
refreshSelect('inputSupplier', data.suppliers, newId);
refreshSelect('inputManufacturer', data.manufacturers, newId);
refreshSelect('inputStatus', data.status, newId);
refreshSelect('inputCategory', data.categories);
refreshSelect('inputManufacturerModel', data.manufacturers, newId); //modal window select
}
});
}
function refreshSelect(name, data, newId) {
// Select by id
let $elem = $('#' + name);
// Get current value
let oldValue = $elem.val();
// Get "template" value with value 0, which is the first element
let emptyOption = $elem.children('option').first();
// Empty the element and add the option. We are back to initial state
$elem.html(emptyOption);
// Append elements retrieved from backend
$.each(data, function(key, value) {
$elem.append('<option value="' + key + '">' + value + '</option>');
});
if(newId){
$elem.val(newId);
}else{
$elem.val(oldValue);
}
}
Function that will insert new values to the database via ajax from the modal window (Very basic):
$(document).ready(function ()
{
$('.modal-submit').on('submit', function(e){
e.preventDefault(); //prevent default form submit action
$(".backend-error").html(''); //clear out previous error messages
$('input').removeClass('input-error'); //clear error border class
var data = $(this).serialize();
var type = $(this).find('input[name="type"]').val();
switch(type){
case "supplier":
var url = '{{ action('AddAssetController#addDescriptor', ['type' => 'supplier']) }}';
var modalName = '#supplierModal';
var modalInput = '#inputSupplierNew';
break;
case "manufacturer":
var url = '{{ action('AddAssetController#addDescriptor', ['type' => 'manufacturer']) }}';
var modalName = '#manufacturerModal';
var modalInput = '#inputManufacturerNew';
break;
case "model":
var url = '{{ action('AddAssetController#addDescriptor', ['type' => 'model']) }}';
var modalName = '#modelModal';
var modalInput = '#inputModelNew';
break;
case "status":
var url = '{{ action('AddAssetController#addDescriptor', ['type' => 'status']) }}';
var modalName = '#statusModal';
var modalInput = '#inputStatusNew';
break;
case "category":
var url = '{{ action('AddAssetController#addDescriptor', ['type' => 'category']) }}';
var modalName = '#categoryModal';
var modalInput = '#inputCategoryNew';
break;
}
$.ajax({
url:url,
method:'POST',
data:data,
success:function(response){
refreshData(newId = response.id); // set newId to the id of the newly inserted item
$(modalName).modal('hide'); //hide modal
$(modalInput).val(''); //clear input value
},
error:function(e){
//console.log(error.responseJSON.error)
//console.warn(error.responseJSON.error);
$.each(e.responseJSON.error, function (i, error) {
$(modalInput).addClass('input-error');
$(modalName + ' .backend-error').html(error[0]); //return error from backend
});
}
});
});
});
Edit: Revised code added
You can pass the required new value to be set to select box from your ajax POST's success handler to your refreshData() call and ultimately to your refreshSelect() function as follows:
Save Data Call:
var data = $(this).serialize();
console.log(data);
/*TODO*/
var newSupplierId = <logic to get ID/Name of newly added supplier>;
var url = '{{ action('AddAssetController#addAttribute', ['type' => 'supplier']) }}';
$.ajax({
url:url,
method:'POST',
data:data,
success:function(response){
if(response.success){
refreshData(newSupplierId); //passing newSupplierId to refreshData function
$('#supplierModal').modal('hide');
$('#inputSupplierNew').val('');
console.log(response);
}else{
alert('There was an error inserting data. Please try again.')
}
},
error:function(error){
console.log(error)
}
});
Other modified code:
function refreshData(newSupplierId) {
$.ajax({
url: '/json/collection.json',
type: 'GET',
dataType: 'json',
success: function(data) {
refreshSelect('inputSupplier', data.suppliers, newSupplierId);
refreshSelect('inputManufacturer', data.manufacturers);
refreshSelect('inputStatus', data.status);
refreshSelect('inputCategory', data.categories);
refreshSelect('inputManufacturerModel', data.manufacturers); //modal window select
}
});
}
function refreshSelect(name, data, newSupplierId) {
// Select by id
let $elem = $('#' + name);
// Get current value
let oldValue = $elem.val();
// Get "template" value with value 0, which is the first element
let emptyOption = $elem.children('option').first();
// Empty the element and add the option. We are back to initial state
$elem.html(emptyOption);
// Append elements retrieved from backend
$.each(data, function(key, value) {
$elem.append('<option value="' + key + '">' + value + '</option>');
});
if(newSupplierId) // check whether newSupplierId is null or not
{
//if newSupplierId is not null means select newly added supplier
$elem.val(newSupplierId);
}
else{
// Restore selection
$elem.val(oldValue);
}
}
Hope this will help you.
I am using ajax to validate user credentials after i have validated the user has input data into the required fields but afterwords the form is not being submitted. I have created a variable submit_form which is supposed to determine if the default form action is performed or not but when set it to true and console log it, it still seems to continue it's default value of false, why is it like that and how can change it so my form can submit after the username and password are correct.
Here is my screenshot of the console in the browser
Here is a my code:
/*global $*/
/*global _*/
$(document).ready(function() {
'use strict';
$('#login-form').on('submit', function(event) {
var form_items = {
username: { required: true, name: 'Username' },
password: { required: true, name: 'Password' },
token: {}
};
var $login_form = $(this);
var submit_form = false;
var errors;
var display = '';
var data;
var validation = new Validation( form_items );
validation = validation.check( $login_form['context'] );
// If any element has the class for errors, remove the class
$('.has-error').removeClass('has-error');
if ( validation.passed() ) {
data = JSON.stringify( validation.getData() );
$.ajax({
method: "POST",
url: "ajax/login.ajax.php",
data: { info: data }
}).done(function( response ) {
response = JSON.parse(response);
// if the error list display is there, remove it
$('.bg-danger').parent().remove();
if ( _.has(response, 'errors') ) {
errors = response['errors'];
display = '<div class="form-group"><ul class="bg-danger">';
if ( _.isArray(errors) || _.isObject(errors) ) {
_.each( errors, function(elem, index, list) {
display += '<li>' + elem + '</li>';
});
} else {
display += '<li>' + errors + '</li>';
}
display += '</ul></div>';
$login_form.prepend( display );
} else {
submit_form = true;
}
});
console.log( submit_form );
} else {
// if the error list display is there, remove it
$('.bg-danger').parent().remove();
errors = validation.getErrors();
display = '<div class="form-group"><ul class="bg-danger">';
_.each( errors, function(elem, index, list) {
var $form_element = $('#'+index); // get form element
$form_element.parent().parent().addClass('has-error');
display += '<li>' + elem + '</li>';
});
display += '</ul></div>';
$login_form.prepend( display );
}
if ( !submit_form ) {
event.preventDefault();
}
});
});
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
I'm very new to ajax/javascript so I will try my best to explain my problem. Here's what I have so far:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).val());
console.log($(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default.aspx",
type: "post",
dataType: "json",
data: { UpdateQuery: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
Every time a checkbox is checked, ajax passes the data onto the server. Here is an example of some checkbox values after a few have been checked in the data form obtained from the Developer's Console:
You can try the following code:
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
I have been using this jQuery before I use $.ajax(); and it was working good:
$(document).ready(function(){
var urlSerilize = 'some link';
var appList = $("#applications > li > a");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//var appList = $(".body-list > ul > li");
//var appCheck = $('input[type=checkbox][data-level="subchild"]');
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
installbtn.on('click', function () {
event.preventDefault();
jQuery.each( form, function( i, val ) {
console.log(val);
var request = $.ajax({
url: urlSerilize,
type: 'GET',
data: $('#'+val).serialize(),
success: function( response ) {
console.log( response );
$('#applications').html();
$('#apps_box').html();
}
});
request.done(function(msg){
console.log('Ajax done: ' + 'Yeah it works!!!');
});
request.fail(function(jqXHR, textStatus){
console.log('failed to install this application: ' + textStatus);
});
});
});
});
but after I used this ajax code the .click() jQuery event don't work anymore:
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
})
request.fail(function() {
console.log("error");
})
request.always(function() {
console.log("complete");
});
//end loading apps
var showmore = $('.showapps');
showmore.click(function(){
var parent = $(this).parent('.tv_apps');
var displayC = parent.children('.body-list').css('display');
console.log(displayC);
if (displayC=='none') {
parent.children('.body-list').show('400');
$(this).children().find('img').rotate({animateTo: 180});
}else{
parent.children('.body-list').hide('400');
$(this).children().find('img').rotate({animateTo: 0});
};
});
});
at first place I though it was because of the ajax loads and don't stop, then i was wrong.
I have tried the window.load=function(); DOM function to load the script after Ajax finish loading and also was wrong.
So please if there any idea to fix this problem,
Thanks.
This is the event I want it to be fixed:
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
showmore.click(function(){
should be
$('.showapps').on('click', function(){
OR
$(document).on('click','.showapps', function(){
For dynamically added contents, you need to bind events to it.
For more info: http://learn.jquery.com/events/event-delegation/
Thanks everyone, at last I have found the solution.
It was a question of the DOM, when I use the ready method of jquery it loads an empty ul (without content), so then what I figured out in the first time was correct, all I did is to remove the ready and use a simple function that includes all the .click() events, then call it in request.done();.
This is the solution:
function loadInstaller(){
var urlSerilize = 'some link';
var appList = $("#applications > li");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//...etc
};
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
loadInstaller();
})
//...etc
});
I hope this answer will help someone else :)