Multiple dynamic selections - php

I need a way of having multiple selections but only one visible at a time.
When the user wants to add another selection he/she clicks a button,checkbox,radio..whatever
They need to be able to add an unlimited number of selections. Any Ideas?

Old question, but might as well add my 2 cents, in case anyone else wants to know an answer.
I would use JavaScript to create a <select> element in a "more" section, from a JavaScript loop. For example, your first page would have
<input type="button" value="New Select Box" onclick="createNewBox();" /><br />
<span id="selectElement1">
<select>[your code for the select box goes here]</select>
<span id="selectElement2"></span>
</span>
Which could setup your basic select element, and the New Select Box would activate this JavaScript function code:
<script type="text/javascript">
// Initialization Code
var currentSelect = 1; // Keeps track of which select box is current
// New Select Box code
function createNewBox()
{
var currentSelect = currentSelect + 1;
var nextSelect = currentSelect + 1;
document.getElementById('selectElement'+currentSelect).innerHTML = "<select>[code goes here]</select><span id=\"selectElement"+nextSelect+"\"></span>";
}
</script>
This whole thing can run with only those two code snippets, and no jQuery code is needed.

Related

JQuery var to form POST for PHP

To start off, sorry if this is a duplicate, or explained already. I've read a minimum of 15 other topics that I assumed are similar to mine, yet I haven't had any success in getting it to work.
I currently have a form that is action="submit.php". The form is an order form (see Jfiddle link at bottom of post). Inside submit.php I'm making an array of all $_POST values. That works great. Now the problem:
On the forum page (where user inputs), I have the following JQuery script that calculates totals. There are 3 types of totals (all this is clear in the JFiddle). The 3rd total, called "overallTotal", takes the sum of all "grandTotal"s and as of now, puts in #overallTotal ID. I need that number to be included in the form submission (i.e., so it is accessible by $_POST).
Thanks in advance, and sorry again if this is repetitive.
JSFiddle: http://jsfiddle.net/rc694dzL/
function oninput(e) {
// process this row first
var row = $(e.target).closest("tr");
// explicitly cast to a number
var quantity = +$(e.target).val();
var price = +row.find(".val1").text();
var output = row.find(".multTotal");
var total = price * quantity;
output.text(total);
// now calculate total
var subtotal = 0;
var table = $(e.delegateTarget);
table.find(".multTotal").each(function () {
subtotal += (+$(this).text());
});
table.find(".grandTotal").text(subtotal);
// now calculate overall total
var overallTotal = 0;
$(document).find(".grandTotal").each(function () {
overallTotal += (+$(this).text());
});
$('#overallTotal').text(overallTotal);
Add a hidden input in your form like this
<input type="hidden" name="overallTotal" id="overallTotalInput">
and set the value from javascript like this
$('#overallTotalInput').val(overallTotal);
Now when submitting the form, the value will be stored into $_POST['overallTotal']
Add some hidden fields in the form, and then populate the values with jquery.
Edit: tweaking your Fiddle now with an example: http://jsfiddle.net/dozecnp6/1/
1) Added the hidden input in the form:
<input type="hidden" name="OverallTotal" id="overallTotalField">
2) Added a bit to your oninput() function:
$('#overallTotalField').val(overallTotal);
in this fiddle i can use type="text" you can change it to type="hidden"
check this
fiddle

how to stop refreshing page on onchange="this.form.submit()"

