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);
});
});
});
Related
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 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.'")'
I would like to show the value from textbox that user type in after the user click on submit.
In the page, I add one button "ADD TEXTBOX" which make the user can add the textbox by themselves for the maximum 10 textboxes.
Here is my current code
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' + '<input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function() {
if (counter == 2) {
alert("System required at least one.");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="<?php $_PHP_SELF ?>" method="post">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 :</label>
<input type='textbox' id='textbox1' name="textbox1">
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<br/>
<input type="submit" name="submit" id="submit">
</form>
Now, I would like to show all the value from the textbox when the user click on the submit button by using php.
This for loop does not show anything after I clicked submit
<?php
if(isset($_POST['submit'])) {
for($i = 1; $i< 10; $i++)
{
if(isset($_POST['textbox'+$i]))
{
$obj = $_POST['textbox'+$i];
echo $obj;
}
}
}
?>
Is there a way to let php check whether the textbox exist or check how many textbox exist in the current form?
To check with php if textbox exists use :
if(isset($_POST['textboxn']))
{
}
You can also check every textbox in one loop
for($i = 0; i< 10; i++)
{
if(isset($_POST['textbox'+i]))
{
}
}
Replace this with following form tag
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
For iterating text boxes use for loop
if ($_SERVER["REQUEST_METHOD"] == "POST") {
for($i = 1; $i <= 10; $i++)
{
if(isset($_POST['textbox'+$i]))
{
}
}
}
Submit form on last select onchange: I have multiple selects, options are generated dynamically.
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
im using select onchange at the same time adding select also this code submit only first level select. I have many levels inside them and options are generated dynamically. I want to submit on last select onchange.
<form id="search_mini_form" action="<?php echo $catalogSearchHelper->getResultUrl() ?>" method="get">
<select id="first_cat" onchange="showCat(this, 2);this.form.submit()" name="<?php echo $catalogSearchHelper->getQueryParamName() ?>" value="<?php echo $catalogSearchHelper->getEscapedQueryText(); ?>" class="input-text" >
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<button type="submit" title="<?php echo $this->__('Search') ?>" class="button"><span><span><?php echo $this->__('Search') ?></span></span></button>
</form>
var select = document.getElementsByTagName('select')[0];
function myFunction(e){
if(e.value == select.options[select.options.length-1].text){
alert("Last value selcted")
}
}
var select = document.getElementsByTagName('select')[0];
function myFunction(e){
if(e.value == select.options[select.options.length-1].text){
alert("Last value selcted")
}
}
<select onchange="myFunction(this)">
<option>item1</option>
<option>item2</option>
<option>item3</option>
<option>item4</option>
<option>item5</option>
</select>
Here http://webmark.pt/sharepics/orders.png is the sales order layout (./sharepics/add.zip the full code) that I need to customize.
Problem:
Dynamically sum the cells between size 39 and 50, and put the value in the Pairs (quantity).
Already managed to add the lines, but the result is added to the lines immediately below.
The code that does this operation:
var newTr = $('<tr id="row_' + count + '"></tr>');
newTr.html('<td><input name="product' + count + '" type="hidden" value="' + item_code + '"><input class="span5 tran" name="item' + count + '" type="text" value="' + item_code + '"></td>
.......
<td><input class="input-block-level text-center" name="sort' + count + '" type="text" value="" id="sort-' + count + '" onClick="this.select();"></td>
<td><input class="input-block-level text-center" name="size39' + count + '" type="text" value="" id="size39-' + count + '" onClick="this.select();"></td>
......
<td><input class="input-block-level text-center" name="size50' + count + '" type="text" value="" id="size50-' + count + '" onClick="this.select();"></td>
<td><input class="input-block-level text-center" name="quantity' + count + '" type="text" value="1" id="quantity-' + count + '" onClick="this.select();"></td>
<td><input class="span2 tran" style="text-align:right;" name="unit_price' + count + '" type="text" id="price-' + count + '" value="' + item_price + '"></td>
<?php echo '<td><input class="span2 tran2" name="cart\'+ count +\'" type="text" value="" required="required" data-error="' . $this->lang->line("cart") . ' ' . $this->lang->line("is_required") . '"></td>';
if (DISCOUNT_OPTION == 2) {
echo '<td><select class="span2 select tran" data-placeholder="Select..." name="discount\' + count + \'" id="discount-\' + count + \'">';
foreach ($discounts as $discount) {
echo "<option value=" . $discount->id;
if ($discount->id == DEFAULT_DISCOUNT) {
echo ' selected="selected"';
}
echo ">" . $discount->name . "</option>";
}
echo '</select></td>';
}
?>
<td><input class="input-block-level text-center" name="subtotalpares' + count + '" type="text" value="" id="subtotalpares" disabled onClick="this.select();"></td>
<td><i class="icon-trash tip del" id="' + count + '" title="Remove this Item" style="cursor:pointer;" data-placement="right"></i></td>');
newTr.prependTo("#dyTable");
count++;
an++;
total += parseFloat(item_price);
$("input[id^=size]").keyup(function () {
var sum = 0;
$("input[id^=size]").each(function () {
sum += (parseInt(this.value) ? parseInt(this.value) : 1);
});
$("input[id^=quantity]").val(sum);
});
I look forward to some help!