Need to restrict clone max10 in mobile device using jquery - javascript

Working on Jquery clone where in large device like desktop and tablet user can clone more but in mobile I have to restrict user to clone 10. Is this possible to restrict user to clone
Here is the jquery code
var i = 1;
$(document).on("click", ".btn_more", function () {
$(".cloned-row:first").clone().insertAfter(".cloned-row:last").attr({
'id': function(_, id) {
return id + i
},
'name': function(_, name) {
return name + i
},
'class': "add_pn_grp"
//'value': ''
}).end().find('[id]').attr({
'id': function(_, id) {
return id + i
}
});
if(i < $('.cloned-row1').length){
$(this).closest(".edu_add_button").removeClass('btn_more edu_add_button').addClass('btn_less btn_less1');
}
i++;
});
$(document).on('click', ".btn_less", function () {
$(this).closest(".cloned-row").remove();
});
Here is the html code
<div id ="phone_div" class="col-xs-12 col-sm-9 col-md-9 col-lg-9 ">
<!--Phone information Help pop up-->
<div class="modal-dialog" role="document" id="phonehint" align="center">
<div class="modal-content">
<div class="modal-header text-center" >
<h4 id="myModalLabel" class="modal-title" style="color:black;">Help - Phone</h4>
</div>
<div class="modal-body" >
<h5 style="color:black;" align="left"> Provide number <br/>Provide your phone number along with the country code.</h5>
</div>
</div>
</div>
<!--Contact information Help pop up Ends-->
<label>Phone</label> <i class="fa fa-question-circle help_icon" onclick="showphonehint()" onmouseout="hidephonehint()"></i>
<div class="em_pho cloned-row">
<select id="sel_phntype" name="sel_phntype" class="sslt_Field">
<option selected='selected' value="">Phone Type</option>
<option value="BUSN">Business</option>
<option value="CAMP">Campus</option>
<option value="CELL" >Cellphone</option>
<option value="CEL2">Cellphone2</option>
<option value="FAX">FAX</option>
<option value="HOME">Home</option>
<option value="OTR">Other</option>
</select>
<span class = "ph-inline">
<input type="text" class="cc_field" placeholder="Country Code" id="txt_CC" maxlength="3" name="txt_CC" />
<input type="text" class="pn_field" placeholder="Phone Number" id="txt_Pno" name="txt_Pno" />
<input type="radio" name="preferred" id="rad_Prf" value="preferred">
<label class="radio-label">Preferred</label>
<!--<button class="btn_more" id="buttonvalue"></button>-->
<input type="button" class="btn_more" id="buttonvalue"/>
</span>
</div>
</div>
I have created variable count I have assigned the count as 10 but how to restrict in mobile I am confused like anything.
Kindly help me
Thanks in advance
Mahadevan

you could prevent execution in those cases, isMobile and size > 9, using a relatively effective one-liner.
edit
as suggested in another post on the topic, you could check for mobile with matchMedia.
$(document).ready(function() {
$(".btn_add").click(function() {
if ( $('.cloned_row').size() > 9 && isMobile() ) return;
// cloning logic
});
});
function isMobile() { return window.matchMedia("only screen and (max-width: 760px)").matches; }

Related

Setting Events for similar fields in HTML using JQuery, and Javascript

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:

Programmatically select2 to select 2 select option sequentially

