Add and edit form in one page - javascript

I have two buttons 'Add' and 'Edit' in my page. When I try to click the 'Add' button I get one popup form and I fill the details and will be added in to the database. The same thing when I click the 'Edit' button the same form should be displayed with the filled in details. I know how to get the data from the backend. But I am not aware of how should I differentiate the add and edit in one form.
https://jqueryui.com/dialog/#modal-form
I have refered this link and I have added the details for add form.
Can some one help me how do I do the edit?
<html>
<input class="btn btn-info" type="button" id="create-user" value="Add user">
<div class="row-fluid top-space-20">
{% if result | length == 0 %}
<div>
<p>There are no user details ,If you want you can add it </p>
</div>
{% else %}
<table class="table table-striped">
<thead>
<th>user name</th>
<th>user duration</th>
<th>user Description</th>
<th>user requirements</th>
<th>Actions</th>
</thead>
{% for each_item in result %}
<tbody>
<td>{{each_item.user_name}}</td>
<td>{{each_item.user_time}}</td>
<td>{{each_item.user_description}}</td>
<td>{{each_item.user_requirement}}</td>
<td>
<input class="btn btn-info" type="button" id="edituser" value="Edit">
</td>
</tbody>
{% endfor %}
{% endif %}
</table>
</div>
</div>
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="username">user name</label>
<input type="text" name="username" id="username" class="text ui-widget-content ui-corner-all">
<label for="duration">Duration</label>
<input type="text" name="duration" id="duration" class="text ui-widget-content ui-corner-all">
<label for="description">Description</label>
<input type="text" name="description" id="description" class="text ui-widget-content ui-corner-all">
<label for="requirements">Requirements</label>
<input type="requirements" name="requirements" id="requirements"
class="text ui-widget-content ui-corner-all">
<input type="hidden" id='departmentId' ,value="{{department_id}}">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<script>
$(function () {
var dialog, form,
username = $("#username"),
duration = $("#duration"),
description = $("#description"),
requirements = $("#requirements"),
allFields = $([]).add(username).add(duration).add(description).add(requirements),
tips = $(".validateTips");
function updateTips(t) {
console.log(t);
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
var username = $("#username");
var duration = $("#duration");
var description = $("#description");
var requirements = $("#requirements");
var departmentId = document.getElementById("departmentId").value;
valid = valid && checkLength(username, "username", 3, 16);
valid = valid && checkLength(duration, "duration", 3, 16);
valid = valid && checkLength(description, "description", 3, 300);
valid = valid && checkLength(requirements, "requirments", 5, 300);
if (valid) {
var username = $("#username").val();
var duration = $("#duration").val();
var description = $("#description").val();
var requirements = $("#requirements").val();
var departmentId = document.getElementById("departmentId").value;
$("#users tbody").append("<tr>" +
"<td>" + username + "</td>" +
"<td>" + duration + "</td>" +
"<td>" + description + "</td>" +
"<td>" + requirements + "</td>" +
"</tr>");
$.ajax({
type: 'POST',
url: '/department/%d/user' % departmentId,
data: {
'username': username,
'duration': duration,
'description': description,
'requirements': requirements
},
success: function (result) {
console.log(result);
alert("The user has been added");
document.location.href = "/departments";
},
})
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create user": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function () {
console.log("I am first");
dialog.dialog("open");
});
});
</script>
</body>
</html>

There are Multiple Way to do it, Next time Please Post the code. Let me assume that you were using the
Model to view
https://jqueryui.com/dialog/#modal-form.
For more details post the code we can help you out
Here is the updated Answer
<tbody>
<td>{{each_item.user_name}}</td>
<td>{{each_item.user_time}}</td>
<td>{{each_item.user_description}}</td>
<td>{{each_item.user_requirement}}</td>
<td>
<input class="edituser btn btn-info" type="button" value="Edit" data-user-id = "{{each_item.user_id}}">
</td>
</tbody>
change the id to class
$(".edituser").button().on("click", function () {
var id = $(this).attr("data-user-id");
var tempUser;
for(var user in results){
if(user.id == id){
tempUser = user;
}
}
$("#username").val(tempUser.user_name);
$("#duration").val(tempUser.user_name);;
dialog.dialog("open");
});
you can set the value accordingly from using "user id"
and on submit change the value in the "results" object you using to construct the view

