I have a problem.
here is my php & HTML:
<?php
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$sub_lapangan."',1,$row->IDLapangan);");
}
?>
<HTML><BODY>
<div class="row">
<div class="form-group" id="sub_lapangan">
<div class="col-lg-3"><label>Nama Sub-Lapangan :</label></div>
<div class="col-lg-2">
<input type="text" name="sub_lapangan" class="form-control" required>
</div>
<div class="col-lg-1">
<a onclick="tambahSubBaru()" class ="btn btn-info"> <i class="fa fa-plus"></i></a>
</div>
</div>
</div>
<div id="sembunyisub">
</div>
</BODY></HTML>
Here is my script:
var count = 0;
function tambahSubBaru() {
count += 1;
if (count > 15) {
alert("Maksimal Untuk Tambah Sub Lapangan adalah 15 Sub Lapangan");
}
else {
$('#sembunyisub').append(
'<div class="row" id="barisbarusub' + count + '">'
+ '<div class="form-group">'
+ '<div class="col-lg-3">'
+ '</div>'
+ '<div class="col-lg-2">'
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan" required>'
+ '</div>'
+ '<div class="col-lg-1">'
+ '<a class ="btn btn-warning" onclick="hapusSub(' + count + ')"> <i class="fa fa-trash"></i></a>'
+ '</div>'
+ '</div>'
+ '</div>'
);
}
}
function hapusSub(row) {
$('#barisbarusub' + row).remove();
}
Here is the pic:
So the scenario is, when i click the "plus" button, it will show up the second textbox. I want to insert them into database. but when i try to insert, the SECOND textbox is succedded to insert in database. but the FIRST textbox doesn't insert to database.
How can i insert the FIRST textbox?
to show up the second textbox, i use .append in javascript.
help me please. I aprreciated the answer. many thank you. :)
You have to loop through your fields in PHP. Therefore you have to create an Array-input-element with [] after the name.
HTML:
<input type="text" name="sub_lapangan[]" class="form-control" required> <!-- Add [] to your field name for creating an Array-->
JS:
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan[]" required>' //The same in you dynamic input field
PHP: Loop through you fields (Array)
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$fields = $_POST['sub_lapangan']; //Your Array
foreach($fields as $field => $value) {
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$value."',1,$row->IDLapangan);");
}
}
Try this:
'INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES("'.$sub_lapangan.'","1","'.$row->IDLapangan.'")'
Related
I'm currently working on something to store matches/events in a database. I like to note that this is my first use of jQuery. Everything is pretty much done, expect this problem.
I use PHP to create a list of teams. When a 'team' is selected, the matches of that team are loaded into div "display". Every match has a id, title, date and time field.
<?php
// show_overview.php
$event_info = mysqli_query($conn, "SELECT e.match_id, e.title, e.date, e.starttime
FROM matches AS e
WHERE e.team_id = '$team' AND e.date >= CURDATE()
ORDER BY e.date asc;");
foreach($event_info as $row) {
$events[] = array('match_id' => $row['match_id'], 'title' => stripslashes($row['title']), 'date' => $row['date'], 'starttime' => $row['starttime']);
}
$data['events'] = $events;
echo json_encode($data);
?>
Here we have the body of the page. In the dropdown box you can select your team.
<!-- BEGIN MATCHES -->
<div class="form-group row">
<label for="team-matchlist" class="col-sm-8 col-md-7 col-form-label">Kies van welk team je de wedstrijden wilt zien:</label>
<div class="col-sm-2 col-md-3 mb-5">
<select class="form-control" id="team-matchlist" name="team-matchlist">
<?php
// Create a list of teams to select the matches. This is loaded in the header. The list is correctly showing.
// $teams = mysqli_query($conn,"SELECT * FROM teams ORDER BY team;");
if ($hierarchy_session >= 3):
while($team = mysqli_fetch_assoc($teams)):
echo '<option value="' . $team['team_id'] . '">' . $team['team'] . '</option>';
endwhile;
mysqli_data_seek($teams, 0);
else:
echo '<option value="' . $team_id_session . '">' . $teamname_session . '</option>';
endif;
?>
</select>
</div>
<!-- Here is the match data loaded -->
<div id="display" class="container"></div>
</div>
</div>
<!-- END MATCHES -->
In are the matches loaded. There are two buttons created for editing a match. It won't connect the data to the modal. I can't get my head around it. I think it's a binding problem, but I can't make it to work.
If I use php directly to export the data, it works. But when I load the data in jQuery. It won't load the data in the body of the modal.
I looked at bind, but I couldn't make that work. I hope someone can make me look in the right direction. I tried to make the code as little as possible.
$(document).ready(function() {
// BEGIN SHOW MATCHES
// Create a list of all the matches from database
// When a team is selected
$("#team-matchlist").change(function () {
var team = $(this).val();
$.ajax({
url: "show_overview.php",
type: "POST",
dataType: "json",
data: {
team: team
},
success: function(response) {
var i;
var display = document.getElementById("display");
if (response.events.length > 0) {
display.innerHTML = "";
var user_hierarchy = '<?php echo $hierarchy_session;?>';
var user_team = '<?php echo $team_id_session;?>';
for (i = 0; i<response.events.length; i++) {
display.innerHTML += (
"<form method='post' class='mb-5 text-md-right'>" +
"<div class='form-group row'>" +
"<label for='firstname' class='col-sm-4 col-md-3 col-form-label'>Titel</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='text' class='form-control' id='etitle-" + response.events[i].match_id + "' name='title' value='" + response.events[i].title + "'>" +
"</div>"+
"</div>"+
"<div class='form-group row'>" +
"<label for='lastname' class='col-sm-4 col-md-3 col-form-label'>Datum</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='date' class='form-control' id='edate-" + response.events[i].match_id + "' name='date' value='" + response.events[i].date + "'>" +
"</div>"+
"</div>"+
"<div class='form-group row'>" +
"<label for='lastname' class='col-sm-4 col-md-3 col-form-label'>Starttijd</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='time' class='form-control' id='estarttime-" + response.events[i].match_id + "' name='starttime' value='" + response.events[i].starttime + "'>" +
"</div>"+
"</div>"+
// Here is the button for editing the match
"<div class='form-group btn-group'>"+
"<button type='button' id='edit_match-" + response.events[i].match_id + "' class='btn btn-primary edit-match' data-toggle='modal' data-target='#modal-edit_match'>" +
"Wijzigen" +
"</button>" +
"</div>"+
"<hr/>"+
"</form>"
);
}
} else {
display.innerHTML = "Er zijn geen wedstrijden voor dit team.";
}
}
});
}).change();
// Show info for confirmation in modal
$('.edit-match').on("click", function() {
var itemID = $(this).attr("id");
var split = itemID.split("-");
var id = split[1];
var title = $("#etitle-"+id).val();
var date = $("#edate-"+id).val();
var starttime = $("#estarttime-"+id).val();
var elem_id = document.getElementById("edit_match");
var title_id = document.getElementById("modal-title-edit_match");
var body_id = document.getElementById("modal-body-edit_match");
var date = new Date(date + "T" + starttime);
const date_options = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric'};
const time_options = { hour: 'numeric', minute: 'numeric' };
var datestring = date.toLocaleDateString('nl-NL', date_options);
var timestring = date.toLocaleTimeString('nl-NL', time_options);
title_id.innerHTML = "Wedstrijd wijzigen";
body_id.innerHTML = "Titel: " + title +
"<br>Datum: " + datestring +
"<br>Starttijd: " + timestring +
"<br><br>Weet u zeker dat u deze wedstrijd wilt wijzigen?";
$(".edit_match").attr("id", "edit_match-" + id);
});
});
</script>
The confirmation is not applied in the modal.
Below we have the modal. The modal is loaded. Only the javascript is not applied to the modal. It remains empty.
<!-- BEGIN MODALS -->
<!-- Modal after clicking on edit match -->
<div class="modal fade" id="modal-edit_match" tabindex="-1" role="dialog" aria-labelledby="modal-title" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-title-edit_match">Wedstrijd wijzigen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Sluiten">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal-body-edit_match">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuleren</button>
<button type="button" name="edit_match" id="edit_match" class="btn btn-primary edit_match">Wijzigen</button>
</div>
</div>
</div>
</div>
<!-- END MODALS -->
Does anyone have any ideas?
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso['+$count+']>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default" id="eliminacorso['+$count+']" aria-label="Elimina">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:
$('#eliminacorso[]').on('click', function() {
$count --;
$('#corso[]').remove();
});
So my ask is: How can i insert between the square brackets the right identifier of the div?
A better choice is:-
1.Instead of using id use button class
2.And then use event delegation concept like below:-
$(document).on('click','.btn-default',function(){
$(this).closest('.form-group').remove();
});
Reference:- https://api.jquery.com/closest/
Use as below the script that add DIV. Remove '[' from id attribute from div tag and anchor tag as below
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso'+$count+'>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default" id="corso'+$count+'" aria-label="Elimina">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
And then script to get the clicked id and remove the matched div on click of button as below
$('.btn').on('click', function() {
var selectedId = $(this).attr('id');
$('#'+selectedId).remove();
});
Try below code.It may help you
var $count =0
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso_'+$count+'">' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso_'+ $count + '"/>' +
'<a class="btn btn-default" id="eliminacorso_'+$count+'" aria-label="Elimina" onclick="remove(this);">' +
'Test' +
'</a>' +
'</div>' +
'</div>' +
'');
});
function remove(aRemove){
console.log(aRemove);
var divid = aRemove.id.replace("eliminacorso_","corso_");
$("#" + divid).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="aggiungi"> Click ME </button>
<div id="corsi">
</div>
https://codepen.io/vino4all/pen/vZrQEX
Try this code.
<button id="aggiungi">Click</button>
<div id="corsi"></div>
Add a class attribute to the <a> tag.
var $count = 0;
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso['+$count+']>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default delBtn" id="eliminacorso['+$count+']" aria-label="Elimina"><span>X</span>' +
'<i class="fa fa-times" aria-hidden="false"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
$('#corsi').on('click', '.delBtn', function() {
console.log('this :'+$(this));
$count --;
$(this).parent().parent().remove();
});
Notice the usage of on function.
It should be like below
$('#corsi').on('click', '.delBtn', fun);
You can use something like this
var count = 3;
$('button').click(function(){
count--;
$($('.corso')[count]).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="corso">1. <input type="text" /></div><br />
<div class="corso">2. <input type="text" /></div><br />
<div class="corso">3. <input type="text" /></div><br />
<br />
<button>Remove</button>
Try this:
var $count = 0
$('#aggiungi').on('click', function () {
$count++;
let divId = `input_div_${$count}`;
let html = `<div class="form-group row" id="${divId}">
<label class="col-sm-2 col-form-label" for="corsi">Input ${$count}</label>
<div class="col-sm-10 form-inline">
<input type="text" class="form-control" id="input" name="${divId}"/>
<button type="button" id="remove_btn_${$count}" aria-label="Elimina" onclick="remove('${divId}');">
remove
</a>
</div>
</div>`;
$('#main-div').append(html);
});
function remove(removeDivId) {
console.log(removeDivId);
$("#" + removeDivId).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="aggiungi"> Click ME </button>
<div id="main-div">
</div>
I am confused how to populate my dropdown that adds on button click with database values . I used jQuery to do the adding function of dropdown on button click. but it seems like i cant populate the options of the select tag inside my jQuery with database values. Please help me out...
This is my php page
<?php include("connect.php");
$smt = $conn->prepare('select CompanyName From Company');
$smt->execute();
$data = $smt->fetchAll();
?>
<div class="form-group" id='TextBoxesGroup'>
<label for="layer" class="col-sm-3 control-label">Layer</label>
<div id="TextBoxDiv1" class="col-sm-6">
<select class="form-control" id='textbox1' name="company" placeholder="Company" >
<?php foreach ($data as $row): ?>
<option><?=$row["CompanyName"]?></option>
<?php endforeach ?>
</select>
</div><hr/>
</div>
<div class="form-group" >
<div class="col-md-9 text-right">
<input type='button' class="btn btn-default" value='Add +' id='addButton'>
</div>
</div>
The jQuery code used to add dropdown on button click is:
EDIT:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 Layers allowed");
return false;
}
var companies = [<?php echo "'".join("','",$data)."'";?>];
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div class="form-group" id="TextBoxesGroup"><label class="col-sm-3 control-label">Layer '+ counter + ' : </label>' +' <div id="TextBoxDiv1" class="col-sm-6"><select class="form-control" name="textbox' + counter + '" id="textbox' + counter + '" name="company" placeholder="Company">');
$.each(companies, function(key, value){
newTextBoxDiv.append('<option>'+value+'</option>');
});
newTextBoxDiv.append('</select> </div></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
</script>
But the output shows like this:
Thanks
Well, you need to echo out the value of $row['companyName'] (the one inside your foreach loop)
Another implementation would be... say you have an array of values in your PHP.
$data = array("company A", "company B", "company C");
And the javascript...
<script>
var companies = [ <?php echo "'". join("','", $data) . "'";?> ];
//This generates : ['company A', 'company B', 'company c'];
function insertOptions()
{
$.each(companies, function(key, value){
$("#IDofSelectTag").append("<option>"+value+"</option>");
});
}
</script>
I have a submit form for writing a caption in an image. I'm using plupload for this. When file is uploaded it will append a div and inside it is a textarea where you can write your caption of that image. But I always getting an error of Undefined Index when submitting a form.
This is my code when file was uploaded:
uploader.bind('FileUploaded', function(up, file) {
var filename = file.id + '.' + file.name.split(".").pop()
var uploaded_files = $('#uploaded_files').attr('value');
var appended_files = uploaded_files + file.id + ',';
$('#uploaded_files').attr('value', appended_files);
var prev = '<div class="col-sm-12" style="margin-bottom:5px;" id="upload-' + file.id + '">' +
'<div class="col-sm-3">' +
'<img class="img-thumbnail" width="100%" height="auto" src="./assets/images/gallery/resorts_gallery/' + filename + '">' +
'</div>' +
'<div class="col-sm-6">' +
'<textarea name="' + file.id + '_Caption" class="form-control" style="font-size:12px;height:70px" placeholder="Put a caption"></textarea>' +
'</div>' +
'<div class="col-sm-3"><span class="btn btn-danger btn-xs"><span class="fa fa-times"></span></span></div>' +
'</div>';
$("#prevCap").append(prev);
});
In my html:
<form role="form" method="POST" id="submit-review" enctype="multipart/form-data">
<div class="form-group">
<label for="uploadphoto">Share your Experiences by uploading Photos</label> <span class="small-text">(optional)</span><br/>
<div class="well" id="caption-thumb"> <!-- preview and caption -->
<div id="prevCap" class="col-sm-12" style="margin-bottom:10px"></div>
<input type="hidden" name="uploaded_files" id="uploaded_files" value="" />
<hr>
<button class="btn btn-default navbar-btn" type="button" data-toggle="modal" data-target="#upload-modal">Add Photos</button>
<hr id="hr-line" style="display:none">
</div>
</div>
<input type="submit" class="btn btn-embossed btn-default" id="btnsubmit" name="submit" disabled value="SUBMIT"/>
</form>
in my php i do something like this:
$last_id = insert_getID("reviews", $fields, $val);
$uploaded_files = $_POST['uploaded_files'];
$uploaded_files = explode(',', $uploaded_files);
$uploaded_files = array_filter($uploaded_files);
foreach ($uploaded_files as $file) {
$wherefields = array('img_name', 'users_id');
$upload_value = $file;
$wherevalues = array($upload_value, $_SESSION['uid']);
$where_file = where($wherefields, $wherevalues, "", "");
$caption = $file . "_Caption";
$file_caption = $_POST['\'' . $caption . '\''];
$file_field = array('review_id', 'caption');
$file_value = array($last_id, $file_caption);
update('gallery', $file_field, $file_value, $where_file);
echo "<pre>" + $file_caption + "</pre>";
}
WHen the files where successfully uploaded, textarea will append inside the div #prevCap and that div was also inside the form. I'm getting an error because the form can't get the value of textarea. How can i fix this problem, how can i get textarea value that was appended?
i am creating a dynamic dropdowns based on a scenario i need to. i am wondering how it possible to keep the states of those added drop downs dynamically when a page is loading after submit button is clicked.
i am able to stote a variable in jquery and check whether form is submitted or not and if submitted to load back the previously dynamically added dropdowns (html select box) but even though i load them back still i have a problem of getting the previously selected values of those dynamic dropdowns.
I have created a fiddler. http://jsfiddle.net/jBJSw/8/
My form
<form>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type="text" id="textbox1">
</div>
</div>
<input type="button" value="Add Button" id="addButton">
<input type="submit" value="submit Button" id="subButton">
</form>
Script
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
'<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
Appreciate if any help on finding a way to get the previously selected values after form submission. (this is needed because when a form is submitted with errors, these selected values should be same but now it refreshes and comes to default. also in a view scenario also this should be preloaded)
You will have to send back the selected value to the page from server side in the querystring or post header. then select the option accordingly in jquery on the base of the the value sent back.
Sorry for getting late have trouble in my work. Here's a possible solution for your problem.
DOM:
<form id="myform" method="post"> <!--adding id attribute-->
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type="text" id="textbox1">
</div>
<!--check if POST is established-->
<?php if($_POST): ?>
<?php if(count($_POST['mySelect']) < 0 ): ?>
<?php
//Recreate your select DOM
$arr = $_POST['mySelect'];
foreach($arr as $ind => $val){
echo '<select>';
echo '<option val="val" ' . ($val == "val" ? "selected" : "") . '>desc2</option>';
echo '<option val="val2" ' . ($val == "val2" ? "selected" : "") . '>desc</option>';
echo '<option val="val3" ' . ($val == "val3" ? "selected" : "") . '>desc3</option>';
echo '</select>';
}
?>
<?php endif; ?>
<?php endif; ?>
</div>
<input type="button" value="Add Button" id="addButton">
<input type="submit" value="submit Button" id="subButton">
</form>
SCRIPT:
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
'<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
//adding hidden inputs
$('#myFORM').on('submit', function(){
$('#myFORM select').each(function(){
slct = $('<input type="hidden" name="mySelect[]" value="' + $(this).val() +'">');
$('#myFORM').append(slct);
});
});
});