Editing data with jQuery in modal won't work - javascript

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?

Related

Creating an option select from db using ajax

I am trying to create an additional form text field on click of a button which wotrtks fine, my only problem is that the select option is blank and when I inspect element I see that NAN is added to it.
Here is the design for the dynamic form elements container
<div class="col-sm-6" id="prescription-container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" class="form-control search-select">
<?php echo $drug_drop_down; ?>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Comment</label>
<div class="phone-icon">
<input type="text" class="form-control" name="diagnosis">
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<a href="#" id="add_prescription" class="btn btn-warning"><i class="fa fa-plus"></i>Add
prescription</a>
</div>
</div>
This is how I have implemented the onclick listener for the add prescription button
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
var result="<option value=''>Select Drug<option>";
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
if (data.length > 0) {
$.each(data, function(i, item) {
result += "<option value='" + data.id + "'>"+data.name+"<option>";
})
} else{
result += "<option value='" + data.id + "'>"+data.name+"<option>";
}
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ result +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Finally this is the controller sending back data
function () {
$drugs = Medicine::get();
return response()->json( $drugs);
}
Now my problem is that when i alert(data) I get [object Object],[object Object]. This made me modify the controller as follows
function () {
$drugs = Medicine::get();
$drug_drop_down = "<option>Select drug</option>";
foreach($drugs as $drug){
$drug_drop_down .="<option value='".$drug->id."'>$drug->name</option>";
}
return response()->json( $drug_drop_down);
}
and the onclick listener to
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ data +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Now if I alert(data) I get <option>Select drug</option><option value='1'>Quinine</option><option value='2'>Malariaquine</option> but the select is still being added without options and the following appear on inspect element for the added filed
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" '="" class="form-control">NaN</select>
</div>
</div>
</div>
What could I be doing wrong here?
After some searching just realized that the second way was supposed to work except that this + + data + "</select>" + means I am using + as an addition operator and not a concatenator, changing it to + data + "</select>" + solved my problem. I do not still understand what the issue could have been with the first approach

Print the contents of a pop up modal window

