change checkbox label after select - javascript

I have some checkboxes (101) which labels should change based on a select input. The JS I have only runs for one, which is logical. Though I'm not very familiar with jquery functions, I don't know how to proceed for all the 101 checkboxes.
the inputs :
<?php
for ($i = 1; $i < 102; $i++): //adjust this number to whatever number of checkboxes you want
echo '<div class="each_checkboxes">';
// $j = sprintf('%04u', $i);
echo '<label id="contact" for="checkbox"></label>';
echo '<input type="checkbox" name="tape[]" id="checkbox" value=""/>';
echo '</div>';
endfor;
?>
the select :
<select id="method" name="server" class="custom-dropdown__select custom-dropdown__select--white" required>
<option value="0" default>Choose server</option>
<option value="server1">server 1</option>
<option value="server2">server 2</option>
</select>
the js :
$(document).ready(function () {
$('#method').change(function () {
var method = $('option:selected').val();
if (method == "server1") {
$('#contact').text("MA" + i);
} else if (method == "server2") {
$('#contact').text("SAS" + i);
}
});
});

You need to use class instead of id, because id should be unique for each element. Try like following.
PHP:
<?php
for ($i = 1; $i < 102; $i++):
echo '<div class="each_checkboxes">';
echo '<label class="contact" for="checkbox'.$i.'"></label>';
echo '<input type="checkbox" name="tape[]" id="checkbox'.$i.'" value=""/>';
echo '</div>';
endfor;
?>
jQuery:
$(document).ready(function () {
$('#method').change(function () {
var method = $('option:selected').val(),
text = "";
if (method == "server1") {
text = "MA";
} else if (method == "server2") {
text = "SAS";
}
$('.contact').each(function (i) {
var value = text + (++i);
$(this).text(value);
$('#' + $(this).attr('for')).val(value);
});
});
});

You are referencing to id attribute in your jQuery selector which will only look for first match in your dom You need to assign a class to your label and reference to that when changing you label text then this will work.
<?php
for ($i = 1; $i < 102; $i++): //adjust this number to whatever number of checkboxes you want
echo '<div class="each_checkboxes">';
// $j = sprintf('%04u', $i);
echo '<label id="contact" class="contact" for="checkbox"></label>';
echo '<input type="checkbox" name="tape[]" id="checkbox" value=""/>';
echo '</div>';
endfor;
?>
and in jQuery just use class selector like this;
$(document).ready(function () {
$('#method').change(
function () {
var method = $('option:selected').val();
if (method == "server1") {
$('.contact').text("MA" + i);
} else if (method == "server2") {
$('.contact').text("SAS" + i);
}
});
});
That's it.

Use label class instead of id
<?php
for ($i = 1; $i < 102; $i++): //adjust this number to whatever number of checkboxes you want
echo '<div class="each_checkboxes">';
// $j = sprintf('%04u', $i);
echo '<label class="contact" for="checkbox"></label>';
echo '<input type="checkbox" name="tape[]" id="checkbox" value=""/>';
echo '</div>';
endfor;
?>
js code is
$(document).ready(function () {
$('#method').change(
function () {
var method = $('option:selected',this).val();
if (method == "server1") {
$('.each_checkboxes label.contact').html("MA" + i);
} else if (method == "server2") {
$('.each_checkboxes label.contact').html("SAS" + i);
}
});
});

Use "class" for your checkbox's label instead of "id". Basically, "id" of an element should be unique. But class, more than one elements can have the same class.
So, the label should be like this:
<label class="contact" for="checkbox"></label>
Then your onchange method should be like this:
$('#method').change(
function () {
var method = $('option:selected').val();
if (method == "server1") {
$('.contact').text("MA" + i);
} else if (method == "server2") {
$('.contact').text("SAS" + i);
}
});

Related

I can't save specific selected value. it saved all data from database