There are Multiple Way to do it, Next time Please Post the code. Let me assume that you were using the Jquery Model to view
https://jqueryui.com/dialog/#modal-form.
First Way: One Add button one Edit Button(assuming)
set id = "Add" for add id = "edit"
On Click on Add but show the empty form and use $( "#dialog-form" .dialog( "open" ); to to open the empty form
On click on Edit Set the Value in the form (fetch the value from the database if its required) and then $( "#dialog-form" .dialog( "open" );
Secon Way: One Add button Multiple Edit Button(assuming) for each li
1. use class selector class ="edit"
<button class ="edit" data-form-id = "123">Edit</button>
$( ".edit" ).click(function()
{
var formId = $(this).attr("data-form-id ");
$( "#dialog-form" .dialog( "open" );
});
For more details post the code we can help you out

you can add
<input type='hidden' name='actiontype'>
and set value Edit Or Add then in backend you can read this value and choose action for form

Related

DIfferent URL has to be passed for same ajax call

I am doing add and edit operation.
To perform edit operation I have used the below link for reference
and finished it. If I click the edit button I can see popup form with details. Now I have to call the funtion and should perform ajax call for both add and edit. But the URL for edit is different .How should I do it?Please refer my previous question
<html>
<head>
<title>
List of user
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Add,Edit,Delete user</title>
<link href="/static/css/qxf2_scheduler.css" rel="stylesheet">
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet">
<link href="//resources/demos/style.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="dialog-confirm" title="Delete user?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These user will be
permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<div class="container col-md-offset-1">
<h2 class="grey_text text-center">user List</h2>
<input class="btn btn-info" type="button" id="create-user" value="Add user">
<div class="row-fluid top-space-20">
{% if result | length == 0 %}
<div>
<p>There are no user details ,If you want you can add it </p>
</div>
{% else %}
<table class="table table-striped">
<thead>
<th>user name</th>
<th>user duration</th>
<th>user Description</th>
<th>user requirements</th>
<th>Actions</th>
</thead>
{% for each_item in result %}
<tbody>
<td>{{each_item.user_name}}</td>
<td>{{each_item.user_time}}</td>
<td>{{each_item.user_description}}</td>
<td>{{each_item.user_requirement}}</td>
<td>
<input class="edituser btn btn-info" type="button" value="Edit" data-user-id = "{{each_item.user_id}}" data-user-name="{{each_item.user_name}}" data-user-description="{{each_item.user_description}}" data-user-requirement="{{each_item.user_requirement}}" data-user-duration="{{each_item.user_time}}">
<input type="button" class="btn btn-info" onclick="delete_user(this)" value="Delete"
id="delete-button{{each_item.user_id}}" data-delete-user-id="{{each_item.user_id}}"
data-delete-department-id="{{department_id}}" />
</td>
</tbody>
{% endfor %}
{% endif %}
</table>
</div>
</div>
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="username">user name</label>
<input type="text" name="username" id="username" class="text ui-widget-content ui-corner-all">
<label for="duration">Duration</label>
<input type="text" name="duration" id="duration" class="text ui-widget-content ui-corner-all">
<label for="description">Description</label>
<input type="text" name="description" id="description" class="text ui-widget-content ui-corner-all">
<label for="requirements">Requirements</label>
<input type="requirements" name="requirements" id="requirements"
class="text ui-widget-content ui-corner-all">
<input type="hidden" id='departmentId' ,value="{{department_id}}">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<script>
$(function () {
var dialog, form,
username = $("#username"),
duration = $("#duration"),
description = $("#description"),
requirements = $("#requirements"),
allFields = $([]).add(username).add(duration).add(description).add(requirements),
tips = $(".validateTips");
function updateTips(t) {
console.log(t);
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function addUser(url,msg) {
var valid = true;
allFields.removeClass("ui-state-error");
var username = $("#username");
var duration = $("#duration");
var description = $("#description");
var requirements = $("#requirements");
var departmentId = document.getElementById("departmentId").value;
valid = valid && checkLength(username, "username", 3, 16);
valid = valid && checkLength(duration, "duration", 3, 16);
valid = valid && checkLength(description, "description", 3, 300);
valid = valid && checkLength(requirements, "requirments", 5, 300);
console.log(url,msg);
if (valid) {
var username = $("#username").val();
var duration = $("#duration").val();
var description = $("#description").val();
var requirements = $("#requirements").val();
var departmentId = document.getElementById("departmentId").value;
$("#users tbody").append("<tr>" +
"<td>" + username + "</td>" +
"<td>" + duration + "</td>" +
"<td>" + description + "</td>" +
"<td>" + requirements + "</td>" +
"</tr>");
$.ajax({
type: 'POST',
url: url,
data: {
'username': username,
'duration': duration,
'description': description,
'requirements': requirements
},
success: function (result) {
console.log(result);
alert(msg);
document.location.href = "/departments";
},
})
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create user": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
var url = '/department/%d/user'%departmentId;
var msg = 'The user has been added'
addUser(url,msg);
});
editDialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Edit user": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
var url = '/department/%d/user/edit'%departmentId;
var msg = 'The user has been edited'
addUser(url,msg);
});
$("#create-user").button().on("click", function () {
console.log("I am first");
dialog.dialog("open");
});
$(".edituser").button().on("click", function () {
var id = $(this).attr("data-user-id");
var userName=$(this).attr("data-user-name");
var userDuration=$(this).attr("data-user-duration");
var userDescription=$(this).attr("data-user-description");
var userRequirements=$(this).attr("data-user-requirement");
console.log(id,userName);
$("#username").val(userName);
$("#duration").val(userDuration);
$("#description").val(userDescription);
$("#requirements").val(userRequirements);
editDialog.dialog("open");
});
});
</script>
<script>
//Confirmation message for deleteing user
var user_id;
var department_id;
var dialog = $("#dialog-confirm").dialog({
resizable: false,
height: "auto",
autoOpen: false,
width: 400,
modal: true,
buttons: {
"Delete": function () {
console.log("user_id" + user_id)
$.ajax({
type: 'GET',
url: '/user/' + user_id + '/departments/' + department_id + '/delete',
data: { 'user_id': user_id },
success: function (data) {
window.location.reload();
console.log("successfully deleted the data")
}
})
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
function delete_user(action_delete) {
user_id = action_delete.getAttribute("data-delete-user-id");
department_id = action_delete.getAttribute("data-delete-department-id");
dialog.dialog("open");
}
</script>
</body>
</html>
By Making the common function for the Ajax:
function doAjaxCall(var url,var data,var method,var callBackFunction)
{
$.ajax({
type: method,
url: url,
data: data,
success: function(data){
callBackFunction(data);
}
});
}
Call the Function like this
function onAdd(data){
// Code to append
}
doAjaxCall("/add",userData,"POST",onAdd);
function onEdit(data){
// Code to update
}
doAjaxCall("/update",userData,"PUT",onEdit);
Store your url in a string variable. Depends on add/edit button onClick, change the url string of that variable and pass that variable in ajax call url attribute.

Switch toggle return to previous state when I click "No" in the alert prompt

I created a switch toggle that allows the system administrator to activate/deactivate the login access of an account.
After the admin click the switch toggle (the switch moving from state 1 to 0), it will prompt via alert box a confirmation (Do you want to activate / deactivate this account? Yes | No), whenever I click "no," I want it to return to its previous state (from 0 to 1).
I manage to successfully do this if the state is "1" [The account is activated], but when it's the other way around, from status 0 to 1, the switch toggle doesn't return back to its previous state and gets stuck to state 1.
It still sends the proper POST command tho (e.g. deactivates the account if it's activated, and vice versa), but the visual display is wrong.
This is my code.
Javascript for the toggle switch
var chk;
$(document).on('change', '.btn-change-status', function(e) {
e.preventDefault();
chk = $(this);
var switch_status = $(this).attr('data-status');
var account_status = (switch_status == 1) ? 0 : 1;
var id = $(this).attr('data-id');
var confirm_alert = (switch_status == 1) ? confirm("Are you sure you want to deactivate this account?") : confirm("Are you sure you want to activate this account?");
if (confirm_alert == true) {
$.ajax({
url: "/user/update-status",
type: "POST",
data: {
_token: "{{csrf_token()}}",
id: id,
status: account_status
},
success: function(data) {
if (data.success === true) {
alert("Account Successfully Updated!");
location.reload();
}
}
});
}
else {
if(chk.checked) {
chk.prop("checked", false);
}
else {
chk.prop("checked", true);
}
}
});
EDIT: added the HTML part of the switch, although it's still in javascript coz I attached it to a dataTable.
HTML of the dataTable
<div class="card mb-3">
<div class="card-header">
<i class="fas fa-table"></i>
Accounts Management</div>
<div class="card-body">
<button type="button" id="btn-add-account" class="btn btn-primary">Add Account</button>
<div class="table-responsive mt-3">
<table class="table table-bordered dt-responsive" id="table-accounts" width="100%" cellspacing="0">
<thead>
<tr>
<th class="hidden">ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Date Created</th>
<th style="width: 15.5%">Actions</th>
</tr>
</thead>
<tfoot>
<tr>
<th class="hidden">ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Date Created</th>
<th style="width: 15.5%">Actions</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
Javascript of the dataTable
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'username' },
{ data: 'email'},
{ data: 'role.id'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
// <button type='button' class='btn btn-primary btn-sm btn-edit' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>
// html += "<button class='btn btn-danger btn-sm btn-delete' data-id='"+data.id+"' data-account='"+data.id+"'>Remove</button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 4 }
]
});
Thank you!
There are too many values that represent the same thing. You only need two values:
id: [type: String] id of the checkbox.
status: [type: Boolean] By default a checkbox value is true if checked and false if not checked.
In this case you don't need any data-* attributes, but if you still think you do, use .data() method instead:
$('.status').data('id') // Returns the value of `data-id` on each `input.status`
If for some reason you find that you need to use more values for such a trivial task you need to reevaluate your code fundamentally. Details are commented in demo, it uses a live test server to verify what was sent to it.
/* This function extracts the value of each output.member and then assigns a
modified version of the value as the id of the checkbox that follows (input.status)
This is not required to answer the OP's question and is intended just to provide each
checkbox with a unique id */
$('.member').each(function(index) {
let user = $(this).val().split('#')
let id = user[0] + '-' + index;
$(this).next('.status').attr('id', id);
});
// Any change event occuring on any input.staus (checkbox)...
$('.status').on('change', function(e) {
// A boolean that reflects the checkbox "check status"
let checked = $(this).is(':checked');
// A simple confirm...
let changed = confirm("Are you sure you want to change this account?");
//... if user cancels...
if (!changed) {
/* ...ternary: [?][if checkbox is checked] - [uncheck it] [:][otherwise] - [check it]
[return][Terminate function - don't do anything else] */
return checked ? $(this).prop('checked', false) : $(this).prop('checked', true);
}
/* function continues here if user confirmed by clicking "OK"
The data will be posted to a live test server.
A link will appear at the bottom, follow the directions to verify response */
let ID = this.id;
let active = checked ? 1 : 0;
$.ajax({
url: "http://ptsv2.com/t/status/post",
type: "POST",
data: {
id: ID,
status: active
},
success: function() {
$('.response').show();
}
});
});
:root {
font: 16px/1 Arial
}
label {
display: block;
margin: 8px 0 0 0;
}
.member {
display: inline-block;
width: 25ch;
vertical-align: middle
}
.status {
display: inline-block;
vertical-align: middle
}
.response {
display: none;
cursor: pointer;
width: 99vw
}
.response * {
display: block;
margin: 8px auto;
width: 90%
}
<form id='admin-panel'>
<fieldset class='member-status'>
<legend>Member Status</legend>
<label>
<output class='member'>zer00ne#gmail.com</output>
Status: <input class='status' type='checkbox' checked>
</label>
<label>
<output class='member'>tech.artificer#gmail.com</output>
Status: <input class='status' type='checkbox' checked>
</label>
<label>
<output class='member'>joker666#4chan.org</output>
Status: <input class='status' type='checkbox'>
</label>
<label>
<output class='member'>byte.my#ss.com</output>
Status: <input class='status' type='checkbox' checked>
</label>
<label>
<output class='member'>bruce#wayne.com</output>
Status: <input class='status' type='checkbox' checked>
</label>
<label>
<output class='member'>clark.kent#dailyplanet.com</output>
Status: <input class='status' type='checkbox' checked>
</label>
</fieldset>
<hr>
<output class='response'>
<a href="https://ptsv2.com/t/status/d/latest" target='view'>Click then scroll down to <i style='display:inline'>Parameters</i> inside the iframe below</a>
<iframe name='view'></iframe>
</output>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Could you please update your post with your HTML, as I am unsure about the situation described in the question. I had an idea as to why the code doesn't work, but need to see the HTML to investigate further. In hindsight, I realise that my solution probably does not address the problem.
If the element with the class btn-change-status is a <button> tag in HTML, then jQuery's .on("change", handler) will not work (where handler is your function). According to the jQuery documentation:
The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements.
Instead, I would recommend using one of the following:
.on("click", handler)
.on("mouseup", handler)
.on("mousedown", handler)
See which one works.
Because you are using class selector '.btn-change-status'
chk = $(this);
chk is now a collection with 1 element. To check whether it is checked use
chk.prop('checked')
or
chk[0].checked
You are calling the ajax and trying to toggle your input at the wrong event. You have to handle those events on the yes button of the popup not in the change event.
The code should clear it out.
$(document).on('change', '.btn-change-status', function(e) {
e.preventDefault();
var chk = $(this);
var switch_status = $(this).attr('data-status');
var account_status = (switch_status == 1) ? 0 : 1;
var id = $(this).attr('data-id');
popUpConfirmation(id, status);
});
function popUpConfirmation(id,status) {
//popup opens here is visible
$("#ok-button").data("id", id);
$("#ok-button").data("status", status);
}
$("#ok-button").on('click', function() {
var id = $(this).attr('data-id');
var status = $(this).attr('data-status');
var checkbox = $("input[data-id='"+id+"']");
if(checkbox.prop('checked')) {
checkbox.prop('checked',false);
} else {
checkbox.prop('checked',true);
}
$.ajax({
url: "/user/update-status",
type: "POST",
data: {
_token: "{{csrf_token()}}",
id: id,
status: account_status
},
success: function(data) {
if (data.success === true) {
alert("Account Successfully Updated!");
location.reload();
}
}
});
});
$("#cancel-button").on('click', function() {
//close or hide the popup
});
For the popup create a view. This can be anything a div or a button, or you can use modal-view popups. the main key thing is the triggering buttons.
<div class="popup">
<input type="button" id="ok-button"></input>
<input type="button" id="cancel-button"></input>
</div>
This should fix your view issue without changing your code much. You can shorten the code using ternary operator. But I want to keep it simple for others to be able to understand too.
Fell free to ask if you have any queries.
I hope this helps...Happy coding.

disable submit button according to at least 1/10 checkboxes being checked

The user are of the site I am working on has an email management section.
This displays a list of emails that they have Sent, Inactive, And In process
There are options that allow to select specific emails and send them or make them inactive, or active.
My problem is that if the user has no tick boxes checked, they can click one of these buttons and the jquery / ajax for this button is run, with nothing in.
I would like to stop this from happening and am not sure how to go about it for multiple checkboxes.
I found a solution that did what i want for 1 checkbox, not say, 10 for example. If one is clicked then another, it will disable the button again
<div class='span8' style='padding-bottom:10px;margin-left:0px;'><label class='checkbox'><input title='Select All Sent Emails' type='checkbox' id='selectallsent'>Select All Sent</label> <label class='checkbox'><input title='Select All In Progress Emails' type='checkbox' id='selectallprogress'>Select All In Progress</label><br /><label class='checkbox'><input title='Select All Active Emails' type='checkbox' id='selectallactive'>Select All Active</label> <label class='checkbox'><input title='Select All Inactive Emails' type='checkbox' id='selectallinactive'>Select All In Inactive</label></div>
<div class='span4' style='padding-bottom:10px;text-align:right;margin-right:0px;vertical-align:top;'><br /><br /><input type="button" onclick="inactive()" class="btn btn-small setInactive" value="Set Inactive"> <input type="button" onclick="active()" class="btn btn-small setActive" value="Set Active"> Send / Resend</div></form>
<table id='reviewHistoryTable' class='table table-bordered table-striped'>
<thead>
<tr>
<th align='center' width='2%'></th>
<th align="center" width="10%">
Order Id
</th>
<th align="center" width="20%">
Customer Name
</th>
<th align="center" width="20%">
Customer Email
<th align="center" width="20%" >
Date Send
</th>
<th align='center' width='5%'>
Type
</th>
<th align="center" width="15%" >
Status
</th>
</tr>
</thead>
<tbody>
<?php foreach($histories as $row): ?>
<tr>
<td><input type='checkbox' name='<?=$row->service_feedback_email_id?>' class='<?=$row->email_sent?> <?=$row->status?>'></td>
<td ><?=$row->order_id?></td>
<td ><?=$row->customer_name?> </td>
<td ><?=$row->customer_email;?> </td>
<td><?=$row->date_send;?> </td>
<td><?=(!$row->review_type || $row->review_type=='store')?"Store":"Product"?></td>
<td>
<div id="editEmail_<?=$row->service_feedback_email_id?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="editEmailLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Edit Details</h3>
</div>
<div class="modal-body" style="height:900px;">
<form name="editEmail" id="<?=$row->service_feedback_email_id?>" method="post">
<input type="hidden" value="<?=$row->service_feedback_email_id?>" id="serviceFeedbackEmailId">
<label>Order ID</label><input id="orderId_<?=$row->service_feedback_email_id?>" type="text" value="<?=$row->order_id?>" disabled/>
<label>Customer Name</label><input id="customerName_<?=$row->service_feedback_email_id?>" class="customerName" name="customerName" type="text" value="<?=$row->customer_name?>"/>
<label>Customer Email</label><input id="customerEmail_<?=$row->service_feedback_email_id?>" type="text" value="<?=$row->customer_email?>"/>
<div class="input-prepend input-append">
<input name="from_date" type="text" class='datepicker' value='<?=$row->date_send;?>'>
<span class="add-on"><i class=' icon-calendar'></i></span>
</div><br/>
</form>
</div>
<div class="modal-footer">
<input type="button" onclick="update()" data-dismiss="modal" class="btn btn-small" value="Update">
Close
</div>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<br/>
<div align='center'><?php echo($paging_link);?></div>
<!--<table>
<tr>
<td>
<div id="buttons">
<!-- <form action="<?=site_url()?>admin/csvexport/exportexitclick" method="post" target="_blank">
<input type="hidden" id="query" name="query" value="<?php //echo($query);?>" />
<input type="submit" value="Export CSV" name="export-submit" id="export-submit" class="button fr ">
<!--<a id="exportcsv" class="button fr " href="" target="_blank">Export CSV</a>
</form>
</div>
</td>
</tr>
</table>-->
<?php
}
?>
<div id="send_emails" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="sendEmailLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Send Emails</h3>
</div>
<div class="modal-body" style="height:40px;">
</div>
<div class="modal-footer">
<input type="button" onclick="send()" data-dismiss="modal" class="btn btn-small" value="Send New Emails Only">
<input type="button" onclick="resend()" data-dismiss="modal" class="btn btn-small" value="Resend Old Emails Only">
<input type="button" onclick="sendall()" data-dismiss="modal" class="btn btn-small" value="Send / Resend All Selected Emails">
Close
</div>
</div>
</div>
<script>
$('span[data-toggle="tooltip"]').tooltip({
trigger: "hover",
placement: "right"
});
var selected = new Array();
function sendResend() {
var selected = Array();
var selectedSend = $(".no:checked").length;
var selectedResend = $(".yes:checked").length;
var totalSendResend = selectedSend + selectedResend;
$('input:checked').each(function () {
selected.push($(this).attr('name'));
});
if (totalSendResend < 1) {
$("#send_emails .modal-body").html('You have selected no emails. Please select some emails before proceeding.');
$("#send_emails .modal-body").css({
"height": "20px"
});
} else {
$("#send_emails .modal-body").html('You have selected ' + totalSendResend + ' emails. ' + selectedSend + ' New emails will be sent & ' + selectedResend + ' will be resent. Please confirm that you want to proceed?');
}
}
function send() {
ajaxEmailQuery($(".no:checked"));
}
function resend() {
ajaxEmailQuery($(".no:checked"));
}
function sendall() {
ajaxEmailQuery($(".yes:checked"));
}
function ajaxEmailQuery(data) {
var selected = Array();
data.each(function () {
selected.push($(this).attr('name'));
});
$.ajax({
url: "/b2b/ajaxEmailQuery",
type: "POST",
data: {
data: selected
},
success: function (data) {
alert(data);
loadFeedbackServiceHistory(1)
}
})
}
function inactive() {
var selected = Array();
$('input:checked').each(function () {
selected.push($(this).attr('name'));
});
var answer = confirm('Are you sure you want to set these emails as inactive?');
if (answer) {
$.ajax({
url: "/b2b/inactive",
type: "POST",
data: {
data: selected
},
success: function (data) {
alert(data);
loadFeedbackServiceHistory(1)
}
})
}
}
function active() {
var selected = Array();
$('input:checked').each(function () {
selected.push($(this).attr('name'));
});
var disabled = $(".setActive");
if(selected>0){
$disabled.removeProp("disabled");
}
var answer = confirm('Are you sure you want to set these emails as active?');
if (answer) {
$.ajax({
url: "/b2b/active",
type: "POST",
data: {
data: selected
},
success: function (data) {
alert(data);
loadFeedbackServiceHistory(1)
}
})
}
}
$(function () {
// add multiple select / deselect functionality
$("#selectallsent").click(function () {
$('.yes').prop('checked', this.checked);
});
$("#selectallprogress").click(function () {
$('.no').prop('checked', this.checked);
});
$("#selectallactive").click(function () {
$('.active').prop('checked', this.checked);
});
$("#selectallinactive").click(function () {
$('.inactive').prop('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".yes").click(function () {
if ($(".yes").length == $(".yes:checked").length) {
$("#selectallsent").prop("checked", "checked");
} else {
$("#selectallsent").removeAttr("checked");
}
});
$(".no").click(function () {
if ($(".no").length == $(".no:checked").length) {
$("#selectallprogress").prop("checked", "checked");
} else {
$("#selectallprogress").removeAttr("checked");
}
});
$(".active").click(function () {
if ($(".active").length == $(".active:checked").length) {
$("#selectallactive").prop("checked", "checked");
} else {
$("#selectallactive").removeAttr("checked");
}
});
$(".inactive").click(function () {
if ($(".inactive").length == $(".inactive:checked").length) {
$("#selectallinactive").prop("checked", "checked");
} else {
$("#selectallinactive").removeAttr("checked");
}
});
});
function update() {
var id = $("#serviceFeedbackEmailId").val();
var customerName = $("#customerName" + "_" + id).val();
var customerEmail = $("#customerEmail" + "_" + id).val();
var answer = confirm('Are you sure you want to update this email? Changes can not be reverted.');
if (answer) {
$.ajax({
type: "POST",
url: "/b2b/update",
data: {
id: id,
customerName: customerName,
customerEmail: customerEmail
},
success: function (data) {
alert(data);
loadFeedbackServiceHistory(1)
}
});
}
}
</script>
<!-- dashboard-content -->
Assign each email input a class such as emailInput. This can be used to loop through all of the checkbox inputs using the JQuery .each() method.
You can use a return to break out of a .each() loop early. Reference
Example
$('#SendEmailsBtn' ).click(function () {
//Loop through checkbox inputs
$('.emailInput').each(function ( index, domEle) {
// domEle == this
//Check if input is checked
if ($(domEle).is(":checked"))
{
SubmitFunction();
return; //At least one input is checked exit loop
}
});
});
You can add a click listener to each checkbox and when a box is clicked the "submit" button is enabled!
Maybe not what you are looking for but it does the job!
An other option is to use a loop that goes over all the checkboxes. As soon as you encounter the first box that is checked you can stop the loop and continue processing the data.
edit:
Pseudo code:
for each (checkbox)
{
var checked = checkbox.checked();
if (checked)
{
submit();
exit();
}
}
If at least one checkbox is checked, call the submit function, else do nothing.
$("#SendEmailBtn").click(function(){
if ($("input:checked").length != 0)
submit();
}

jQuery $this clicked element

I have the following script that sends an image URL to an input field on click (from a modal window). I am also sending that same url, imgurl to a <div class="preview-image> to show it on insertion.
var BusiPress_Configuration = {
init : function() {
this.files();
},
files : function() {
if ( $( '.busipress_upload_image_button' ).length > 0 ) {
window.formfield = '';
$('.busipress_upload_image_button').on('click', function(e) {
e.preventDefault();
window.formfield = $(this).parent().prev();
window.tbframe_interval = setInterval(function() {
jQuery('#TB_iframeContent').contents().find('.savesend .button').val(busipress_vars.use_this_file).end().find('#insert-gallery, .wp-post-thumbnail').hide();
}, 2000);
if (busipress_vars.post_id != null ) {
var post_id = 'post_id=' + busipress_vars.post_id + '&';
}
tb_show(busipress_vars.add_new_file, 'media-upload.php?' + post_id +'TB_iframe=true');
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function (html) {
if (window.formfield) {
imgurl = $('a', '<div>' + html + '</div>').attr('href');
window.formfield.val(imgurl);
window.clearInterval(window.tbframe_interval);
tb_remove();
$('.preview-image img').attr('src',imgurl);
} else {
window.original_send_to_editor(html);
}
window.formfield = '';
window.imagefield = false;
}
}
}
}
BusiPress_Configuration.init();
Sending the image URL to the editor and the div are working fine, but it is doing it for every instance of that div on the page. I've been playing around with $(this) and closest() to see if I could localize the insertion to the specific div near the input, but haven't had any luck. Any help would be greatly appreciated. Thanks!
Default markup
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row">Default Map Icon</th>
<td>
<input type="text" class="-text busipress_upload_field" id=
"busipress_settings_map[default_map_icon]" name=
"busipress_settings_map[default_map_icon]" value=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/red-dot.png" /><span> <input type="button"
class="busipress_upload_image_button button-secondary" value=
"Upload File" /></span> <label for=
"busipress_settings_map[default_map_icon]">Choose the default map icon (if
individual business type icon is not set</label>
<div class="preview-image" style="padding-top:10px;"><img src=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/red-dot.png" /></div>
</td>
</tr>
<tr valign="top">
<th scope="row">Active Map Icon</th>
<td>
<input type="text" class="-text busipress_upload_field" id=
"busipress_settings_map[active_map_icon]" name=
"busipress_settings_map[active_map_icon]" value=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/blue-dot.png" /><span> <input type="button"
class="busipress_upload_image_button button-secondary" value=
"Upload File" /></span> <label for=
"busipress_settings_map[active_map_icon]">Choose the active map icon (if
individual business type icon is not set</label>
<div class="preview-image" style="padding-top:10px;"><img src=
"http://localhost/jhtwp/wp-content/plugins/busipress/img/blue-dot.png" /></div>
</td>
</tr>
</tbody>
</table>
Assuming you can select the button already (I changed it to "button-selector" for the meantime), use parent to get the parent td then find the child div to be changed. This will get the nearest div to your button.
$("button-selector").parent('td').find("div")

How Could i rearrange textboxes which are named as array index

i am working on a project in which i have to render rows dynamically . but user could also delete that row have a look at my current working
JQuery
var counter = 1;
function addrow() {
var textbox = "<div id='rows" + counter + "'> </br><label> Option : </label><input type='text' name='Answers[" + counter + "]' class='ahsan required' />Remove</div>";
var form = $("#form").valid();
if (form) {
$("#TextBoxesGroup").append(textbox);
counter++;
}
else {
return false;
}
}
html
<div id="TextBoxesGroup" style="margin-left: 100px;">
<div id="rows0">
</br><label>
Option :
</label>
<input type='text' name='Answers[0]' class='ahsan required' />Remove
</div>
</div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' /></div>
Now , if i have 10 rows there names will be Answers[0,1,2,3,4,5] . I want to remove input when i click on remove anchor and also reoder all textbox's name
For Example if i remove input at 4th index then all textbox automatically get re arranged . Can i Do it Please Help me and Thanks in Advance
You can make it without counter. This way your answers will be always ordered in the array starting by zero.
Here's a plausible solution:
$(function(){
$("#form").validate();
this.addrow = function() {
if ($("#form").valid()) {
var textbox = "<div> </br><label> Option : </label><input type='text' name='Answers["+$("#TextBoxesGroup div").length+"]' class='ahsan required' /><a class='remove-me' href='#'>Remove</a></div>";
$("#TextBoxesGroup").append(textbox);
$('.remove-me').click(function(){
$(this).parent().remove();
return false;
});
}
else {
return false;
}
}
this.addrow();
});
and the html is simple like this:
<form id="form">
<div id="TextBoxesGroup" style="margin-left: 100px;"></div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' />
</div>
</form>

Categories