get multiple value from select box? - php

I am using this script get by somewhere from internet..
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function sureTransfer(from, to, all) {
if ( from.getElementsByTagName && to.appendChild ) {
while ( getCount(from, !all) > 0 ) {
transfer(from, to, all);
}
}
}
function getCount(target, isSelected) {
var options = target.getElementsByTagName("option");
if ( !isSelected ) {
return options.length;
}
var count = 0;
for ( i = 0; i < options.length; i++ ) {
if ( isSelected && options[i].selected ) {
count++;
}
}
return count;
}
function transfer(from, to, all) {
if ( from.getElementsByTagName && to.appendChild ) {
var options = from.getElementsByTagName("option");
for ( i = 0; i < options.length; i++ ) {
if ( all ) {
to.appendChild(options[i]);
} else {
if ( options[i].selected ) {
to.appendChild(options[i]);
}
}
}
}
}
window.onload = function() {
document.getElementById("src2TargetAll").onclick = function() {
sureTransfer(document.getElementById("source"), document.getElementById("target"), true);
};
document.getElementById("src2Target").onclick = function() {
sureTransfer(document.getElementById("source"), document.getElementById("target"), false);
};
document.getElementById("target2SrcAll").onclick = function() {
sureTransfer(document.getElementById("target"), document.getElementById("source"), true);
};
document.getElementById("target2Src").onclick = function() {
sureTransfer(document.getElementById("target"), document.getElementById("source"), false);
};
}
</script>
</head>
<body>
<table>
<tr>
<td>
<form name="formcheck" method="post" action="target.php">
<select id="source" name="source" multiple>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
</td>
<td>
<input type="button" id="src2TargetAll" name="src2TargetAll" value=">>"/><br/>
<input type="button" id="src2Target" name="src2Target" value=">"/><br/>
<input type="button" id="target2Src" name="target2Src" value="<"/><br/>
<input type="button" id="target2SrcAll" name="target2SrcAll" value="<<"/><br/>
</td>
<td>
<select id="target" name="target" multiple>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
This code creating a two select box which is selected items left to right all code works fine but in php file i am trying to get value by this php code $targets = $_POST['target']; but don't get all value so plz tell me what is the right way to get value of this in php?

Use this
<select id='source' name='source[]' multiple='multiple'>

Give the select element a name ending in [] so that PHP will present it as an array in $_POST/GET/REQUEST.

use this
<select id="source" name="source[]" multiple='multiple'>
it will post a array in server side

Related

Remove / disable selected option[selected from first dropdown] from second dropdown on clicking add button php

