DIfferent URL has to be passed for same ajax call - javascript

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.

Related

Add and edit form in one page

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

Form getting submitted even after using preventDefault

I am submitting a form in ajax. I used certain validation for input format like time and phone no validation etc. But it submits the form after validation. I did use preventDefault() to prevent form submission but it doesn't work.
$("#sche_inter_form").submit(function(e) {
if ($("#inter_name").val() === "") {
$("#inter_name").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
if (($("#inter_date").val() === "") || (!(/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/).test($("#inter_date").val()))) {
$("#inter_date").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
if (($("#inter_hr").val() === "") || (!(/^((0?[1-9])|(1[0-2]))(:|\s)([0-5][0-9])$/).test($("#inter_hr").val()))) {
$("#inter_hr").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
if ($("#inter_mr").val() === "") {
$("#inter_mr").css({
"border-bottom": " 1px solid #dd4b39"
});
e.preventDefault();
}
e.preventDefault();
var candidate_id = $('#candidate_id').val();
var profile_id = $('#profile_id').val();
var date, time, inter_name, meridian, dataString;
var inter_name = $('#inter_name').val();
var date = $('#inter_date').val();
var time = $('#inter_hr').val();
var meridian = $('#inter_mr').val();
var dataString = 'inter_name=' + inter_name + '&inter_date=' + date + '&inter_time=' + time + '&inter_meridian=' + meridian + '&candidate_id=' + candidate_id + '&profile_id=' + profile_id;
$.ajax({
type: "POST",
url: "/schedule_interview",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: dataString,
cache: false,
success: function(data) {
alert("Interview Scheduled Successfully");
}
});
});
This is my form
<form id = "sche_inter_form">
<div class = "form-group">
<input type = "text" id = "inter_name" placeholder = "Name of interviewer" required></input>
</div>
<div class = "form-group">
<b><p id = "schedule_text">Interview Schedule session</p></b>
</div>
<input type="hidden" id="candidate_id"/>
<input type="hidden" id="profile_id"/>
<div class = "form-group form-inline">
<input type = "text" id = "inter_date" placeholder = "dd/mm/yyyy" required></input>
<input type = "text" id = "inter_hr" placeholder = "hh:mm" required></input>
<input type = "text" id = "inter_mr" placeholder = "AM/PM" required></input>
</div>
<div class = "form-group">
<input type = "submit" class ="btn btn-primary" value = "Schedule"></input>
</div>
</form>
You have to prevent default behavior of submit button.
Try with below code
$("#sche_inter_form").submit(function(e){
replace with
$(".btn-primary").click(function(e){
You can add 'id' attribute to your submit button and use in above code instead of 'class'.
inputs don't need closing tag. Remove </input> from your html and use e.preventDefault(); only once. If you want to prevent form submit in some condition use return false
$("#sche_inter_form").submit(function(e) {
e.preventDefault();
if ($("#inter_name").val() === "") {
$("#inter_name").css({
"border-bottom": " 1px solid #dd4b39"
});
}
if (($("#inter_date").val() === "") || (!(/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/).test($("#inter_date").val()))) {
$("#inter_date").css({
"border-bottom": " 1px solid #dd4b39"
});
}
if (($("#inter_hr").val() === "") || (!(/^((0?[1-9])|(1[0-2]))(:|\s)([0-5][0-9])$/).test($("#inter_hr").val()))) {
$("#inter_hr").css({
"border-bottom": " 1px solid #dd4b39"
});
}
if ($("#inter_mr").val() === "") {
$("#inter_mr").css({
"border-bottom": " 1px solid #dd4b39"
});
}
var candidate_id = $('#candidate_id').val();
var profile_id = $('#profile_id').val();
var date, time, inter_name, meridian, dataString;
var inter_name = $('#inter_name').val();
var date = $('#inter_date').val();
var time = $('#inter_hr').val();
var meridian = $('#inter_mr').val();
var dataString = 'inter_name=' + inter_name + '&inter_date=' + date + '&inter_time=' + time + '&inter_meridian=' + meridian + '&candidate_id=' + candidate_id + '&profile_id=' + profile_id;
$.ajax({
type: "POST",
url: "/schedule_interview",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: dataString,
cache: false,
success: function(data) {
alert("Interview Scheduled Successfully");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="sche_inter_form">
<div class="form-group">
<input type="text" id="inter_name" placeholder="Name of interviewer" required>
</div>
<div class="form-group">
<b><p id = "schedule_text">Interview Schedule session</p></b>
</div>
<input type="hidden" id="candidate_id" />
<input type="hidden" id="profile_id" />
<div class="form-group form-inline">
<input type="text" id="inter_date" placeholder="dd/mm/yyyy" required>
<input type="text" id="inter_hr" placeholder="hh:mm" required>
<input type="text" id="inter_mr" placeholder="AM/PM" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Schedule">
</div>
</form>

Remove <LI> from <UL> on click using jQuery

I would like to remove my list result when I search second element from search box.
I have tried some jquery code but I assume its not working because I am using it on wrong place or wrong content.
Any suggestion will be highly appreciated.
Here is the my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Kunde</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script src="autocomplete/jquery.easy-autocomplete.min.js"></script>
<link href="autocomplete/easy-autocomplete.min.css" rel="stylesheet" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="custom.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="jumbotron">
<div class="col-lg-4">
<input type="text" id="KUNDE" size="50" placeholder="Search by name." />
</div>
<div class="col-lg-2">
<input class="btn btn-default" id="buton" type="submit" value="search" onclick="find();" />
</div>
</div>
<ul id="list"></ul>
<div class="footer"><p> © Copyright 2016</p> <strong>RackPeople</strong>.</div>
</div>
<script>
$(function () {
$("#KUNDE").focus();
});
$(document).keypress(function (e) {
if (e.which == 13) {
$("#buton").click();
}
});
//$('#button').on('click', function () {
// $(root).empty();
//});
//$("li:eq(3)", $(root)).remove();
//$('ul').eq(1).toggleClass('hidden');
//$('#ul').empty();
//$("#buton").click(function () {
// $("#list").remove();
//});
//$('#buton').on('click', '.itemDelete', function () {
// $(this).closest('li').remove();
//});
var uri = 'json.json';
function find() {
var info = $('#KUNDE').val();
$.getJSON(uri)
.done(function (data) {
var item = data.filter(function (obj) {
return obj.name === info || obj.ID === info;
})[0];
if (typeof item !== 'undefined' || item !== null) {
$("ul").append("<li>" + 'ID = ' + item.ID, 'Name = ' + item.name, "<br />" + 'Phone = ' + item.phone, "<br />" + 'Contact = ' + item.contact, "<br />" + 'BalanceLCY = ' + item.balanceLCY, "<br />" + 'CreditLimitLCY = ' + item.creditLimitLCY, "</li>")
}
})
.fail(function (jqXHR, textStatus, err) {
$('#RESULTS').text('Error: ' + err);
});
}
var options = {
url: "json.json",
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options);
</script>
</body>
</html>
you have
<input class="btn btn-default" id="buton" type="submit" value="search" onclick="find();" />
try
<button type="button" id="buton">Click me</button>
and
$("#buton").click(function () {
$("#list").remove();
//do more stuff
});

Javascript to jquery conversion

I'm trying to convert this javascript DOM into jquery, and my code isn't running for some reason. This is the DOM I am using.
document.getElementById("forma").onsubmit = function () {
var ime = document.getElementById("ime").value;
var priimek = document.getElementById("priimek").value;
var stranka = document.getElementById("stranka").value;
try {
var kandidat = Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
document.getElementById("seznam").innerHTML = OblikujIzpis(PridobiPolje());
document.getElementById("obvestila").innerHTML = "Uspešen Vnos!";
document.getElementById("obvestila").className = "bg-success";
}
catch (napaka) {
document.getElementById("obvestila").innerHTML = napaka.message;
document.getElementById("obvestila").className = "bg-danger";
}
document.getElementById("forma").reset();
}
document.getElementById("forma_isci").onsubmit = function () {
var iskani_niz = document.getElementById("iskalniNiz").value;
document.getElementById("seznam").innerHTML = OblikujIzpis(Isci(iskani_niz));
document.getElementById("obvestila").innerHTML = "Rezultat iskanja po iskalnem nizu " + iskani_niz;
document.getElementById("obvestila").className = "bg-info";
}
document.getElementById("pobrisi").onclick = function () {
IzbrisiPolje();
document.getElementById("obvestila").innerHTML = "Polje je bilo izbrisano!";
document.getElementById("obvestila").className = "bg-success";
document.getElementById("seznam").innerHTML = "";
document.getElementById("forma").reset();
}
This is what I tried writing in jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("forma").submit(function(){
var ime=$("ime").val();
var priimek=$("priimek").val();
var stranka=$("stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("seznam").html(OblikujIzpis(PridobiPolje());
$("obvestila").html("Uspešen Vnos!");
$("obvestila").addClass("bg-success");
}
catch(napaka){
$("obvestila").html(napaka.message);
$("obvestila").addClass("bg-danger");
}
$("forma").reset();
$("forma_isci").submit=function(){
var iskani_niz=$("iskaniNiz").val();
$("seznam").html(OblikujIzpis(iskani_niz));
$("obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("obvestila").addClass("bg-info");
}
$("pobrisi".click=function(){
IzbrisiPolje();
$("obvestila").html("Polje je bilo izbrisano!");
$("obvestila").addClass("bg-success");
$("seznam").html("");
$("forma").reset();
}
}
});
});
</script>
here is my HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="funkcije.js"></script>
<script src="dom.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>JavaScript - DOM</title>
</head>
<body>
<div class="container">
<h1>Seznam predsedniških kandidatov!</h1>
<form action="#" id="forma_isci" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="iskalniNiz" placeholder="Iskalni niz">
</div>
<button type="submit" class="btn btn-info">Išči</button>
</form>
<br />
<br />
<h3>Vnos novih kandidatov</h3>
<form action="#" id="forma" class="form-group">
<table class="table">
<tr>
<td>Ime:</td>
<td>
<input type="text" id="ime" placeholder="Ime kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Priimek:</td>
<td>
<input type="text" id="priimek" placeholder="Priimek kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Stranka:</td>
<td>
<select id="stranka" class="form-control" >
<option>Demokratska</option>
<option>Republikanska</option>
<option>Neodvisna</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Dodaj" class="btn btn-info" />
</td>
<td>
<input type="reset" value="Ponastavi" class="btn btn-info" />
</td>
</tr>
</table>
</form>
<br />
<br />
<p id="obvestila"></p>
<br />
<br />
<h3>Seznam obstoječih kandidatov</h3>
<ul id="seznam" class="list"></ul>
<button class="btn" id="pobrisi">Pobriši seznam</button>
</div>
</body>
</html>
So anyway, I'm not going to post the functions here since they're not needed to be seen here.
The javascript code works, the site works then and the elements get added normally. But I would like to have the same effect but written in Jquery. I think some of the issues are in .className, which I replaced with .Addclass from jquery and .innerHTML where I write .html(function). If someone could convert this for me it would be great, since I am kinda new to jquery I'm having some issues.
update n1*
changed the Jquery to this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$(document).ready(function(){
$("#forma").submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").myClass("bg-success");
}
catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").myClass("bg-danger");
}
$("#forma").reset();
}
$("#forma_isci").submit=function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").myClass("bg-info");
}
$("#pobrisi".click=function(){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").myClass("bg-success");
$("#seznam").html("");
$("#forma").reset();
}
}
});
});
</script>
Added the # where there's an ID, and changed .addClass to .myClass. Add function is still not working. But some other functions are working.
The functions.
var polje = [];
function Kandidat(ime, priimek, stranka) {
if (ime ==="" || priimek === "") {
throw new Error("Podatki niso popolni!");
}
else {
var id = polje.length + 1;
var oseba = {id:id, ime:ime, priimek:priimek, stranka:stranka};
oseba.Izpis = function () {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka;
}
return oseba;
}
}
function DodajKandidataNaPolje(kandidat) {
polje.push(kandidat);
return true;
}
function PridobiPolje() {
return polje;
}
function OblikujIzpis(polje) {
var izpis = "";
for (var i = 0; i < polje.length; i++) {
izpis = izpis + "<li>" + polje[i].Izpis() + "</li>";
}
return izpis;
}
function Isci(iskalniNiz) {
var rezultat = [];
var oseba;
var vsebuje;
for (var i = 0; i < polje.length; i++) {
oseba = polje[i];
vsebuje = oseba.ime.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.priimek.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.stranka.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
}
}
}
return rezultat;
}
function IzbrisiPolje() {
polje = [];
return true;
}
in jQuery, in order to access an element, you need to use a selector. In your case, the form has an id of forma (which in jQuery selectors, you prefix it with #). In order to access your form, you need to do the following:
change this:
$("forma").submit(function(){
to this:
$("#forma").submit(function(){
Anywhere else you use jQuery to access an element in your code would have to be changed as well. use #myid for ids, .myclass for classes. See this for more information.
Here is your code (jQuery section only) with some things fixed:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var forma = $('#forma');
forma.submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").addClass("bg-success");
} catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").addClass("bg-danger");
}
forma[0].reset();
});
$("#forma_isci").submit(function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").addClass("bg-info");
});
$("#pobrisi").click(function( ){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").addClass("bg-success");
$("#seznam").html("");
forma[0].reset();
});
});
</script>

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();
}

Categories