i am inserting multiple data. what happen is when i select a project from drop down list. it save all data from selection. please check the image below first
function sample($con){
$select = "SELECT * FROM project_tbl";
$select_result = mysqli_query($con,$select);
if (mysqli_num_rows($select_result)> 0) {
while ($row = mysqli_fetch_assoc($select_result)) {
echo "<option value=".$row['project_name'].">" .$row['project_name']."</option>";
}
}
}
*html codes (i used drop down list to populate data from database)
<td class="pro">
<select class="pro">
<option value=""><?php sample($con); ?></option>
</select>
</td>
*ajax codes (adding, saving and removing)
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td class='pro'><select class='pro'><option value=''><?php sample($con); ?></option></select></td>";
html_code += "<td contenteditable='true' class='desc'></td>";
html_code += "<td contenteditable='true' class='comp'></td>";
html_code += "<td contenteditable='true' class='entry'></td>";
html_code += "<td contenteditable='true' class='remarks'></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-outline-danger btn-xs remove' title='remove'><i class='fa fa-times' aria-hidden='true'></i></button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var desc = [];
var pro = [];
var comp = [];
var entry = [];
var remarks = [];
$('.desc').each(function(){
desc.push($(this).text());
});
$('.pro').each(function(){
pro.push($(this).text());
});
$('.comp').each(function(){
comp.push($(this).text());
});
$('.entry').each(function(){
entry.push($(this).text());
});
$('.remarks').each(function(){
remarks.push($(this).text());
});
$.ajax({
url:"insert_inspection.php",
method:"POST",
data:{desc:desc, pro:pro, comp:comp, entry:entry, remarks:remarks},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
$('select').prop('selectedIndex',0);
for(var i=2; i<= count; i++){
$('tr#'+i+'').remove();
}
}
});
});
});
Here is what happen when I save.
database
I am new in PHP.
insert_inspection.php
<?php
$con = mysqli_connect("localhost", "root", "", "pms");
if (isset($_POST["desc"])){
$desc = $_POST["desc"];
$pro = $_POST["pro"];
$comp = $_POST["comp"];
$entry = $_POST["entry"];
$remarks = $_POST["remarks"];
$query = '';
for($count = 0; $count<count($desc); $count++){
$desc_clean = mysqli_real_escape_string($con, $desc[$count]);
$pro_clean = mysqli_real_escape_string($con, $pro[$count]);
$comp_clean = mysqli_real_escape_string($con, $comp[$count]);
$entry_clean = mysqli_real_escape_string($con, $entry[$count]);
$remarks_clean = mysqli_real_escape_string($con, $remarks[$count]);
if($desc_clean != '' && $pro_clean != '' && $comp_clean != '' && $entry_clean != '' && $remarks_clean != ''){
$query .= 'INSERT INTO `inspection_tbl`(`description`, `project_name`, `completion`, `entry`, `remarks`) VALUES("'.$desc_clean.'", "'.$pro_clean.'", "'.$comp_clean.'", "'.$entry_clean.'", "'.$remarks_clean.'");
';
}
}
if($query != ''){
if(mysqli_multi_query($con, $query)){
echo 'Item Data Inserted';
}else{
echo 'Error';
}
}else{
echo 'All Fields are Required';
}
}
?>
it is saved as such because your select element only has one option value
modify it from:
<td class="pro"> <select class="pro"> <option value=""><?php sample($con); ?></option> </select> </td>
to:
<td class="pro">
<select class="pro">
<option value=""></option>
<?php sample($con); ?>
</select>
</td>
and modify your select element handler to push only your selected item
something like this:
$('.pro').each(function(){
if($(this).prop("selected")) {
pro.push($(this).text());
}
});
or modify this part to something like:
$(".pro > option:selected").each(function(){
pro.push($(this).text());
});

Php id recognizing in js