index.php
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
function fill_unit_select_box($connect)
{
$output = '';
$query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
}
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
<br />
<h4 align="center">Enter Item Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Enter Item Name</th>
<th>Enter Quantity</th>
<th>Select Unit</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Name at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Quantity at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
insert.php
<?php
//insert.php;
if(isset($_POST["item_name"]))
{
$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
$order_id = uniqid();
for($count = 0; $count < count($_POST["item_name"]); $count++)
{
$query = "INSERT INTO tbl_order_items
(order_id, item_name, item_quantity, item_unit)
VALUES (:order_id, :item_name, :item_quantity, :item_unit)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':order_id' => $order_id,
':item_name' => $_POST["item_name"][$count],
':item_quantity' => $_POST["item_quantity"][$count],
':item_unit' => $_POST["item_unit"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
What I need is:
I don't want to show bags option selected in the first row inside the Select Unit dropdown of the second row.
That is, I want the user to select only one option from the Select Unit dropdown. The selection of the same option from the Select unit dropdown must be restricted.
Have a look at jquery fiddle link: https://jsfiddle.net/fyxog73t/3/
HTML Code:
<div class="row">
<div class="col-md-6">1st Row</div>
<div class="col-md-6">
<select id="select_1">
<option value="">Choose</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">2st Row</div>
<div class="col-md-6">
<select id="select_2">
<option value="">Choose</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">3st Row</div>
<div class="col-md-6">
<select id="select_3">
<option value="">Choose</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
</div>
</div>
JS Code:
$(document).on('change', '[id^="select_"]', function(){
var dropdown_value = $(this).val();
var dropdown_id = $(this).attr('id');
// code to update options from other dropdowns excluding currently selected dropdown
if(dropdown_value != "") {
$('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value='"+dropdown_value+"']").attr('disabled', true);
}
// code to check, if any disabled option is present with it's value not present in other dropdown as selected option. If so then removing disabled option for that dropdown
$('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value!='"+dropdown_value+"']:disabled").each(function(){
dropdown_value = $(this).val();
dropdown_id = $(this).parent().attr('id');
if($('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value='"+dropdown_value+"']:selected").length == 0) {
$(this).removeAttr('disabled');
}
});
});
Had used below steps to achieve the required output:
1) On change method written for each dropdown.
2) In that on change method, disabling other dropdown's option whose value is same as selected option from current dropdown.
3) Then checked, is their any disabled option in other dropdown's(excluding currently selected dropdown). Checking whether that disabled value is present as selected value in other dropdown's or not. If not selected then remove it's disabled attribute.

Check sum values in a select

I need a validation before submitting this form:
<form action="<?php echo $editFormAction; ?>" method="POST" id="form1" name="contract">
<table class="myp-table">
<tr>
<td>Value Test</td>
</tr>
<?php do { ?>
<tr>
<td><select name="playerContract[]">
<option value="0" <?php if (!(strcmp(0, $row_datacontract['playerContract']))) {echo "selected=\"selected\"";} ?>>0</option>
<option value="1" <?php if (!(strcmp(1, $row_datacontract['playerContract']))) {echo "selected=\"selected\"";} ?>>1</option>
<option value="2" <?php if (!(strcmp(2, $row_datacontract['playerContract']))) {echo "selected=\"selected\"";} ?>>2</option>
<option value="3" <?php if (!(strcmp(3, $row_datacontract['playerContract']))) {echo "selected=\"selected\"";} ?>>3</option>
</select></td>
</tr>
<?php } while ($row_datacontract = mysql_fetch_assoc($datacontract)); ?>
<tr>
<td><input class="linkbuttonmp" name="contract" type="submit" value="Invio" /></td></tr>
</table>
</form>
The sum of the values selected by users mustn't exceed the default value which in my case is a value retrieved from my database.
I tried with jquery in this way:
var max = 3;
$("#form1 select").change(function () {
var selects = <?php echo $row_datacoach['coachContract']; ?>;
$("#form1 select").each(function () {
selects = selects + parseInt($(this).val());
});
if(selects >= max) {
$("#submit").attr("disabled","disabled");
} else {
$("#submit").removeAttr("disabled");
}
});
Unfortunately it doesn't work.
Can you help me?
UPDATE
Sorry, I made a mistake: the following is the script I actually tried:
<script type="text/javascript">
var max = <?php echo $row_datacoach['coachContract']; ?>;
$("#form1 select").change(function () {
var selects = 0;
$("#form1 select").each(function () {
selects = selects + parseInt($(this).val());
});
if(selects >= max) {
$("#submit").attr("disabled","disabled");
} else {
$("#submit").removeAttr("disabled");
}
});
</script>
The value fetched from database need to be assigned to variable max and the selects has to be initialized with value 0.
I think it should be
var max = <?php echo $row_datacoach['coachContract']; ?>;
$("#form1 select").change(function () {
var selects = 0;
$("#form1 select").each(function () {
selects = selects + parseInt($(this).val());
});
if(selects >= max) {
$("#submit").attr("disabled","disabled");
} else {
$("#submit").removeAttr("disabled");
}
});
Demo: Fiddle
add ID to form :
<form action="" method="POST" name="contract" id="form1">
then do :
var max = 3;
$("#form1 select").on('change', function () {
var selects = 0;
$("#form1 select").each(function () {
selects += parseInt(this.value, 10);
});
$("#submit").prop('disabled', selects >= max);
});

Show/hide dynamic textbox based on pulldown

I'm trying to figure out how to have jQuery show/hide a dynamically generated textbox based on a pulldown menu selection. My JS skills are extremely limited. I have the following created in a while loop, depending on the number of people:
<select name="location[<?=$pid?>]" id="location[<?=$pid?>]">
<option value="<?=$loc_id?>" selected><?=$loc_name?> </option>
<option value="Other">Other</option>
<option value="Other">--------</option>
<? $query_loc = mysqli_query($link, "SELECT * FROM locations WHERE loc_app = 'Y' ORDER BY loc_name ASC");
while($fetch_loc = mysqli_fetch_array($query_loc)){
$loc_id = $fetch_loc['loc_id'];
$loc_name = $fetch_loc['loc_name'];
?>
<option value="<?=$loc_id?>"><?=$loc_name?></option>
<?
} ?>
</select>
<input name="location_other[<?=$pid?>]" type="text" id="location_other[<?=$pid?>]" style="display:none" />
jQuery function:
<script type='text/javascript'>
$(window).load(function(){
$('#location').change(function () {
if ($(this).val() == "Other") {
$('#location_other').show();
} else {
$('#location_other').hide();
}
});
});
</script>
I need to keep the id of the and the serialized with the $pid variable for later processing. Is there another way to call the jquery function on these?
The HTML output looks like this:
<select name="location[287]" id="location[287]">
<option value="1" selected>A</option>
<option value="Other">Other</option>
<option value="Other">--------</option>
<option value="12">B</option>
<option value="12">C</option>
</select>
<input name="location_other[287]" type="text" id="location_other[287]" style="display:none" />
Try
$(window).load(function(){
$('#location').change(function () {
$('input[id^=location_other]').hide();
if ($(this).val() == "Other") {
$('#location_other').show();
} else {
$('#location_other' + $(this).val()).hide();
}
});
});
Try this
<select name="location[287]" id="location[287]">
<option value="Other">Other</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
<input name="location_other[287]" type="text" id="location_other" style="display:none" />
<script type='text/javascript'>
$(window).load(function() {
if ($('select[id^="location"]').val() == "Other") {
$('#location_other').show();
} else {
$('#location_other').hide();
}
$('select[id^="location"]').change(function() {
if ($(this).val() == "Other") {
$('#location_other').show();
} else {
$('#location_other').hide();
}
});
});
</script>

Control multiple-select box using a single select box using javascript

`<select multiple="multiple" name="state[]" id="state">
<option value="">Select a State</option>
<?php
foreach($state_list as $key=>$value){
echo "<option value=\"$key\"";
if($html['state']==$key|| $row['state']==$key){
echo ' selected="selected"';
}
echo ">$value</option>\n";
}?>
</select> </p>`
<p>Select A Country
<select name="country" id="country">
<option value="0">Select a Country</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select> </p>
I have two select boxes 1)state[] 2) country . What is want is that "If the selected country is not USA, disable the multi-select box which consists all the USA states". Any help is appreciated
Add this Javascript to your code:
<script type="text/javascript">
<!--
window.onload = function() {
var selectCountry = document.getElementById('country');
selectCountry.onchange = function() {
document.getElementById('state').disabled = (selectCountry.value != 'USA')? true : false;
};
};
//-->
</script>
You could do the following if you have jQuery:
$('#country').change(function () {
if($('#country').val() != "USA") {
$('#state').attr('disabled', 'disabled');
}
else {
$('#state').removeAttr('disabled');
}
});
Or if you are using plain JavaScript:
var elem = document.getElementById("country");
elem.onchange = function () {
if(elem.options[e.selectedIndex].value != "USA") {
document.getElementById('state').disabled = "disabled";
}
else {
document.getElementById('state').removeAttribute("disabled");
}
}
This will disable the state combo box when the country combo box contains a value that is not "USA". When the selected country is "USA", it will remove the disabled attribute and make it usable again.
Hope this helps.