see my client site first to get an idea.
In above site, i have a giftfinder box in right side. There are 3 select boxes. currently I'm using 3 forms for these 3 select boxes which means each drop down select box is embedded into form. When you select the first drop down select box, it picks one and second select box's value will be determined which value is selected from first select box. So if you choose Man, then all athe related occasions of Man will be dispalyed into seconds drop down select box. Its working fine.
But the problem is it refreshes everytime you select the first drop down box.
I don't want to refresh page. it must select the value and pass the value so seconds select box can determine its related values.
so I'm thinking to us ajax. but no success.
So i included some code for the first drop down select box.
this is mix of html and php and wordpress.
<div class="select-one">
<form id="searrec" method="post" action="">
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
<?php
$results_rec = get_option('current_recipient');
if(isset($_POST['selectionRecipient'])){
$results_rec = $_POST['selectionRecipient'];
update_option('current_recipient', $results_rec);
$results_rec = get_option('current_recipient');
}
?>
<?php
//asort($result_rec);
$t_name_arr = array();
foreach($result_rec as $rec):
$t_id = $rec->term_id;
$term = get_term($t_id , 'category' );
$t_name_arr[] = $term->name;
endforeach;
//print_r($t_name_arr);
rsort($t_name_arr);
foreach ($t_name_arr as $t_name):?><option class="rec_val"<?php if($results_rec==$t_name){ echo 'selected="selected"';}?>value="<?php echo $t_name;?>"><?php echo $t_name;?></option>
<?php endforeach;?>
</select>
<input type="hidden" id="submitrec" value="Search" />
</form> -->
</div>
So I'm am using form method post and using $_POST to retrieve the selected value and pass it to $results_rec variable.
Later in the code, I'm using if.. else to determine if $results_rec =='Man' then display certain items which are related to Man and so forth.
So what I want is not to refresh the page while I select item from first drop down select box.
Please help.
change this:
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
to this:
<select name="selectionRecipient" id="selectionRecipient">
and the jquery:
$("#searrec").submit(function(e) {
e.preventDefault();
// your code
return false;
});
EDITED:
use this to get the selected index (number)
var index = $("#selectionRecipient")[0].selectedIndex;
or value:
var value = $("#selectionRecipient")[0].value;
Then you can call an ajax perhaps: (assuming the other selection box has "id=other_select"
$.ajax({url:"index.php",type:"POST",data {type:"populate",index:2,value:"option1"},dataType:"json",
success: function(data) {
// data (json) returned from server so populate other selection boxes with that..
// in this example 'data' is an array, coming directly from server (see below the .php)
$("#other_select")[0].selectedIndex = 0;
for(var x in data) {
$("#other_select")[0].options[x] = new Option(data[x]);
}
}
})
in your .php i assume you get a list (etc. database) to populate the other selection list (in client). This code could looks like:
if (isset($_POST["type"]) && $_POST["type"]=="populate") {
echo json_encode(array("option1","option2","option3"));
exit(1);
}
$('#searrec').submit(function () {
//do some form submit work here
return false;
});
You'll have to use an AJAX call to populate the other select boxes based on whatever you've selected in the first one without reloading the page.
I suggest you take a look at jQuery's AJAX functionality. Read up on $.ajax and $.post - with them you could submit the value that you've selected in the first listbox to a PHP script and then based on that value return and populate the other select boxes.
Use AJAX to update the other selects without refreshing the page. Use jQuery to make AJAX easy.
This question will help:
Change the selected value of a drop-down list with jQuery
$('#searrec').submit(function(e){
e.preventDefault();
});
You should delete event onchange="this.form.submit(); from combobox
And use ajax with jquery:
$("#searrec").onchange(function() {
$.ajax({
url:"",
success:function(response){
alert("success");
}
});
});
Guys its fixed.
Plz have a look at http://giftideasitems.com/.
See gift finder box and see how it works.
I used iframe and embedded the forms, drop down coding there. thats it.
Even I used onchange="this.form.submit()" and page doesnot referesh, actually page refresh .... but not the main page, only the iframe is refreshing which is fine. this is exactly what i wanted.
<div id="gift-finder">
<div class="gift-finder-form">
<iframe name="inlineframe" src="code.php" frameborder="0"
scrolling="auto" width="200" height="180"
marginwidth="0" marginheight="0" id="gift-iframe">
</iframe>
</div>
This is my iframe code and see src, i used code.php; so all code is in separate place.
Though I had to modify some css, but anyways this is fine.
Thanks everyone who contributed yesterday.

Dynamic select list & PHP array

I want to create a PHP array of a select list. The list have dynamic options, the options are filled with the help of javascript. I want to get all the options on next page.
So I want to create an array of options. Is there any another way to complete this stuff?
Can anybody help me out? Thank you so much in advance.
<script type = "text/javascript">
var val = "";
function removeOptions(selectbox) {
val = selectbox.value;
for (var i = selectbox.options.length-1; i>=1; i--) {
if (selectbox.options[i].selected) {
addOption(document.form1.list2,val,val);
selectbox.remove(i);
document.form1.list1.focus();
}
}
}
function addOption(selectbox,optiontext,optionvalue ){
var optn = document.createElement("OPTION");
optn.text = optiontext;
optn.value = optionvalue;
selectbox.options.add(optn);
}</script>
//list1
<select name="list1" size="7" multiple="multiple" id="jumpMenu" onchange="removeOptions(this)" style="width:200px">
<option>Choose Area...</option>
<?php foreach($dbh->query($sql) as $row){
$a=$row['name'];?>
<option value="<?php echo $a?>"><?php echo $a?></option>
<?php }?>
</select>
//list2
<select name="list2" size="7" multiple="MULTIPLE" id="list2" style="width:170px">
</select>
First: if You want to use multiple with select box, then this selectbox's name have to contain sharp brackets: name="list1[]" and name="list2[]" - this way a PHP will know that this is an array of values.
Second: learn jQuery - though it may seem hard in the beginning it will save You a lot of time and browser-compatibility problems in the future. And jQuery will save Your a*s many times in the future.
For Your purpose I would recommend not just using onchange events but implement additional 4 buttons between the two multiselectboxes that will move the selected options from one to another or all from one to another. This kind of multiselect looks like the one pictured below.
By the first button >> all the options from 1. select are moved to the second one and vice versa with the 4th button <<.
By the second button > only the selected option(s) is(are) moved the second select and vice versa with the third button <.
By this You only catch the click event on the buttons... That is really easy using jQuery...

An error with in the execution of an ajax

I have been a really big fan of stackoverflow(which led me to ask the question here and not anywhere else), anyway, without further ado...
While creating a shop system, I planned to implement an ajax which buys the item on the fly. Now This is how the loop for retrieving items looks like:
<?php
$shop_query = mysql_query("SELECT * FROM sector0_item WHERE 1");
$numrows = mysql_num_rows($shop_query);
While ($shop_fetch = mysql_fetch_array($shop_query)){
?>
<div id="shop_main">
<div class = 'item_img'>
<a><img src = "http://images.wikia.com/dofus/images/4/4e/Discovery_Potion.png" height = '100px'/></a>
</div>
<div class="item_buy">
<a><center>Price: <?php echo number_format($shop_fetch['item_price']);?></center><br /></a>
<a>Quantity: <input type = 'text' size = '9' id = 'itemquantity'/><br /></a>
<a><p>Point requirement: <?php echo number_format($shop_fetch['item_pt_req']);?></p></a>
<a><input type = 'button' id = 'buy' value = 'buy'/></a><span id = 'buy_status'></span>
</div>
<a><h3><?php echo $shop_fetch['item_name'];?></h3></a>
<a><p><?php echo $shop_fetch['item_desc'];?></p></a>
<a>Item Type: <font color = 'green'><?php echo $shop_fetch['item_class'];?></font></a>
</div>
<br />
<?php
}
?>
However, my ajax seems to act really weird. My implementation was to show a loading gif image.
Script:
<script type = 'text/javascript'>
$('#buy').click (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
</script>
The problem is, Only one button shows the circle when clicked. Does the position of the script cause this? Any help is appreciated.
You can only have one item with a given id. When you have multiple elements with the same id, it is indeterminate which one will be returned, but it will usually be the first item only.
If you want multiple buy buttons and want to assign them all the same jQuery event handler, then use a common class name instead of an id.
If you are loading content dynamically and you want event handlers to work for that content, then you need to use delegated event handling.
In jQuery, that is generally done with either .on() or .delegate(). The basic idea is that you pick a static parent object that is not dynamically loaded (perhaps the parent of show_main) and bind the event to that object and then pass the selector of the dynamic element like this (note, I've changed from an id to a class to identify the buy button):
$(staticParentSelector).on('click', '.buyButton', function() {
$(this).closest(".item_buy").find(".buy_status").html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
})
Two things:
It's hard to tell from the sample, but is there an iterator that creates a list of available items? If so, you shouldn't be using IDs which are meant to be unique. If there's really only one #buy then you're fine, though.
When content is updated with Ajax, you're going to lose bindings. Assuming the item related to the #buy button gets replaced with other items, you're better off with a delegated event:
// not in an inline script, but just once, ideally in your main JS file
$(document).ready(function() {
$('#wrapper').on('click', '#buy', (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
})
Where #wrapper is some ancestor higher up in the DOM tree that is never destroyed by the Ajax event.
id is unique value - on html page each id must have unique value. Use class instead.
You need to put your code inside $(document).ready(). So its:
$(document).ready( function() {
$('#buy').click( function(){
// do something here
});
});
Also, you may want to list to jfriend00's advice on IDs.

Allow Users to Select Multiple Options, Aggregate Results and Display

I am having difficulty finding specifically what I'm searching for, most likely because I'm not sure how to express it well in a Google search.
Basically what I would like to do is display 30 or so buttons that users would then be able to select. Once selected a button changes color indicating that the particular option has been chosen. Users are required to select 10 out of 30 options. The results should then be aggregated (basically counting each unique button selected) and displayed to another user who can login and see the results.
Multiple users should be able to select these options and have their results recorded.
I'm not looking to create a drop down list, multi-list, or checkbox solution. In my research so far I have found plenty of references to this type of option. Also, Javascript restricting the min/max number of checkboxes a user can select.
I hope that makes sense. Any assistance with identifying the best method for going about this task would be greatly appreciated.
Thank You,
-Nathan
What you can do, you can create 30 buttons, and connect each button to a hidden check box, then you can post it to server, eg.
<input type="checkbox" value="1" name="chk_one" id="chk_one" style="display: none;">
<input type="button" value="Check Box One" id="btn_one"/>
CSS
input[type="button"].selected { color: red; }
input[type="button"] { color: black; }
then you can write jQuery solution in order to make it change colors:
var _minLength = 10;
var _maxLength = 30;
$(document).ready(function() {
$('#submit_id').click(function() {
if($('#form_id input[type="checkbox"]').is(':checked').length < _minLength)
{
alert('you need to select at least ' + _minLength + ' of buttons'); return false;
};});
$('#form_id input [type="button"]').click(function() {
var _id = $(this).attr('id').toString().split('_')[1];
if(_id != null)
{
var _chckBox = $('#chk_'+_id);
var _newState = _checkBox.attr('checked') ? false, true;
if($('#form_id input[type="checkbox"]').is(':checked').length+1 > _maxLength)
return;
_checkBox.attr('checked', _newState);
if(_checkBox.attr('checked'))
$(this).addClass('selected');
else
$(this).removeClass('selected');
}
});
});
Method from above will attach click event to every button in the area you specified with "#form_id" then when clicked it will toogle state of hidden checkbox and will set or remove class from button, it depends of checkbox state.
And by the way number of checkboxes is not limited.

Categories