I have a loop in php and I'm using a js function onclick to get the id from the php loop. I do loop in js to recognize a php dynamic id, but it recognizes the wrong order of the loop item.
Sample php code:
$list = 1;
for ($i = 0; $i < 7; $i++ ){
$listNo = $list;
$list++;
$html .= "<div class='row l'>";
$html .= " <div class='col-xl-3 col-lg-8 col-6'>
<input name=']' id='dm_slider_img_url_$listNo' type='text' value='" . $dm_slides[++$counter] . "'/>
<button class='set_custom_images' id='meta-image-button-$listNo'>
<span class='dashicons dashicons-plus-alt'></span>
</button>
</div>
<div class='col-xl-1 col-lg-4 col-6 mr-auto'>
<img id='dm_slider_img_preview_$listNo' src='" . $dm_slides[$counter++] . "' name=''>
</div>";
$html .= "</div>";
}
Sample js code:
var send_attachment_bkp = wp.media.editor.send.attachment;
for (let ids=1; ids<8; ids++) {
if ($('#meta-image-button-'+ids).length > 0) {
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor) {
$(document).on('click', '.set_custom_images', function(e) {
e.preventDefault();
var button = $(this);
var id = button.prev();
wp.media.editor.send.attachment = function(props, attachment) {
$('#dm_slider_img_url_'+ids).val(attachment.url);
$('#dm_slider_img_preview_'+ids).attr('src',attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
};
wp.media.editor.open(button);
return false;
});
}
}
}
What am I doing wrong?
After looking other questions related to getting id, I figured it out. After calling click function using button class, I stored it as variable and added this variable.
$(document).ready(function() {
var $ = jQuery;
// var ids = 1;
// $(«.set_custom_images»).onclick = function(t) {t.attr(«id»)}
var send_attachment_bkp = wp.media.editor.send.attachment;
if ($("[id^='meta-image-button-']" ).length > 0) {
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor) {
$(document).on('click', '.set_custom_images', function(e) {
var clickedID = this.id;
e.preventDefault();
var button = $(this);
var id = button.prev();
wp.media.editor.send.attachment = function(props, attachment) {
$('#dm_slider_img_url_'+clickedID).val(attachment.url);
$('#dm_slider_img_preview_'+clickedID).attr('src',attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
};
wp.media.editor.open(button);
return false;
});
}
}
});
And in php make some changes
$list = 1;
for ($i = 0; $i < 7; $i++ ){
$listNo = $list;
$list++;
$html .= "<div class='row l'>";
$html .= " <div class='col-xl-3 col-lg-8 col-6'>
<input name='' id='dm_slider_img_url_m_$listNo' type='text' value='" . $dm_slides[++$counter] . "'/>
<button class='set_custom_images' id='m_$listNo'>
<span class='dashicons dashicons-plus-alt'></span>
</button>
</div>
<div class='col-xl-1 col-lg-4 col-6 mr-auto'>
<img id='dm_slider_img_preview_m_$listNo' src='" . $dm_slides[$counter++] . "' name=''>
</div>";
$html .= "</div>";
}
I hope this will help for someone who searches solution like this

How to add HTML form fields based on JSON response data