populating a select box with javascript

I currently have an auto populating select box depending on what option you select in the first select box. This is all working fine and does the job.
What i am trying to achieve is when the form is submitted it retains the values selected. I can get this working for the first initial select box, but when it comes to the second select box (the one loaded automatically) i cant seem to get it working.
The first select box id is ctlJob with the static information, and the second one has an id of ctlPerson.
Here is my HTML:
<form id="homesearch" action="view.php" method="get">
<label for="ctlJob"></label>
<select name="id" id="ctlJob" style="clear:both; float:left;">
<option value="0">Please Select...</option>
<option <?php if ($_GET['id'] == '1') { ?>selected="true" <?php }; ?>value="1">Regional General Manager</option>
<option <?php if ($_GET['id'] == '2') { ?>selected="true" <?php }; ?>value="2">General Manager</option>
<option <?php if ($_GET['id'] == '3') { ?>selected="true" <?php }; ?>value="3">Deputy General Manager</option>
<option <?php if ($_GET['id'] == '4') { ?>selected="true" <?php }; ?>value="4">Operations Manager</option>
<option <?php if ($_GET['id'] == '5') { ?>selected="true" <?php }; ?>value="5">Shift Manager</option>
<option <?php if ($_GET['id'] == '6') { ?>selected="true" <?php }; ?>value="6">First Line Manager</option>
<option <?php if ($_GET['id'] == '7') { ?>selected="true" <?php }; ?>value="7">Stock Controller</option>
<noscript>
<input type="submit" name="action" value="Load Individuals" />
</noscript>
<select name="person_id" id="ctlPerson" style="clear:both; float:left;">
</select>
<input id="submit" type="submit" name="action" value="search" style="margin-top:40px;" />
</form>
Here is my js:
<script type="text/javascript">
document.getElementById('id').value = "<?php echo $_GET['id'];?>";
document.getElementById('person_id').value = "<?php echo $_GET['person_id'];?>";
</script>
Any ideas on how i can get the secondry select box to stay populated with the option selected after the form has been submitted to itself?
Thanks, Dan
Sorry i missed this js out:
<script type="text/javascript" charset="utf-8">
$(function(){
$("select#ctlJob").change(function(){
$.getJSON("view.php",{id: $(this).val(), ajax: 'true'}, function(data){
var $persons = $("#ctlPerson").empty();
$.each(data, function() {
$persons.append("<option value=" + this.optionValue + ">" + this.optionDisplay + "</option>");
});
})
});
})
</script>
Whatever code you use to populate it (presumably a change event handler), just call it on page load. I do stuff like that with this kind of code:
(elem.onsomething = function() {
// some event-handling code
}).call(elem);

Categories