how can I clone ajax dropdown - javascript

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>

Related

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

How to print the values in jquery into html text?

I wanted to join the HTML text with the values of the item.certificate_name.
I've tried many things but any of it didn't works.
The line I mean is I commented <!-- I WANTED THE CERTIFICATE NAME TO BE HERE-->. I've already inspected, I've already got the name value. The only problem is how to join the text with the value?
<div class="col-xs-12">
<div class="row">
<div class="col-xs-2">
<i class="glyphicon glyphicon-trash center" style="font-size: 50px"></i>
</div>
<div class="col-xs-8">
<div class="clTulisanHapus center" id="idTulisanHapus">
Anda Yakin ingin menghapus Pelatihan?
<!-- I WANTED THE CERTIFICATE NAME TO BE HERE -->
</div>
</div>
</div>
</div>
<div class="col-md-offset-8">
<div class="btn-group">
<input type="hidden" id="idDataId">
<input type="hidden" id="idDataNama">
<button type="button" id="idBtnHapusBatal" class="btn clBtnMdlHapus">Tidak</button>
<button type="button" id="idBtnHapusHapus" data-id="${item.id}" class="btn clBtnMdlHapus">Ya</button>
</div>
</div>
$('#idBtnHapusHapus').click(function() {
var angka = $('#idDataId').val();
var angka = $('#idDataNama').val();
debugger;
$.ajax({
url: './hapussertifikasi/' + angka,
type: 'DELETE',
success: function(model) {
debugger;
window.location = './sertifikasi'
},
error: function(model) {
debugger;
}
});
});
Use Node.textContent to concatenate the text content of the div with item.certificate_name value and CSS white-space: pre; to wrap text on line breaks:
var item = {
certificate_name: 'Certificate Name'
};
var div = document.getElementById('idTulisanHapus');
div.style.whiteSpace = "pre";
div.textContent += ' ' + item.certificate_name
<div class="clTulisanHapus center" id="idTulisanHapus">
Anda Yakin ingin menghapus Pelatihan?
</div>

Calculating values based on dynamically added fields