I have a HTML form for products which contains initially a fields group (for the product components) of 2 rows and can add rows using a button with an onClick event to a js function addRow(). the code is:
<?php
$arrayNumber = 0;
for($x = 1; $x < 3; $x++) { ?>
<tr id="editRow<?php echo $x; ?>" class="<?php echo $arrayNumber; ?>">
<td style="padding-left:20px;padding-right: 20px;">
<div class="form-group">
<select class="form-control" name="editRawName[]" id="editRawName<?php echo $x; ?>" onchange="getRawData(<?php echo $x; ?>)">
<option value="">~~SELECT~~</option>
<?php
$rawSql = "SELECT * FROM raw_material WHERE status = 1";
$rawData = $connect->query($rawSql);
while($row = $rawData->fetch_array()) {
echo "<option value='".$row['raw_id']."' id='changeRaw".$row['raw_id']."'>".$row['raw_name']."</option>";
} // /while
?>
</select>
</div>
</td>
<td style="padding-left:20px;">
<div class="form-group">
<input type="number" name="editQuantity[]" id="editQuantity<?php echo $x; ?>" autocomplete="off" class="form-control" min="1"/>
</div>
</td>
<td>
<button class="btn btn-default removeRawRowBtn" type="button" id="removeRawRowBtn" onclick="removeRawRow(<?php echo $x; ?>)"><i class="glyphicon glyphicon-trash"></i></button>
</td>
</tr>
<?php
$arrayNumber++;
} // /for?>
Now, to edit a product I use a js function editProduct() to fetch the selected product data and return it as a JSON response to fill the product form fields. The editProduct function code part to grab and fill product fields is:
function editProduct(productId = null) {
if(productId) {
$("#productId").remove();
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
$('.div-loading').removeClass('div-hide');
$('.div-result').addClass('div-hide');
$.ajax({
url: 'action.php',
type: 'post',
data: {productId: productId},
dataType: 'json',
success:function(response) {
$('.div-loading').addClass('div-hide');
$('.div-result').removeClass('div-hide');
$(".editProductFooter").append('<input type="hidden" name="productId" id="productId" value="'+response.product_id+'" />');
// product name
$("#editProductName").val(response.product_name);
// category name
$("#editCategoryName").val(response.categories_id);
// quantity
$("#editProductQuantity").val(response.quantity);
// product unit
$("#editProductUnit").val(response.product_unit);
// sales margin
$("#editSalesMargin").val(response.sales_margin);
// status
$("#editProductStatus").val(response.status);
// Get the product components count
var totalComponents = response.total_components;
// Loop for every component
// Set the fields id that will contains the data
// Fill the fields with data
for (var x = 0; x<totalComponents; x++){
var idrawn = "#editRawName"+x.toString();
var idrawq = "#editQuantity"+x.toString();
var resri = "raw_id_"+x.toString();
var resqu = "rp_quantity_"+x.toString();
$(idrawn).val(response[resri]);
$(idrawq).val(response[resqu]);
}
The problem is: In case of a product with a total components of more than 2, I need to add rows to be filled with the components data.
First, I tried to launch the addRow() function before the last for loop in the editProduct function like this (didn't work):
if (totalComponents > 2) {
var adro = totalComponents - 2;
for (var y=0; y<adro; y++)
{ addRow(); }
}
Then, I tried to simulate the click of the Add Component button that launch the addRow function using the solution posted here: How to simulate a click with JavaScript? and change the above code like this:
if (totalComponents > 2) {
var adro = totalComponents - 2;
for (var y=0; y<adro; y++)
{ eventFire(document.getElementById('addRowBtn'), 'click'); }
}
but still no luck.
The code of addRow function is:
function addRow() {
$("#addRowBtn").button("loading");
var tableLength = $("#rawTable tbody tr").length;
var tableRow;
var arrayNumber;
var count;
if(tableLength > 0) {
tableRow = $("#rawTable tbody tr:last").attr('id');
arrayNumber = $("#rawTable tbody tr:last").attr('class');
count = tableRow.substring(3);
count = Number(count) + 1;
arrayNumber = Number(arrayNumber) + 1;
} else {
// no table row
count = 1;
arrayNumber = 0;
}
$.ajax({
url: 'action1.php',
type: 'post',
dataType: 'json',
success:function(response) {
$("#addRowBtn").button("reset");
var tr = '<tr id="row'+count+'" class="'+arrayNumber+'">'+
'<td style="padding-left:20px;padding-right: 20px;">'+
'<div class="form-group">'+
'<select class="form-control" name="rawName[]" id="rawName'+count+'" onchange="getRawData('+count+')" >'+
'<option value="">~~SELECT~~</option>';
$.each(response, function(index, value) {
tr += '<option value="'+value[0]+'">'+value[1]+'</option>';
});
tr += '</select>'+
'</div>'+
'</td>'+
'<td style="padding-left:20px;">'+
'<div class="form-group">'+
'<input type="number" name="quantity[]" id="quantity'+count+'" autocomplete="off" class="form-control" min="1" />'+
'</div>'+
'</td>'+
'<td>'+
'<button class="btn btn-default removeRawRowBtn" type="button" onclick="removeRawRow('+count+')"><i class="glyphicon glyphicon-trash"></i></button>'+
'</td>'+
'</tr>';
if(tableLength > 0) {
$("#rawTable tbody tr:last").after(tr);
$("#totalComponents").remove();
var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+count+'" />';
} else {
$("#rawTable tbody").append(tr);
$("#totalComponents").remove();
var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+tableLength+'" />';
}
$("#rawTable").after(comp);
}
});}
I was wandering if there is a way to get the result that I need.

nested categories dropdown in magento

I have the following working code in magento frontend in a form for customer "add a product" functionality that Im developing:
Helper area:
public function getCategoriesDropdown() {
$categoriesArray = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'))
->load()
->toArray();
foreach ($categoriesArray as $categoryId => $category) {
if (isset($category['name'])) {
$categories[] = array(
'label' => $category['name'],
'level' =>$category['level'],
'value' => $categoryId
);
}
}
return $categories;
}
PHTML File:
<select id="category-changer" name="category-changer" style="width:150px;">
<option value="">--Select Categories--</option>
<?php
$_CategoryHelper = Mage::helper("marketplace")->getCategoriesDropdown();
foreach($_CategoryHelper as $value){
foreach($value as $key => $val){
if($key=='label'){
$catNameIs = $val;
}
if($key=='value'){
$catIdIs = $val;
}
if($key=='level'){
$catLevelIs = $val;
$b ='';
for($i=1;$i<$catLevelIs;$i++){
$b = $b."-";
}
}
}
?>
<option value="<?php echo $catIdIs; ?>"><?php echo $b.$catNameIs ?></option>
<?php
}
?>
</select>
this code generates a dropdown with categories and subcategories. like this one:
my main idea is to create n level nested chained dropdowns for subcategories like this example:
or this layout would be better:
any guidance or code example to modify the proposed php in order to include an ajax call, or javascript to generate those frontend chained frontends will be appreciated
brgds!
Here is my way:
In helper class, add method:
public function getCategoriesDropdown() {
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'));
$first = array();
$children = array();
foreach ($categories->getItems() as $cat) {
if ($cat->getLevel() == 2) {
$first[$cat->getId()] = $cat;
} else if ($cat->getParentId()) {
$children[$cat->getParentId()][] = $cat->getData();
}
}
return array('first' => $first, 'children' => $children);
}
In PHTML File:
<?php $tree = $this->helper('xxx')->getCategoriesDropdown(); ?>
<script type="text/javascript">
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);
}
}
</script>
<select id="first_cat" onchange="showCat(this, 2)">
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<div id="sub_cat"></div>
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
/* You can play with this code */
echo '<select>';
echo getChildrenCategoryOptions($rootCategoryId);
echo '</select>';
/* You can play with this code */
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$html .= '<option value="'.$_category->getId().'">'.str_repeat("-", ($_category->getLevel() - 2)).$_category->getName().'</option>';
$html .= getChildrenCategoryOptions($_category->getId());
}
return $html;
}
else {
return '';
}
}
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$categoriesHierachy = getChildrenCategoryOptions($rootCategoryId);
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$array[$_category->getLevel()][$_category->getId()]['name'] = $_category->getName();
$array[$_category->getLevel()][$_category->getId()]['subcategories'] = getChildrenCategoryOptions($_category->getId());
}
return $array;
}
else {
return array();
}
}