first I have a form that placed inside a modal, this is the form:
<form id="kt_modal_add_menu_form" class="form" action="{{route('administrator....')}}" method="POST">
#csrf
{{-- begin: scroll --}}
<div class="d-flex flex-column scroll-y me-n7 pe-7" id="kt_modal_add_menu_scroll" data-kt-scroll="true" data-kt-scroll-activate="{default: false, lg: true}" data-kt-scroll-max-height="auto" data-kt-scroll-dependencies="#kt_modal_add_menu_header" data-kt-scroll-wrappers="#kt_modal_add_menu_scroll" data-kt-scroll-offset="300px">
<div class="fv-row mb-7">
<label class="required fw-semibold fs-6 mb-2">Menu Name</label>
<input id="menu-name" type="text" name="menu_name" class="form-control form-control-solid mb-3 mb-lg-0" placeholder="Menu Name" />
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Module Name</label>
<select name="module_name" aria-label="Select the module" data-control="select2" data-placeholder="Select module" class="form-select form-select-solid"
data-dropdown-parent="#kt_modal_add_menu_scroll" id="select-module-name">
<option value="New Module" selected>New Module</option>
#foreach ($allModule as $module)
<option value="{{$module->module_name}}">
<b>{{$module->module_name}}</b>
</option>
#endforeach
</select>
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Parent</label>
<select name="parent_id" aria-label="Select the Parent" data-control="select2" data-placeholder="Select parent" class="form-select form-select-solid"
data-dropdown-parent="#kt_modal_add_menu_scroll" id="select-parent">
<option value=""></option>
</select>
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Routes Name</label>
<input id="route-name" type="text" name="routes_name" class="form-control form-control-solid mb-3 mb-lg-0" placeholder="Routes Name e.g. administrator.menu.menu-list-page" />
</div>
<div class="fv-row mb-7">
<label class="fw-semibold fs-6 mb-2">Routes URL</label>
<input id="route-url" type="text" name="url_routes" class="form-control form-control-solid mb-3 mb-lg-0" placeholder="Routes URL e.g. modules/parent/url_name" />
</div>
</div>
{{-- end: scroll --}}
<div class="text-center pt-15">
<button type="reset" class="btn btn-light me-3" data-kt-users-modal-action="cancel">Discard</button>
<button type="submit" class="btn btn-primary" data-kt-users-modal-action="submit">
<span class="indicator-label">Submit</span>
<span class="indicator-progress">Please wait...
<span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
</button>
</div>
<div class="text-left pt-10">
<p>
note:<br>........
</p>
</div>
</form>
inside the form there is a field id="select-module-name", after this menu selected, it will get from ajax to fill the selection for the next field with:
// after selecting module, show menu with parent_id == module menuID
$("#select-module-name").change(function () {
var moduleName = $(this).val();
const selectParent = document.querySelector('#select-parent');
// empty the select-parent options, then add the default empty select
$('#select-parent').empty();
selectParent.add(new Option('',''));
if(moduleName != null && moduleName != "New Module"){
$.ajax({
type: "GET",
url: "/administrator.......,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
response.forEach(function (parentData) {
var option = new Option(parentData.menu_name, parentData.id);
selectParent.add(option, undefined);
});
}
});
}
});
it works fine when creating a new menu,
but when edit, I want to get the prefilled form.
The only one got problem is the select with id="select-parent", this below is the code event when I click edit on selected menu:
// edit menu button eventListener
$(".edit-menu").click(function () {
var menuID = $(this).data('id');
console.log(menuID);
$.ajax({
type: "GET",
url: "/administrator.......,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
console.log(response);
$("#menu-id").val(response.id);
$("#menu-name").val(response.menu_name);
$("#route-name").val(response.routes_name);
$("#route-url").val(response.url_routes);
$("#select-module-name").val(response.module_name).trigger("change");
if(response.parent_id != 0){
$("#select-parent").val(response.parent.menu_name).trigger("change");
// $('#select-parent').val(menuData.parent_id).trigger("change.select2");
// $("#select-parent").select2('data', {id: menuData.parent.module_name, text: menuData.parent.module_name});
}
n.show();
}
});
});
basically, there is 2 select2, but the second select2 is getting the value after the first got selected.
And the problem is the #select-parent (second select2) wont get selected within the value, data is valid but still the select option wont get selected, happen when edit (prefilled form)
thank you in advance if any solution from anyone
$("#select-parent").val(response.parent.menu_name).trigger("change");
$('#select-parent').val(menuData.parent_id).trigger("change.select2");
$("#select-parent").select2('data', {id: menuData.parent.module_name, text: menuData.parent.module_name});
I have tried this 3 option, and even try using setTimeout,
have been suffered this pain for over than 2 weeks XD

change style through checkbox

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

Show / Hide Elements within the same parent div