I am trying to create a dynamic aggregation based on fields. The only difference is that it's not a table but a div block.
What I am trying to accomplish
On button click add field, the content from the template is cloned ( it's like a table row ), this part is fully working.
The code is supposed to count the values, for each row add some fields. I used keyup function to keep it updated all time.
Why is it not working?
Well I was not able to get it working like such .each of i_row or template contains fields p_cnetto[] p_pvat[] p_ilosc[] ( quantitiy )
Because I can't read row wise - I tried many things but apparently did something bad it only counts curr_net value and it's still not the way it should be.
Decimal values should be acceptable : example 2222.00
How it should work?
Add a row
Summing row part [ not really need to display row aggregation ]:
curr_netto = get this row p_cnetto[] value multiply by p_ilosc[]
curr_brutto = get this row (p_cnetto[] * p_pvat[]) / 100 * p_ilosc[]
At the end it should calculate a grand total of all rows for as total_netto,total_brutto - could be in console.log
Thanks for any tips.
JsFiddle Example
<!-- statistic block --->
<div id="curr_netto"></div>
<div id="curr_brutto"></div>
<button class="btn btn-primary btn-add-panel mt-5" type="button"> <i class="glyphicon glyphicon-plus"></i> Add field</button>
<div class="row">
<div class="col-sm-12" id="extra_group">
<!-- s -->
<div class="widget widget2 card template mb-2 bg-light-blue-50" style="display: none;">
<div class="col-lg-5">
<div class="row i_row">
<div class="form-group col-md-2">
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label>Name</label>
<input type="text" name="p_nazwa[]" class="form-control"></input>
</div>
</div>
<div class="form-group col-md-2">
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label>Qty</label>
<input type="text" name="p_ilosc[]" class="form-control p_ilosc"></input>
</div>
</div>
<div class="form-group col-md-2">
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label>Unit</label>
<select class="form-control" name="p_unit[]">
<option value="Kg">Kilogram</option>
</select>
</div>
</div>
<div class="form-group col-md-2">
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label>Net</label>
<input type="text" name="p_cnetto[]" class="form-control p_cnetto"></input>
</div>
</div>
<div class="form-group col-md-2">
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label>VAT</label>
<input type="text" name="p_pvat[]" class="form-control p_pvat"></input>
</div>
</div>
<div class="form-group col-md-2">
<div class="subtot"></div>
</div>
<div class="form-group col-md-2">
<button class="btn btn-danger btn-add-panel rh mt-5 ml-3"> <i class="glyphicon glyphicon-minus"></i> Del</button>
</div>
</div>
</div>
</div>
<!-- s -->
</div>
</div>
below code will loop through individual block and get the values.
$(document).keyup(function() {
// desired calculation : for curr_netto is [name='p_cnetto[]']" * [name="p_pvat[]"]
// curr_brutto = ([name='p_cnetto[]']" * [name="p_pvat[]"]) / 100 * name="p_ilosc[]"
var cnetto = 0;
var pnetto = 0;
jQuery('#extra_group .template').each(function(){
var resetVar = (Number(jQuery(this).find('.p_cnetto').val()) * Number(jQuery(this).find('.p_pvat').val()));
cnetto = cnetto + resetVar;
pnetto = pnetto + ((resetVar / 100) * Number(jQuery(this).find('.p_cnetto').val()));
});
$("#curr_netto").html("Netto : " + cnetto + " -- " + pnetto)
console.log(cnetto);
});
#Kavvson Empcraft also updated your jsfiddle - you can check the output
Based on the answer, this works for me
$(document).bind("keyup change", function (e) {
var pbrutto = 0;
var wartosc_vat = 0;
var cnetto = 0;
jQuery('#extra_group .template').each(function () {
var qty_field_current = (Number(jQuery(this).find('.p_ilosc').val()));
var vatfield_current = (Number(jQuery(this).find('.p_pvat').val()));
var nettofield_current = (Number(jQuery(this).find('.p_cnetto').val().replace("Zł ", "").replace(",", "")));
cnetto = cnetto + (nettofield_current * qty_field_current);
wartosc_vat = wartosc_vat + (nettofield_current * vatfield_current) / 100;
wartosc_vat = wartosc_vat * qty_field_current;
});
pbrutto = cnetto + wartosc_vat;
$("#curr_brutto").html("Brutto : " + pbrutto + " zł");
$("#curr_netto").html("Netto : " + cnetto + " zł");
$("#curr_vat").html("Vat : " + wartosc_vat + " zł");
});

Uncaught TypeError: Cannot read property 'val' of null jquery

I'm trying to pass form values, check them and then return the response with jquery, everything gets passed correctly, the image gets uploaded and the path gets added to the database, but instead of returning the message on the same page, it redirects to the addmember.php, doesn't even go through the checks - like the javascript file doesn't even exist and it has been bothering me for quite a while... I've tried searching but I didn't find anything relatable to me since the problem lies in the picture/image...
Uncaught TypeError: Cannot read property 'val' of null
addmember.js and the **form
$(document).ready(function() {
$("#submit").click(function() {
var membershipnumber = $("#membershipnumber").val();
var membername = $("#membername").val();
var membersurname = $("#membersurname").val();
var memberdate = $("#memberdate").val();
var memberphonenumber = $("#memberphonenumber").val();
var memberemail = $("#memberemail").val();
var memberpicture = document.getElementById("#memberpicture").val();
if ((membershipnumber == "") || (membername == "") || (membersurname == "") || (memberdate == "") || (memberphonenumber == "")) {
$("#message").html("<div class=\"alert alert-danger alert-dismissable fade in\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Polja označena sa * ne smeju biti prazna.</div>");
} else {
$.ajax({
type: "POST",
url: "addmember.php",
data: {
"membershipnumber": membershipnumber,
"membername": membername,
"membersurname": membersurname,
"memberdate": memberdate,
"memberphonenumber": memberphonenumber,
"memberemail": memberemail,
"memberpicture": memberpicture
},
success: function(html) {
var text = $(html).text();
var response = text.substr(text.length - 4);
$("#message").html(html);
},
error: function() {
},
beforeSend: function() {
$("#message").html("<p class='text-center'><img src='images/ajax-loader.gif'></p>")
}
});
}
return false;
});
});
<form name="createnewmember" id="createnewmember" method="post" action="addmember.php" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<!-- name and surname -->
<label for="membername" class="col-xs-2 control-label">Ime i prezime:<font color="#d9534f">*</font></label>
<div class="col-xs-10">
<div class="form-inline">
<input name="membername" id="membername" type="text" class="form-control" placeholder="Ime" autofocus />
<input name="membersurname" id="membersurname" type="text" class="form-control" placeholder="Prezime" />
</div>
</div>
</div>
<!-- /name and surname -->
<div class="form-group">
<!-- date of birth -->
<label for="memberdate" class="col-xs-2 control-label">Datum rođenja:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberdate" id="memberdate" type="date" class="form-control" value="1990-01-01" />
</div>
</div>
<!-- /date of birth -->
<div class="form-group">
<!-- membership number (scanned with barcode scanner) -->
<label for="membershipnumber" class="col-xs-2 control-label">Članski broj:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="membershipnumber" id="membershipnumber" type="text" class="form-control" placeholder="Članski broj" data-toggle="tooltip" data-placement="right" title="Očitajte bar-kod sa nekorišćene kartice." />
</div>
</div>
<!-- /membmership number -->
<div class="form-group">
<!-- phone number -->
<label for="memberphonenumber" class="col-xs-2 control-label">Broj telefona:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberphonenumber" id="memberphonenumber" type="text" class="form-control" placeholder="Broj telefona" />
</div>
</div>
<!-- /phone number -->
<div class="form-group">
<!-- email -->
<label for="memberemail" class="col-xs-2 control-label">Email adresa:</label>
<div class="col-xs-3">
<input name="memberemail" id="memberemail" type="text" class="form-control" placeholder="Email adresa" />
<div class="checkbox">
<label><input name="memberemailinglist" id="memberemailinglist" type="checkbox" disabled/> Prijavi na mailing listu?</label>
</div>
</div>
</div>
<!-- /email -->
<div class="form-group">
<!-- picture -->
<label for="memberpicture" class="col-xs-2 control-label">Slika:</label>
<div class="col-xs-10">
<label class="btn btn-default" for="memberpicture">
<input id="memberpicture" name="memberpicture" type="file" style="display:none;" onchange="$('#memberpicture-info').html($(this).val());" accept=".jpg,.png,.jpeg" class="form-control" />
<span class="glyphicon glyphicon-camera"></span> Traži...
</label>
<span class="label label-danger" id="memberpicture-info">Nije izabrana ni jedna slika...</span>
</div>
</div>
<!-- /picture -->
<div class="form-group">
<span class="pull-right">Polja označena sa <font color="#d9534f">*</font> su obavezna! &nbsp</span>
<!-- required fields text -->
</div>
<button name="Submit" id="submit" class="btn btn-default pull-right" type="submit">Podnesi</button>
<!-- submit button -->
</form>
<!-- /form -->
addmember.php
<?php
require 'includes/functions.php';
include_once 'config.php';
$membershipnumber = $_POST['membershipnumber'];
$membername = $_POST['membername']." ".$_POST['membersurname'];
$membersurname = $_POST['membersurname'];
$memberdate = $_POST['memberdate'];
$memberphonenumber = $_POST['memberphonenumber'];
$memberemail = $_POST['memberemail'];
$memberpicture_dir = '/images/members';
if(isset($_FILES['memberpicture'])) {
$memberpicture_temp = $_FILES['memberpicture']['tmp_name'];
$ext = pathinfo(basename($_FILES['memberpicture']['name']), PATHINFO_EXTENSION);
$memberpicture = $membershipnumber.".".$ext;
move_uploaded_file($memberpicture_temp , $_SERVER['DOCUMENT_ROOT'] . '/spartangym/images/members/' . $memberpicture);
} else {
$memberpicture = "nopicture.jpg";
}
$regdate = new DateTime();
$memberregdate = $regdate->getTimestamp();
$memberexpires = $memberregdate + 2592000;
if (strlen($memberemail) > 0 && !filter_var($memberemail, FILTER_VALIDATE_EMAIL) == true) {
echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Email adresa nije validna.</div><div id="returnVal" style="display:none;">false</div>';
} else {
$a = new AddMemberForm;
$response = $a->createMember($membershipnumber, $membername, $memberdate, $memberphonenumber, $memberemail, $memberpicture, $memberregdate, $memberexpires);
if ($response == 'true') {
echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Član '. $membername .' je uspešno dodat u bazu.</div><div id="returnVal" style="display:none;">true</div>';
} else {
mySqlErrors($response);
}
};
?>
Your problem is here
var memberpicture = document.getElementById("#memberpicture").val();
Native methods don't have val(), nor should you include the hash.
As val() is a jQuery method, you probably wanted to do
var memberpicture = $("#memberpicture").val();
The native alternative would be
var memberpicture = document.getElementById("memberpicture").value;
Your validation looks fine, but on-click you should use event.preventDefault() to keep the form from submitting and only allow the submission in the event of all fields being valid.
Usage here:
https://api.jquery.com/event.preventdefault/
at first check
before check
var membershipnumber = $("#membershipnumber").val();
after check
var membershipnumber='none object';
if(typeof($('#membershipnumber'))!="undefined")
{
membershipnumber= $('#membershipnumber').val();
}
alert(membershipnumber);

How to get the class property for each HTML component inside a parent div?

Hello to the community.
This is my HTML code, what I want is to get the class property, only those that start with 'col-sm-', and that is inside the parent div, only identifying it by the property 'kyros'
<div id="div_wid_001" class="widget-main">
<div kyros="div_frm_gro_001" class="form-group">
<label id="lbl_001" kyros="lbl_001" class="col-sm-2 control-label no-padding-right">Label 001:</label>
<div class="col-sm-2">
<input id="txt_001" kyros="txt_001" class="form-control bas_com" type="text">
<div class="button-wrapper">
<i class="ace-icon fa fa-pencil-square-o"></i>
<i class="ace-icon fa fa-times"></i>
</div>
</div>
<div id="div_sm_003" class="col-sm-8 frm_com ui-droppable"></div>
</div>
</div>
JS:
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
///
$('div[kyros='+div_parent+']').children('div[class^='+col_sm+']').each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
You should get the following result:
col-sm-2 control-label no-padding-right
col-sm-2
col-sm-8 frm_com ui-droppable
Two changes you need to make:
Use find so you search all descendants, not just children. Not sure why I thought one of your targets was nested inside another, but it isn't; so children is fine if you know they'll be children.
Remove the div restriction from your div[class^=...], because one of the elements you want to find is a label, not a div.
Example:
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
///
$('div[kyros='+div_parent+']')
.children('[class^='+col_sm+']')
.each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
<div id="div_wid_001" class="widget-main">
<div kyros="div_frm_gro_001" class="form-group">
<label id="lbl_001" kyros="lbl_001" class="col-sm-2 control-label no-padding-right">Label 001:</label>
<div class="col-sm-2">
<input id="txt_001" kyros="txt_001" class="form-control bas_com" type="text">
<div class="button-wrapper">
<i class="ace-icon fa fa-pencil-square-o"></i>
<i class="ace-icon fa fa-times"></i>
</div>
</div>
<div id="div_sm_003" class="col-sm-8 frm_com ui-droppable"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But, that's fragile; it requires that the col-sm- be at the beginning of the class attribute. If someone adds a class before it later in development, this will break.
Instead, use a "contains" (*=) as a rough filter and then filter to fine-tune it:
$('div[kyros='+div_parent+']')
.children('[class*='+col_sm+']') // or .find to include descendants
.filter(function() {
// Filter out foo-col-sm-, requiring that col-sm- be at the
// beginning of the string or after a space
return this.className.startsWith(col_sm) || this.className.indexOf(" " + col_sm) != -1;
})
. // ...
Example (I've changed the third match so col-sm- isn't at the beginning of class):
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
///
$('div[kyros='+div_parent+']')
.children('[class*='+col_sm+']')
.filter(function() {
return this.className.startsWith(col_sm) || this.className.indexOf(" " + col_sm) != -1;
})
.each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
<div id="div_wid_001" class="widget-main">
<div kyros="div_frm_gro_001" class="form-group">
<label id="lbl_001" kyros="lbl_001" class="col-sm-2 control-label no-padding-right">Label 001:</label>
<div class="col-sm-2">
<input id="txt_001" kyros="txt_001" class="form-control bas_com" type="text">
<div class="button-wrapper">
<i class="ace-icon fa fa-pencil-square-o"></i>
<i class="ace-icon fa fa-times"></i>
</div>
</div>
<div id="div_sm_003" class="ui-droppable col-sm-8 frm_com"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You aren't getting the first result you expect because you are only looking for div.
$('div[kyros='+div_parent+']').children('div[class^='+col_sm+']').each(function () {
var kyr_class = $(this).attr('class');
console.log(kyr_class);
});
If you change your selector, it will work as expected
.children('*[class^='+col_sm+']')
This solution will work :
var div_parent = 'div_frm_gro_001';
var col_sm = 'col-sm-';
$('div[kyros='+div_parent+']').find('[class^='+col_sm+']').each(function () {
alert($(this).attr('class'));
console.log($(this).attr('class'));
});
Here is solution done : https://jsfiddle.net/txmmboxf/
I've updated it for lebel selection, now it will select any element start with class name.

Categories