I'm working ona fullcalendar project.
I have these 2 checkboxes (Ore Personali e Assenze), when they are checked they should hide the events but at the moment they are not doing it.
This is my input checkbox:
<input type="checkbox" id="OP" name="calendario" value="OP">
And this is the function i've build so far:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var checkBox = document.getElementById("OP");
var x = document.getElementsByClassName("fc-event-container");
if (checkBox.checked === true){
x.style.visibility = "visible !important";
}else{
x.style.visibility = "hidden !important";
}
})
})
I build it by looking on the internet cause i'm new to JS and dont know much, just basic stuff.
And it's giving error in the x.style part (telling me is undefined).
Can someone explain to me how i should do it, cause on internet i only found this way and some other who's just giving me errors anyway.
thanks in advances whos gonna help me (or at least try)
i did as #Cypherjac suggest and it worked.
But now it just hide the events on the current month, when i change months i have to checked and unchecked to hide. Even if i go back to the month i hid the events they are visible
Is there a way to let them stay hide even if i change month?
Before i update the code i will specify that this is not my code, my fullcalendar is from a template i found on internet, i add the function i needed but most of th stuff was already there:
calendar.js code:
key: 'handleFullcalendar',
value: function handleFullcalendar() {
var myOptions = {
header: {
left: 'today',
center: 'prev,title,next',
right: 'none',
},
buttonText:{
today: 'Oggi',
month: 'Mese',
week: 'Settimana',
day: 'Giorno'
},
locale:'it',
allDaySlot: false,
selectable: true,
selectHelper: true,
timeFormat: 'H(:mm)',
editable: true,
eventLimit: true,
resourceAreaHeaderContent: 'Calendari',
resources: [
{
id: 'a',
title: 'Ore Personali'
},
{
id: 'b',
title: 'Assenze'
}
],
windowResize: function windowResize(view) {
var width = $(window).outerWidth();
var options = Object.assign({}, myOptions);
options.events = view.calendar.clientEvents();
options.aspectRatio = width < 667 ? 0.5 : 1.35;
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar(options);
},
//_______apre modal per aggiungere nuovo evento
select: function select(event) {
$('#addNewEvent').modal('show');
$('#calendar').fullCalendar('refetchEvents',event._id)
},
//_______________ELIMINARE EVENTO TRAMITE X
eventRender: function(event, element, view) {
if (view.name == 'listDay') {
element.find(".fc-list-item-time").append("<span class='closeon'>X</span>");
} else {
element.find(".fc-content").prepend("<span class='closeon'>X</span>");
}
element.find(".closeon").on('click', function() {
var deleteMsg = confirm("Vuoi davvero eliminare " + event.title + "?");
if (deleteMsg == true) {
$.ajax({
url: 'eventi/deleteEvent.php',
type: 'POST',
data: {_id: event.idAssenza, nomeUtente: event.nomeUtente},
success: function(html){
location.reload();
}
})
$('#calendar').fullCalendar('removeEvents',event._id);
}else{
location.reload();
}
})
},
//triggherà apertura modal di #editEvent
eventClick: function eventClick(event) {
var color = event.backgroundColor ? event.backgroundColor : (0, _Config.colors)('blue', 600);
$('#editEname').val(event.title);
$('event.id').val(event.idAssenza);
$('nomeUtente').val(event.nomeUtente);
$('#editStarts').val(event.start.toISOString());
$('#editEnds').val(event.end.toISOString());
$('#editNewEvent').modal('show').one('hidden.bs.modal', function (e) {
event.title = $('#editEname').val();
event.start = $('#editStarts').val();
event.end = $('#editEnds').val();
$.ajax({
url: 'eventi/updateEvent.php',
type: 'POST',
data: {start: event.start, _id: event.idAssenza, end: event.end, title: event.title, },
success: function(html){
location.reload();
}
});
$('#calendar').fullCalendar('updateEvent', event._id);
});
},
events: {
url: 'eventi/load.php',
method:'POST'
//color: <- fare in modo che prenda i colori scelti nel modal
},
droppable: false
};
{
$(function() {
$('#OP').change(function() {
var x = $('.fc-event-container');
// Access the element using jQuery
if($(this).prop('checked')){
x.css({
'visibility': 'visible'
})
}
else {
x.css({
'visibility': 'hidden'
})
}
})
});
},
var _options = void 0;
var myOptionsMobile = Object.assign({}, myOptions);
myOptionsMobile.aspectRatio = 0.5;
_options = $(window).outerWidth() < 667 ? myOptionsMobile : myOptions;
$('#editNewEvent').modal();
$('#calendar').fullCalendar(_options);
}
Calendar.php:
<?php
require_once "config.php";
session_start();
if(!ISSET($_SESSION['nomeUtente'])){
header('location:login/login.php');
}
?>
<!DOCTYPE html>
<html class="no-js css-menubar" locale="it">
<head>
<!-- Meta Tag -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="description" content="bootstrap material admin template">
<meta name="author" content="">
<title> Calendario | E.D. Elettronica Dedicata </title>
</head>
<body>
<div class="page">
<div class="page-aside">
<div class="page-aside-switch">
<i class="icon md-chevron-left" aria-hidden="true"></i>
<i class="icon md-chevron-right" aria-hidden="true"></i>
</div>
<div class="page-aside-inner page-aside-scroll">
<div data-role="container">
<div data-role="content">
<!--LISTA CALENDARI-->
<section class="page-aside-section">
<h5 class="page-aside-title">Lista calendari di <?php echo $_SESSION["nomeUtente"]; ?></h5>
<div class="list-group has-actions">
<div class="list-group-item" data-plugin="editlist">
<div class="list-content">
<input type="checkbox" id="OP" name="calendario" value="OP" checked>
<span class="list-text">Ore Personali</span>
</div>
</div>
<div class="list-group-item" data-plugin="editlist">
<div class="list-content">
<input type="checkbox" id="assenze" name="calendario" value="assenze">
<span class="list-text">Assenze</span>
</div>
<div class="list-editable">
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<div class="page-main">
<div class="calendar-container">
<div id="calendar"></div>
<!--addEvent Dialog -->
<div class="modal fade" id="addNewEvent" aria-hidden="true" aria-labelledby="addNewEvent"
role="dialog" tabindex="-1">
<div class="modal-dialog modal-simple">
<form class="modal-content form-horizontal" action="eventi/addEvent.php" method="post" role="form">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
<h4 class="modal-title">Aggiungi Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
</div>
<div class="modal-body">
<div class="form-group row" id=editColor>
<label class="form-control-label col-md-2">Tipo:</label>
<input list="assenza" name="ename" id="ename" style="margin-left: 15px;" />
<datalist id="assenza">
<option value="Normali">
<option value="Straordinarie">
<option value="Ferie">
<option value="Malattia">
<option value="Permesso">
<option value="Smart Working">
<option value="Altro">
</datalist>
<input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="starts">Inizio:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="starts" name="starts" data-container="#addNewEvent">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="ends">Fine:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="ends" name="ends" data-container="#addNewEvent">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Aggiungi Assenza">
<a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
</div>
</div>
</form>
</div>
</div>
<!-- End AddEvent Dialog -->
<!-- editEvent Dialog -->
<div class="modal fade" id="editNewEvent" aria-hidden="true" aria-labelledby="editNewEvent"
role="dialog" tabindex="-1" data-show="false">
<div class="modal-dialog modal-simple">
<form class="modal-content form-horizontal" action="eventi/deleteEvent.php" method="POST" role="form">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
<h4 class="modal-title">Modifica Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="form-control-label col-md-2" for="editEname">Tipo:</label>
<input list="assenza" name="editEname" id="editEname" style="margin-left: 15px;" />
<datalist id="assenza">
<option value="Normali">
<option value="Straordinarie">
<option value="Ferie">
<option value="Malattia">
<option value="Permesso">
<option value="Smart Working">
<option value="Altro">
</datalist>
<input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editStarts">Inizio:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editStarts" name="editStarts" data-container="#editNewEvent">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editEnds">Fine:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editEnds" name="editEnds"data-container="#editNewEvent">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button class="btn btn-primary" data-dismiss="modal" type="button">Salva modifiche</button>
<a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
</div>
</div>
</form>
</div>
</div>
<!-- End EditEvent Dialog -->
</div>
</div>
</div>
</body>
</html>
This is the template i'm using it, most of the code it's there, i just update the part i'm using and modifing
Since you're already using jQuery, you can use it to access the elements instead of native js
Here $(this).prop('checked') is being used to check the checked property of the checkbox
Then when it changes, change the visibility of the element based on the current state..
NOTE: The checkbox is checked initially because the element to toggle is visible when the document loads
$(function() {
$('input[type="checkbox"]').on('change', function() {
x = $('.fc-event-container')
// Access the element using jQuery
if($(this).prop('checked')){
x.css({
'visibility': 'visible'
})
}
else {
x.css({
'visibility': 'hidden'
})
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fc-event-container">
Toggle the checkbox to toggle me
</div>
<input type="checkbox" id="OP" name="calendario" value="OP" checked>
One thing to note about the calendar is that every time you switch the month, week or day, the events are rendered again..
So that means the events will have their default state which is visible every time you switch through the tabs
So if you want to ensure the element remains hidden you have to access the element only after it has been rendered, because rendering happens sequentially, so you cannot access the element as soon as rendering has started, because by then you can't know when it will render..
So the concept I've introduced is just using the property of the calendar which is dayRender to check when the rendering of the contents is being done, and set a timeout of half a second to return the events back to their initial state..
So that is the concept, you can read through the docs to find an event that will fire after all the rendering of the days is done and then call the function to revert back them to their visible or hidden state
Check the codepen for the working demo
Use onchange event
$(document).ready(function() {
$('#OP').change(function() {
var x = document.getElementsByClassName("fc-event-container");
if (this.checked){
x.style.visibility = "visible !important";
}else{
x.style.visibility = "hidden !important";
}
})
});
Related
I am not really good at the HTML world, and I'm not even sure how to debug this one. Anyway, I have an ASP.NET core App. My issue is in a CSHTML view. It is a timeclock system. User logs time against an existing job.
I have an Index.cshtml that is working. It will verify a JobNumber to make sure it exists in the database. And if the user enters a partial number and hits F3, it pops up a modal window (I'm using Bootstrap 5) to allow them to select from a list.
The problem is, the user wants to add more Job numbers. So, they can clock time against up to five Jobs at once. So, I am creating new fields, and naming them JobNumber2, JobNumber3, etc.
What I want to do is reuse the existing scripts to add the verification and popup functionality to each of the new fields.
I have tried several different things based on a half a dozen tutorials out there, but I am just not good enough at Javascript and JQuery to know how to do this.
Any help is appreciated!
[EDIT]
Ruikai Feng's answer shows how to match the first function, but that one calls validateJobNumber(jobNumber), and the result will update a field -- again based on the same pattern. So, now it updates: jobNumberValidationMessage -- but I need it to update the correct jobNumberValidationMessage depending on which JobNumber field got matched in the first half of this. IDK, maybe these could be combined into one function? I'm not sure. But how do I take what I matched with id^='JobNumber to figure out which jobNumberValidationMessage to update (ie jobNumberValidationMessage2, jobNumberValidationMessage3, etc) ;
------------ END EDIT
Here's the code I have that is working, but needs changed:
#using Microsoft.AspNetCore.Http
#using Microsoft.AspNetCore.Http.Extensions
#model dynamic
<!DOCTYPE html>
<html>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-10">
<!-- Clock-In Header -->
<h3>
<img class="logo large" src="logo-png-transparent.png")"
alt="Logo" width="100" height="100"> Add Job Number(s) to Track Time for: #Model.Employee.Name
</h3>
<hr /> <!-- Ruler Line for Separation -->
<!-- End Clock-In Header -->
<!-- Clock-In Form -->
<div class="row">
<div class="col-1 col-md-12 offset-md-0">
<div class="card">
<div class="card-body">
<form asp-action="ClockInBegin" method="post">
<label for="JobNumber" class="col-7 col-md-2 col-form-label text-md-right">Job Number</label>
<div class="col-md-4">
<input type="text" id="JobNumber" name="JobNumber" class="form-control" onkeydown="jobNumberKeyDown(this)" onblur="jobNumberBlur(this)" value="#Model.TrackingItem.JobNumber">
<div class="col-md-8">
<span id="jobNumberValidationMessage"></span>
</div>
</div>
</div>
<div class="form-group row">
<div class="form-check form-switch col-4 align-with-label">
<input class="form-check-input" type="checkbox" value="" id="MultipleCheck">
<label class="form-check-label" for="MultipleCheck">Multiple</label>
</div>
</div> <!-- End form-group row -->
<div>
<button type="submit" class="btn btn-primary w-100">Start Clock</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Clock-In Modal Pop-up -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select Job Number</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<select id="jobNumberSelect" class="form-control">
<option value="">Select Job Number</option>
<!-- Dynamic options generated via JavaScript or ajax -->
</select>
</div>
<div class="modal-footer">
<button type="button" id="CANCEL"class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" id="OK" class="btn btn-primary" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
<!-- End Clock-In Modal Pop-up -->
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#JobNumber").blur(function () {
var jobNumber = $(this).val();
validateJobNumber(jobNumber);
});
$("#JobNumber").keydown(function (event) {
if (event.key === "F3") {
event.preventDefault();
if (event.target.value.length >= 2) {
// Open the modal
$('#myModal').modal('show');
// Populate the select options
$.ajax({
type: "GET",
url: "#Url.Action("GetJobNumbers")",
data: { searchTerm: event.target.value },
dataType: "json",
success: function (data) {
$("#jobNumberSelect").empty();
$.each(data, function (index, item) {
$("#jobNumberSelect").append("<option value='" + item + "'>" + item + "</option>");
});
$("#jobNumberSelect").val("..."); // clear the initial value. Make them select it
//set prompt in first cell of select
$("#jobNumberSelect").prepend("<option value=''>Select Job Number</option>");
$("#myModal").modal("show");
}
});
}
}
});
$("#jobNumberSelect").change(function () {
$("#JobNumber").val($(this).val());
});
$("#OK").click(function () {
$("#JobNumber").val($("#jobNumberSelect").val());
validateJobNumber(); // call the validation
$("#myModal").modal("hide");
});
$('#MultipleCheck').change(function () {
if (this.checked) {
$(this).val(true);
$('[name="MultipleCheck"]:hidden').val(true);
$("#hiddenFields").show();
}
else {
$(this).val(false);
$("#hiddenFields").hide();
}
})
}); // end Document.Ready functions
function validateJobNumber() {
var jobNumber = $("#JobNumber").val();
$.ajax({
type: "POST",
url: "#Url.Action("VerifyJobNumber")",
data: { jobNumber: jobNumber },
dataType: "text",
success: function (respdata) {
// alert(respdata);
const obj = JSON.parse(respdata);
var rmessage = obj.message;
$("#jobNumberValidationMessage").text(rmessage);
$("#jobNumberValidationMessage").css("color", "green");
}
});
}
</script>
</body>
</html>
if you have mutipule inputs like:
<input type="text" id="JobNumber1" name="JobNumber1" class="form-control" value="1">
<input type="text" id="JobNumber2" name="JobNumber2" class="form-control" value="2">
<input type="text" id="JobNumber3" name="JobNumber3" class="form-control" value="3">
and you want validate the value on blur ,just try as below:
$("[id^='JobNumber']").blur(function(e)
{
var jobnumber=$(this).val();
$.ajax({
type: "POST",
url: "#Url.Action("VerifyJobNumber")",
data: { "jobNumber": jobnumber },
dataType: "text",
success: function (respdata) {
alert(respdata);
}
});
});
With a controller :
[HttpPost]
public IActionResult VerifyJobNumber(string jobNumber)
{
return Ok(jobNumber);
}
The result:
I've got three fields inline and one of them is a inpt field, this is how it look like when they are validated
https://ibb.co/X8c1jDZ
the problem is when I enter some values into the input fiedl then it moves all the other fields as you can see from the image
https://ibb.co/Fn666cw
I believe something is wrong with the way I unhighlight the field once has been filled but not sure, maybe someone can help me. Please let me know if you need more details. many thanks
This is my html code
<div class="row">
<div class="form-group fieldGroup">
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Tipologia proprietario</label>
<select class="form-control bs-select" id="kmg_admin_new_building_owner_type-1" name="kmg_admin_new_building_owner_type[]" data-live-search="true" title="Seleziona tipologia proprietario">
<option value="1">Proprietario</option>
<option value="2">Co-Proprietario</option>
<option value="3">Nudo proprietario</option>
<option value="4">Usufruttuario</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Proprietario</label>
<select class="form-control bs-select" id="kmg_admin_new_building_owner-1" name="kmg_admin_new_building_owner[]" data-live-search="true" title="Seleziona tipologia proprietario">
<option value="1">Proprietario</option>
<option value="2">Co-Proprietario</option>
<option value="3">Nudo proprietario</option>
<option value="4">Usufruttuario</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Se
<span class="required"> * </span>
</label>
<div class="input-group">
<input type="text" class="form-control prova" id="kmg_admin_new_building_owner_quota-1" name="kmg_admin_new_building_owner_quota[]" placeholder="Quota titolare">
<span class="input-group-btn input-group-btn input-space">
<button class="btn btn-default addMore" type="button">Aggiungi proprietario</button>
</span>
<span class="input-group-btn input-group-btn input-space">
<button class="btn btn-default remove" type="button">Rimuovi proprietario</button>
</span>
</div>
</div>
</div>
</div>
</div>
This is my javascript code
form.validate({
// doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
kmg_admin_new_building_increment: {
required: true,
digits: true,
remote: {
type: 'POST',
data: {
ajax_action: 'kmg_new_building_check_increment',
kmg_new_building_increment: function() {
return $( "#kmg_admin_new_building_increment" ).val();
}
}
}
},
kmg_admin_new_building_type: { required: true },
kmg_admin_new_building_palazzina: { required: true },
kmg_admin_new_building_interno: { required: true },
"kmg_admin_new_building_owner_type[]": {required: true},
"kmg_admin_new_building_owner[]": { required: true },
"kmg_admin_new_building_owner_quota[]": {
required: true,
number: true,
min: 0,
max: 100
},
kmg_admin_new_building_metri: {
required: false,
digits: true
}
},
messages: {
kmg_admin_new_building_increment: {
required: "Specifica un ordine di stampa univoco",
digits: "L'ordine di stampa può solo essere un numero",
remote: "Ordine di stampa è già registrato!",
},
kmg_admin_new_building_type: "Specifica la tipologia dell'unità immobiliare",
kmg_admin_new_building_palazzina: "Specifica la palazzina dell'unità immobiliare",
kmg_admin_new_building_interno: "Inserisci il valore d'interno",
"kmg_admin_new_building_owner_type[]": "Seleziona tipologia di proprietario",
"kmg_admin_new_building_owner[]": "Seleziona proprietario",
"kmg_admin_new_building_owner_quota[]": {
required: "Specifica la quota",
number: "solo numeri",
min: "minimo 0",
max: "massimo 100"
},
kmg_admin_new_building_metri: {digits: "Inserisci valore numerico"}
},
errorPlacement: function(error, element) { // render error placement for each input type
if (element.parent(".input-group").length > 0) {
error.insertAfter(element.parent(".input-group"));
} else {
error.appendTo(element.closest('.form-group'));
}
},
invalidHandler: function(event, validator) { //display error alert on form submit
success.hide();
error.show();
App.scrollTo(error, -200);
},
highlight: function(element) { // hightlight error inputs
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) { // revert the change done by hightlight
$(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
},
success: function(label) {
label.addClass('valid').closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
},
This is how i clone the fields
//add more fields group
var fieldGroup = $(".fieldGroup").clone();
// Hide remove button
$(".remove").parent('span').hide();
$(".addMore").click(function(e) {
var fgc = $('body').find('.fieldGroup').length;
var fieldHTML = '<div class="form-group fieldGroup">' + fieldGroup.html() + '</div>';
fieldHTML = fieldHTML.replace('kmg_admin_new_building_owner_type-1', 'kmg_admin_new_building_owner_type-' + (fgc + 1));
fieldHTML = fieldHTML.replace('kmg_admin_new_building_owner-1', 'kmg_admin_new_building_owner-' + (fgc + 1));
fieldHTML = fieldHTML.replace('kmg_admin_new_building_owner_quota-1', 'fkmg_admin_new_building_owner_quota-' + (fgc + 1));
$('body').find('.fieldGroup:last').after(fieldHTML);
var el = $('.fieldGroup').next();
// Hide add new button
el.find('.addMore').parent('span').hide();
// Show remove button
el.find('.remove').parent('span').show();
// Load selectpicker again after cloning the inputs
$('.bs-select').selectpicker({
iconBase: 'fa',
tickIcon: 'fa-check',
dropupAuto: false
});
});
//remove fields group
$("body").on("click", ".remove", function() {
$(this).parents(".fieldGroup").remove();
});
This is not a serious problem, I think, you just have to think of the changes of the layout, and prepare for them in your CSS.
Here's an example of what's happening:
(You can find a short explanation at the bottom of the answer.)
jQuery(document).ready(function($) {
$(".modify").on('click', function(e) {
// $.fn.toggle() switches between display: none and
// display: block
$('#il3').find('label').toggle()
})
})
.inputandlabel {
float: left;
}
input[type="text"],
label {
display: block;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-6">
<button type="button" class="btn btn-primary modify">Just push it to see the problem</button>
</div>
</div>
<div class="row">
<div class="col-12">
<div id="il1" class="inputandlabel">
<label for="form1">Form1</label>
<input id="form1" type="text" />
</div>
<div id="il2" class="inputandlabel">
<label for="form2">Form2</label>
<input id="form2" type="text" />
</div>
<div id="il3" class="inputandlabel">
<label for="form3">Form3</label>
<input id="form3" type="text" />
</div>
<div id="il4" class="inputandlabel">
<label for="form4">Form4</label>
<input id="form4" type="text" />
</div>
<div id="il5" class="inputandlabel">
<label for="form5">Form5</label>
<input id="form5" type="text" />
</div>
<div id="il6" class="inputandlabel">
<label for="form6">Form6</label>
<input id="form6" type="text" />
</div>
</div>
</div>
</div>
And here's a solution:
jQuery(document).ready(function($) {
$(".modify").on('click', function(e) {
e.preventDefault()
if ($('#il3').find('label').css('visibility') !== 'hidden') {
$('#il3').find('label').css('visibility', 'hidden')
} else {
$('#il3').find('label').css('visibility', 'visible')
}
})
})
.inputandlabel {
float: left;
}
input[type="text"],
label {
display: block;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-6">
<button type="button" class="btn btn-primary modify">Just push it to see "nothing"</button>
</div>
</div>
<div class="row">
<div class="col-12">
<div id="il1" class="inputandlabel">
<label for="form1">Form1</label>
<input id="form1" type="text" />
</div>
<div id="il2" class="inputandlabel">
<label for="form2">Form2</label>
<input id="form2" type="text" />
</div>
<div id="il3" class="inputandlabel">
<label for="form3">Form3</label>
<input id="form3" type="text" />
</div>
<div id="il4" class="inputandlabel">
<label for="form4">Form4</label>
<input id="form4" type="text" />
</div>
<div id="il5" class="inputandlabel">
<label for="form5">Form5</label>
<input id="form5" type="text" />
</div>
<div id="il6" class="inputandlabel">
<label for="form6">Form6</label>
<input id="form6" type="text" />
</div>
</div>
</div>
</div>
You can see from the two snippets, that by setting display: none; on the label scrambles the layout. display: none; takes the element out of the flow (not the DOM itself, but from the object flow), while visibility: hidden; just makes the element invisible. Quite a difference, isn't it?
So, setting the display CSS property to none "removes the height" that kept your layout in order - try setting the elements visibility to hidden with JS.
If that's not working, then give the form-group a fixed height (the height with success / error message), and don't change that value on success / error.
I've got a dropdown box which is populated with ajax according to what option i choose from another dropdown. I need to duplicate the dropdown box keeping the same options loaded via ajax, this is what i've done o far. Many thanks for your help
This is the code to get tha value from the first dropbox and then use it for ajax
$('#flatGroup').on('change',function(){
var countryID = $(this).val();
console.log(countryID);
if(countryID){
$.ajax({
type:'POST',
url:'../controllers/ctrl_admin_group_table_app/ctrl_admin_get_building_table.php',
data: {
group_id: countryID
},
success:function(html){
$('#flatTable-1').html(html);
$(".bs-select").selectpicker('refresh');
}
});
}
});
This is the code i'm using to close the second dropbox that receive the option from ajax
// start repeating form tabelle
//Start repeating form group add limit
var maxGroup1 = 5;
//add more fields group
var fieldGroup1= $(".fieldGroup1").clone();
$(".addMore1").click(function() {
var fgc1 = $('body').find('.fieldGroup1').length;
if (fgc1 < maxGroup1) {
var fieldHTML1 = '<div class="form-group fieldGroup1">' + fieldGroup1.html() + '<div class="col-md-1"><label class="control-label"> </label><i class="fa fa-close"></i></div></div>';
fieldHTML1 = fieldHTML1.replace('flatTable-1', 'flatTable-' + (fgc1 + 1));
fieldHTML1 = fieldHTML1.replace('flatMillesimi-1', 'flatMillesimi-' + (fgc1 + 1));
$('body').find('.fieldGroup1:last').after(fieldHTML1);
$('.bs-select').selectpicker({
iconBase: 'fa',
tickIcon: 'fa-check'
});
} else {
swal("Operazione Annullata", "Hai raggiunto il massimo numero di proprietari registrabili", "error");
}
});
//remove fields group
$("body").on("click", ".remove", function() {
$(this).parents(".fieldGroup1").remove();
});
// end repeating form
This is the HTML code
<div class="row">
<div class="col-md-9">
<div class="portlet-body form">
<div class="col-md-9">
<div class="mt-repeater">
<div data-repeater-list="group-b">
<div data-repeater-item class="row">
<div class="form-group fieldGroup1">
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Tabella</label>
<select class="form-control bs-select" id="flatTable-1" name="flatTable[]" title="Seleziona tabella millesimale"></select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">
<i class="fa fa-info-circle red tooltips" data-placement="top" data-original-title="Quota del titolare dell'immobile" ></i>Millessimi<span class="required"> * </span>
</label>
<input type="text" id="flatMillesimi-1" name="flatMillesimi[]" class="form-control" placeholder="Millessimi dell'immobile" >
</div>
</div>
</div> <!-- Fine field group -->
</div>
</div>
<!-- <hr> -->
<a href="javascript:;" data-repeater-create class="btn btn-info mt-repeater-add addMore1">
<i class="fa fa-plus"></i> Aggiungi tabella</a>
<br>
<br>
</div>
</div>
</div>
</div>
</div>
I'm using the X-Editable jquery plugin and i'm going crazy over here.
I can't get the AJAX request to being sent on submit. I have send on always but looking at my network i can't see any requests being sent.
Below is my code
<form class="form-horizontal form-editable">
<div class="row padding-top-20">
<div class="col-md-4">
<div class="form-group">
<label class="col-md-3 control-label text-left" for="client-fname">First Name:</label>
<div class="col-md-9 editable-cont col-no-padding-left">
<?php echo $client['fname'];?>
<span class="editable-span">edit</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label text-left" for="client-lname">Last Name:</label>
<div class="col-md-9 editable-cont col-no-padding-left">
<?php echo $client['lname'];?>
<span class="editable-span">edit</span>
</div>
</div>
</div>
<button type="button" class="btn btn-success submit-editable">Save</button>
<button type="button" class="btn btn-default cancel-editable">Cancel</button>
</form>
<script>
$(function(){
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.send = "always";
$.fn.editable.defaults.url = "/post.php";
$.fn.editable.defaults.ajaxOptions = {type: "POST"};
$('.editable-item').editable({
type: 'text',
emptytext: 'Click to Edit',
showbuttons: false,
toggle: 'manual',
onblur: 'ignore',
success: function(response, newValue) {
alert(response);
}
}).on('click', function (e) {
e.stopPropagation();
e.preventDefault();
$('#editable-buttons-container').show();
$('.editable-item').editable('show');
$('.editable-edit').hide();
});
$('.submit-editable').on('click',function(){
alert('submit mofo');
$('.editable-item').editable().submit();
});
});
</script>
Same issue. Found another way that set defaults and its working:
$.extend($.fn.editable.defaults, {
ajaxOptions: {
type: 'PUT',
dataType: 'script'
}
});
How can i show alert box for validation in login form?
I got below output but i want alert box?
This is my index page: index.jsp
<html:form styleId="validate" action="/account_login" styleClass="account" method="post">
<div class="content controls single_advance">
<!-- <div class="form-row user-change-row">-->
<div class=form-row>
<div class=col-sm-3></div>
<div class=col-sm-4>
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-user></span> </div>
<!--<input type=text class=form-control placeholder="Account Name"/>-->
<html:text property="name" styleClass="validate[required] form-control" styleId="Account_Name"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-key></span> </div>
<!--<input type=password class=form-control placeholder="Password"/>-->
<html:password property="password" styleClass="validate[required] form-control" styleId="Password"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-6 col-md-offset-3">
<input class="btn btn-default btn-block btn-clean btn-success" value="Log In" type="submit">
</div>
</div>
<!--<div class=form-row>
<div class="col-md-12"> Forgot your password? </div>
</div>-->
<div class=form-row>
<div class="col-md-12 tac"><strong>OR USE </strong></div>
</div>
<div class=form-row>
<div class="col-md-12"> <a class="btn btn-primary btn-block imeino"><span class="icon-mobile-phone"></span> IMEI NO LOGIN</a> </div>
</div>
</div>
</html:form>
This is my struts action class: account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
HttpSession http_session = request.getSession(true);
http_session.setAttribute("login_name", acc_name);
ArrayList<String> name_list = new ArrayList<String>();
Query enc_password = session.createQuery("from account_dao");
List list = enc_password.list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
account_dao account = (account_dao) iterator.next();
System.out.println("Id : " + account.getId());
System.out.println("Account Name : " + account.getName());
System.out.println("Account Password : " + account.getPassword());
int i = 0;
name_list.add(i,account.getName());
i++;
}
request.setAttribute("namelist", name_list);
dealer_bean Bean = new dealer_bean();
Bean.setCustomerList(name_list);
System.out.println("List : "+name_list);
return mapping.findForward(SUCCESS);
} else {
fromBean.setError("<span style='color:red'><h6>Login failed.</h6></span>");
return mapping.findForward(FAILURE);
}
How can I show error (or) success message in alert box?
Append after the html:form close tag the next code and try:
<logic:present name="account_bean" property="error">
<div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
// When DOM is ready
$(function() {
$("#errorDialog").dialog({
title: "Login",
autoOpen: false,
resizable: false,
show: "clip",
hide: "clip",
modal: true,
dialogClass: "ui-state-active"
});
});
// When Window is ready
$(window).load(function() {
$("#errorDialog").dialog("open");
});
</script>
<div id="errorDialog">
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
</logic:present>
Simply try using struts logic tags for your purpose. Here i used jQuery ready() function,
<logic:present name="account_bean" property="error">
<script>
$(document).ready(function() {
alert('Login failed.');
});
</script>
</logic:present>
Hope this helps..
I haven't tried it and I am not even sure if this works. It was too long to be written as a comment.
Create a field in your form bean as follows:
public class MyForm{
String isUserValid;
//its getters and setters
}
And then in your account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
//rest of your code
formBean.setIsUserValid("Y")//------------Add this
return mapping.findForward(SUCCESS);
else {
formBean.setIsUserValid("N")//--------And this
return mapping.findForward(FAILURE);
}
In your jsp file add a hidden input and the following script as follows:
<head>
<script type="text/javascript">
$(document).ready(function(){
var isLoggedIn = $("#isUserValid").val();
if(isLoggedIn == "N"){
alert("Log in failed");
}
});
</script>
</head>
<body>
<input type="hidden" id="isUserValid" name="isUserValid" />