I'm having trouble getting a div ('.option-other') within a parent group ('.other-row') to show/hide when the corresponding option of the select element ('.select-toggle') is selected. Right now if "other" is selected from either question set 1 or 2 it will show both of the '.option-other' divs. I tried using .parent() and .closest() as described in this solution, but can't seem to figure out the proper way to utilize it for this use case.
$(".select-toggle").change(function() {
var oth = false;
$(".select-toggle option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
if (oth) $('.option-other').show();
else $('.option-other').hide();
// tried this method as well but still doesnt work
// if (oth) $(this).closest('.other-row').children('.option-other').show();
// else $(this).closest('.other-row').children('.option-other').hide();
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
// you wrote:
// tried this method as well but still doesnt work
// if (oth) $(this).closest('.other-row').children('.option-other').show();
// else $(this).closest('.other-row').children('.option-other').hide();
You're close, but $.children only selects direct children of each .other-row. Since .option-other is inside .col inside .other-row, $.children can't see it. Use $.find instead.
// your original code:
var oth = false;
$(".select-toggle option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
This sets one visibility value for the entire page: if at least one "other" option is selected, anywhere, show all the text inputs. The change event is fired for the <select> that actually changed, so focus your efforts there:
var oth = false;
$(this).children("option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
if (oth) $(this).closest('.other-row').find('.option-other').show();
else $(this).closest('.other-row').find('.option-other').hide();
This works, but it could be cleaner. Showing or hiding an element based on a boolean is a common enough requirement that jQuery has a function for it: $.toggle. You can replace the if/else lines with
$(this).closest('.other-row').find('.option-other').toggle(oth);
Your $.each loop does one thing: set oth if there exists at least one selected <option> with a value of "other". You can get the same logic as a one-liner by using an attribute selector:
var oth = ($(this).find('option:checked[value="other"]').length !== 0);
(I changed :selected to :checked because you're already filtering on option elements, and :selected has a performance penalty.)
The final version:
$(".select-toggle").change(function() {
var oth = ($(this).find('option:checked[value="other"]').length !== 0);
$(this).closest('.other-row').find('.option-other').toggle(oth);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
Vanilla JS version:
document.querySelectorAll('.select-toggle').forEach(el => {
el.addEventListener('change', evt => {
const oth = evt.target.querySelector('option:checked[value="other"]');
evt.target
.closest('.other-row')
.querySelector('.option-other')
.style.display = (oth ? '' : 'none');
});
// trigger change event programmatically
const event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);
});
Here is a solution that is a little clunky but I did it relatively quick. It's kind of a work around for having to know which of your two selectors with the same class had been selected.
Here is a working example using your code.
$(".select-toggle").change(function () {
var oth = false;
$(".select-toggle option:selected").each(function () {
if ($(this).val() == "otherFood") {
oth = true;
$('.option-other-food').show();
} else {
$('.option-other-food').hide();
};
if ($(this).val() == "otherDrink") {
oth = true;
$('.option-other-drink').show();
} else {
$('.option-other-drink').hide();
};
});
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="otherFood">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other-food">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like"/>
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="otherDrink">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other-drink">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like"/>
</div>
</div>
</div>
Cheers!

option in form field hides option in next field

I am trying to get the "10.30am" option to dissapear in the Workshop Time field when "Monday 13th April" is selected in the Workshop date field. Failing that I would be happy if the option just disabled.
<div class="form-group">
<form action="ksmail.php" method="POST">
<div class="form-group">
<div class="row">
<p class="control-label blue">Workshop Date:</p>
<select name="date" class="finput" id="wdate">
<option value="11th_APR">Saturday 11th April</option>
<option value="13th_APR" id="dt">Monday 13th April</option>
<option value="18th_APR">Saturday 18th April</option>
</select>
</div>
</div>
<div class="form-group">
<div class="row">
<p class="control-label blue">Workshop Time:</p>
<select name="time" class="finput" id="wtime">
<option value="9am" id="tn">9am</option>
<option value="10_30am" id="tt">10.30am</option>
</select>
</div>
</div>
<div class="row">
<input type="submit" value="Send" class="btn btn-default">
</div>
</div>
</form>
</div>
javascript
$('#wtime') .show();
$('#wdate').bind('change', function (e) {
if( $('#wdate').val() == "#dt") {
$('#tt').hide();
}
css
#wtime{display: none;}
I have tried many variations of this none of which work. Sorry, I am a jquery newbie/moron. Any help would be greatly appreciated.
if you want to disable the option
$('#wdate').on('change', function (e) {
if( $(this).val() == "13th_APR") {
$("#wtime option[value='10_30am']").attr('disabled','disabled');
}
});
or if you want to remove the option
$('#wdate').on('change', function (e) {
if( $(this).val() == "13th_APR") {
$("#wdate option[value='10_30am']").remove();
}
});
Hope this helps
Your condition seem wrong. Try this one, hope this helped :
$('#wtime').show();
$('#wdate').on('change', function (e) {
if( $(this).val() == "13th_APR") {
$('#tt').hide();
}
else
{
$('#tt').show();
}
});

Categories