Text Box not saving in wordpress theme settings

I am creating a wordpress theme with theme options in wordpress. I like to add a dynamic add and remove textbox using jquery inside the theme settings page. My query is,
theme_settings.php
<?php
function theme_settings_init(){
register_setting( 'theme_settings', 'theme_settings' );
}
function add_settings_page() {
add_menu_page( __( 'Theme Settings' ), __( 'Theme Settings' ), 'manage_options', 'settings', 'theme_settings_page');
}
//add actions
add_action( 'admin_init', 'theme_settings_init' );
add_action( 'admin_menu', 'add_settings_page' );
//start settings page
function theme_settings_page() {
if ( ! isset( $_REQUEST['updated'] ) )
$_REQUEST['updated'] = false;
?>
<div>
<div id="icon-options-general"></div>
<h2><?php _e( 'Theme Settings' ) //your admin panel title ?></h2>
<?php
//show saved options message
if ( false !== $_REQUEST['updated'] ) : ?>
<div><p><strong><?php _e( 'Options saved' ); ?></strong></p></div>
<?php endif; ?>
<form method="post" action="options.php">
<?php settings_fields( 'theme_settings' ); ?>
<?php $options = get_option( 'theme_settings' ); ?>
<div id='TextBoxesGroup'>
<?php
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
?>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<p><input name="submit" id="submit" value="Save Changes" type="submit"></p>
</form>
</div><!-- END wrap -->
<?php
}
and my javascript file is:
$(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);
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
Now my question is, In the theme settings page, the add action and remove action works very fine but while saving the theme setting options the added textbox dissappears. It happens while refreshing the page too.
Please anyone help me how to keep those added textbox remains same if saving the theme options page.
Use .append() instead of .after().html(). This way your code goes inside the corresponding div element. I made use of jQuery also.
newTextBoxDiv.after().html(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >');
should be
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
To make the text boxes appear you need a while loop like this:
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
When you save them you could do this:
$counter = 0;
while (isset($_POST['theme_settings']['textbox'.$counter']) && $counter <= 10) {
update_option('textbox'.$counter, $_POST['theme_settings']['textbox'.$counter']);
$counter++;
}
// now remove the rest of them if they were previously set
// for example we now set only 5 of them and there were 10 before
// continue with counter from where we left in the previous while loop
while ($counter <= 10) {
update_option('textbox'.$counter, false);
$counter++;
}
EDIT:
function theme_settings_page() {
$updated = false;
if (isset($_REQUEST['updated'])) {
update_option('theme_settings', $_POST['theme_settings']);
$updated = true;
}
// ....
if ($updated) {
echo '<div><p><strong>';
_e( 'Options saved' );
echo '</strong></p></div>';
}
$counter = 1;
$options = get_option('theme_settings');
while (isset($options['textbox'.$counter])) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" value="'.$options['textbox'.$counter].'" />
</div>';
$counter++;
}
echo '<input type="hidden" name="updated" value="1" />';
// the rest of your form
}

Categories

Resources