I would like to print the contents of a pop up modal window and nothing else on the main page.
I've tried linking a button on the popup window to run the command window.print(); but this just prints a blank page.
I'm assuming that this is because I have not actually called the main content to be printed, but they are in javascript and I simply don't know how to do this.
How can I only print the contents of the pop up window?
The print button is here:
<div id="scheduleModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title_logindetail"></h4>
</div>
<div class="modal-body_logindetail">
</div>
<div id="printarea2">
<div class="modal-footer">
<a class="btn btn-primary" href="javascript:void(0);" onclick="printArea2('printableArea')" >Print</a>
<button type="button" class="btn btn-default" data-dismiss="modal"><?php echo $this->lang->line('cancel'); ?></button>
</div>
</div>
</div>
</div>
</div>
This is what I want to print:
$(document).on('click', '.schedule_modal', function () {
$('.modal-title_logindetail').html("");
$('.modal-title_logindetail').html("<?php echo $this->lang->line('login_details'); ?>");
var base_url = '<?php echo base_url() ?>';
var student_id = '<?php echo $student["id"] ?>';
var student_first_name = '<?php echo $student["firstname"] ?>';
var student_last_name = '<?php echo $student["lastname"] ?>';
$.ajax({
type: "post",
url: base_url + "student/getlogindetail",
data: {'student_id': student_id},
dataType: "json",
success: function (response) {
var data = "";
data += '<div class="col-md-12">';
data += '<div class="table-responsive">';
data += '<p class="lead text text-center" style="font-size:60px;">' + student_first_name + ' ' + student_last_name + '</p>';
data += '<table class="table table-hover">';
data += '<thead>';
data += '<tr>';
data += '<th class="text text-center" style="font-size:40px;">' + "<?php echo $this->lang->line('user_type'); ?>" + '</th>';
data += '<th class="text text-center" style="font-size:40px;">' + "<?php echo $this->lang->line('username'); ?>" + '</th>';
data += '<th class="text text-center" style="font-size:40px;">' + "<?php echo $this->lang->line('password'); ?>" + '</th>';
data += '</tr>';
data += '</thead>';
data += '<tbody>';
$.each(response, function (i, obj) {
data += '<tr>';
data += '<td class="text text-center" style="font-size:30px;"><b>' + firstToUpperCase(obj.role) + '</b></td>';
data += '<input type=hidden name=userid id=userid value=' + obj.id + '>';
data += '<td class="text text-center" style="font-size:30px;">' + obj.username + '</td> ';
data += '<td class="text text-center" style="font-size:30px;">' + obj.password + '</td> ';
data += '</tr>';
});
data += '</tbody>';
data += '</table>';
data += '<b class="lead text text-danger" style="font-size:20px;"> ' + "<?php echo $this->lang->line('login_url'); ?>" + ': ' + base_url + 'site/userlogin</b>';
data += '</div> ';
data += '</div> ';
$('.modal-body_logindetail').html(data);
$("#scheduleModal").modal('show');
}
});
});
function firstToUpperCase(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
</script>
<script>
function printArea2(areaID) {
var printContent = document.getElementById("printarea2");
var WinPrint = window.open('', '', 'width=1100,height=650');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
assuming you want to print div with class $(".modal-title_logindetail")
change your print button to
<a class="btn btn-primary" href="javascript:void(0);" onclick="printArea2();" >Print</a>
try this
function printArea2() {
var contents = document.getElementsByClassName("modal-title_logindetail").innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write('<html><head><title>DIV Contents</title>');
frameDoc.document.write('</head><body>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
return false;
}

Display contents of $row in a modal dynamically

I have a website in which events are queried and displayed on the index page. Upon clicking an image which was among the results of the query, a modal pops up.
As i have multiple images, I would like to dynamically display the contents of each row in the modal depending on which image was clicked. Currently, I am able to click any image and a modal appears, however they all contain the data from row[0].
INDEX PAGE:
while($row = $result->fetch_assoc()) {
include 'testModal.php';
echo "<tr><td><figure><figcaption style='padding-bottom:20px'>" . $row["name"]."</figcaption>".
'<img class="modalBtn" style="width:15em; height:17em;" src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/></figure></td>'.
"<td>".$row["category"]."</td>".
"<td> $".$row["price"]."</td>".
"<td>".$row["age"]."</td>".
"</tr>";
}
?>
The below is the modal page.
MODAL PAGE:
<div id="TheModalTest" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close" onclick="closeWindow()">X</span>
</div>
<div>
<?php echo '<img style="width:15em; height:17em;"
src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>'; ?>
</div>
<?php echo '<p class="desc">'.$row["description"].'</p>' ?>
<div class="modal-footer">
<h3>BOOK NOW</h3>
</div>
</div>
</div>
<script>
//get modal
var Testmodal = document.getElementById('TheModalTest');
//get button that opens modal
//var modalbtn = document.getElementById('modalbtn');
var modalbtn = document.getElementsByClassName('modalBtn');
console.log("Length: " + modalbtn.length);
//Open modal when btn click
for (var i = 0; i < modalbtn.length+1; i++ ) {
console.log("I IS: " + i);
modalbtn[i].onclick = function(){
console.log("MODAL IS: " + modalbtn[i]);
Testmodal.style.display = "block";
}
}
</script>
The below images are what it looks like. When i click the event image for Kanye, the modal pops up with his image. However if i click the image of Katy Perry, the modal pops up with Kanye still.
https://i.imgur.com/YhIoXmT.png
https://i.imgur.com/AaqxChj.png
Your Question Something unclear, Try to Provide the Output screenshots and mark it. Because i don't know the output.
But
I have Re written your mysql Code as foreach So you can play with foreach images.
while($row1 = $result->fetch_assoc()) {
foreach($row1 as $row){
include 'testModal.php';
echo "<tr><td><figure><figcaption style='padding-bottom:20px'>" . $row["name"]."</figcaption>".
'<img class="modalBtn" style="width:15em; height:17em;" src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/></figure></td>'.
"<td>".$row["category"]."</td>".
"<td> $".$row["price"]."</td>".
"<td>".$row["age"]."</td>".
"</tr>";
}
}
Replace the above code with your Old one. Hope it works.
Try not to mix " and '. Just stick with single quotes for php and js, it makes it simpler when you're starting.
What you'll need to do is add an attribute to the element with the data you want to pass to the modal, than grab that attribute's value with your js.
notice: data-category="'.$row['category'].'" below
<?
while($row = $result->fetch_assoc()) {
include 'testModal.php';
echo '<tr><td><figure><figcaption style="padding-bottom:20px">' . $row['name'].'</figcaption>'.
'<img data-category="'.$row['category'].'" class="modalBtn" style="width:15em; height:17em;" src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/></figure></td>'.
'<td>'.$row['category'].'</td>'.
'<td> $'.$row['price'].'</td>'.
'<td>'.$row['age'].'</td>'.
'</tr>';
}
?>
now in the modal... notice category = modalbtn[i].getAttribute('data-category');
<div id="TheModalTest" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close" onclick="closeWindow()">X</span>
</div>
<div>
<?php echo '<img style="width:15em; height:17em;"
src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>'; ?>
</div>
<?php echo '<p class="desc">'.$row["description"].'</p>' ?>
<div class="modal-footer">
<h3>BOOK NOW</h3>
</div>
</div>
</div>
<script>
//get modal
var Testmodal = document.getElementById('TheModalTest');
//get button that opens modal
//var modalbtn = document.getElementById('modalbtn');
var modalbtn = document.getElementsByClassName('modalBtn');
console.log("Length: " + modalbtn.length);
//Open modal when btn click
for (var i = 0; i < modalbtn.length+1; i++ ) {
console.log("I IS: " + i);
modalbtn[i].onclick = function(){
console.log("MODAL IS: " + modalbtn[i]);
/// here your go
var category = modalbtn[i].getAttribute('data-category');
console.log('category',category);
Testmodal.style.display = "block";
}
}
</script>
<script>

INSERT data from append script

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.'")'

Create select box dynamically with jQuery

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

Categories