Multi dynamic combobox populated with mysql - php

Database
$mySql = "SELECT field FROM fields";
$result = mysql_query($mySql);
Html:
<select id="combo1" class="combo" data-index="1">
<option></option>
<?php
while($r = mysql_fetch_array($result))
{
echo "<option value=" .$r['field '] . ">".$r['field '] ."</option>";
}
?>
</select>
<div id="combos"></div>
jQuery
<script type="text/javascript">
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
if (selectedValue !== '' && $(this).find('option').size() > 8) {
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('#combos').append(newComboBox);
}
});
</script>
Questions:
This code is creating comboboxes with my database talble fields.
My problem is that fields cant be repeated when selected once.
Where is the error in the code? Or what am I thiking wrong?
It was supposed to be like that: http://jsfiddle.net/JaVVe/1/

The problem is you are checking size() > 8, so for it work there must be more than 8 options. Change that to size() > 2. Other than that your code will work.
The other problem is you aren't wrapping the option values in quotes. Add quotes:
echo "<option value=\"" .$r['field'] . "\">".$r['field'] ."</option>";
You also have a space after field:
$r['field ']
// ^ here, remove that

on site example is
<option val="Opt1">
In your html it's value attribute instead of val so you need to change
newComboBox.find('option[val="' + selectedValue + '"]').remove();
to
newComboBox.find('option[value="' + selectedValue + '"]').remove();

Related

Get drop down list options based on selected checkbox value

I have the following codes that generate checkboxes from database
< table class="table">
< thead>
< /thead>
< th>
<?php
$oaNamesQuery = "SELECT DISTINCT oaName FROM oaDetails";
$oaNamesQueryExecute = mysqli_query($conn, $oaNamesQuery);
while($oaNamesQueryRow = mysqli_fetch_array($oaNamesQueryExecute)){
$oaName = $oaNamesQueryRow['oaName'];
echo '<div class = "checkbox-group" required style="float:left; margin-right: 25px;"> <input class="checkBoxes" type="checkbox" id="checkBoxArray" name="checkBoxArray[]" value="'.$oaName.'"> '.$oaName.'</div>';
}
?>
< /th>
< /table>
There is another input box as below whereby input type is number
<div class="col-sm">
<label for="numberOfShiftPerDay">Number</label>
<input type="number" class="form-control" id="numberOfShiftPerDay" name="numberOfShiftPerDay" placeholder="No: " onchange="disablingRoutine()" min="1" max="4">
</div>
Example UI as below
When I enter some number, there will be a drop down menu appear according to the number I entered. Eg: If keyed in 1, there will be one drop down list will appear as below using jQuery 'OnChange'. The UI will be as below
What I Need
I need the drop down menu options to be based on user selected checkboxes. Eg: If the user selected checkboxes X, Y and XX, then these drop down list should show X, Y and XX. Can someone help me how to do this?
Edit 1
Added Javascript function on the change routine as suggested by stackoverflow member. But now having duplicate issues. Below the code that I changed
if ($("#numberOfShiftPerDay").val() == 1) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift1').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 2) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift2').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 3) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift3').append('<option>' + cval + '</option>')
});
} else {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift4').append('<option>' + cval + '</option>')
});
}
You can get the selected checkbox values and append to your dropdown list in your onchange function.
Try this:
function disablingRoutine()
{
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
$('#dropdownID').append('<option>'+cval+'</option>')
});
}
Edit 2
function disablingRoutine()
{
cdata = '';
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
cdata += '<option>'+cval+'</option>';
});
$('#dropdownID').html(cdata)
}

Is there any way that the first character of a text box is either '+' or '-' by default

I have a text field on my form actually its like GMT time. I want the users to
enter integers like '+5' '+6' or '-6' or '-5' etc.
I want to make it easy for users so that they don't have to write '+' or '-' by there self. There should be by default option of '+' or '-' as first character in text field.
I saw some solutions like making a simple drop down in front and user can select from there which will automatically appear in text box.
But i want to make it more easy if some other easy solution is there.
will prefer using HTML5 but if not than jquery will be fine..
Try this one:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var num = 0;
$('#txt1').keydown(function(e){
num += 1;
if (e.keyCode > 36 && e.keyCode < 41) {
if(num % 2){
$('#txt1').val('+');
}else{
$('#txt1').val('-');
}
}
});
});
</script>
<input type="text" name="txt1" id="txt1" />
you could try this:
var $input = $('#input');
var defaultChar = '+';
$input.val(defaultChar);
$input.on('keyup', function(event) {
var $this = $(this);
var currentText = $this.val();
currentText = getDigits(currentText);
$this.val(defaultChar + currentText);
});
function getDigits(text) {
var digits = text.match(/[+-]?(\d*)/);
console.log("text = " + text);
console.log("digits = " + JSON.stringify(digits));
if(digits.length > 1) {
return digits[1];
} else {
return 'did not contain numbers';
}
}
here is the fiddle
EDIT: added dropdown to select defaultChar.
Javascript:
var $input = $('#input');
var $defaultCharElem = $('#defaultChar');
var defaultChar = $defaultCharElem.val();
$input.val(defaultChar);
$defaultCharElem.on('change', function() {
var $this = $(this);
defaultChar = $this.val();
$input.val(defaultChar + getDigits($input.val()));
});
$input.on('keyup', function(event) {
var $this = $(this);
var currentText = $this.val();
currentText = getDigits(currentText);
$this.val(defaultChar + currentText);
});
function getDigits(text) {
var digits = text.match(/[+-]?(\d*)/);
console.log("text = " + text);
console.log("digits = " + JSON.stringify(digits));
if(digits.length > 1) {
return digits[1];
} else {
return 'did not contain numbers';
}
}
HTML:
<select id="defaultChar">
<option value="+">+</option>
<option value="-">-</option>
</select>
<input type="text" id="input" value="" />
Here is the new fiddle

Insert PHP code in JQuery

Good day every one. I want to insert my php code in my jquery. I want to show my data in database using PHP and I want to put it in a option box. I used var in jquery plus the code of my php but isn't working. Please help me.
Shows the data:
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
while ($result2 = mysql_fetch_assoc($res)){
$name = $result2["name"];
?>
jquery code(dynamic adding text box)
var nitem =0;
var ntotal = 0;
var option = <?php echo" <option value='$name'>$name</option>";} ?>;
function totalItemExpence(){
ntotal = 0;
$('.expense_cost').each(function(){
if($(this).val() != ""){
ntotal += parseFloat($(this).val());
}
});
//$('#total').val(ntotal);
}
$(document).on('change keyup paste', '.expense_cost', function() {
totalItemExpence();
mytotal();
});
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'<select class="expense_name" id="' + nitem '">"'+ option +'"</select>' +
'<input class="expense_desc" placeholder="Expense Description" id="' + nitem + '" required/>' +
'<input class="expense_cost" onkeypress="return isNumber(event)" placeholder="Expense Cost" id="' + nitem + '" required/> ' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem + " .expense_cost").each(function(){
if($(this).val() != ""){
ntotal -= parseFloat($(this).val());
}
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
Try this for while loop :
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
$options = '';
while ($result2 = mysql_fetch_assoc($res)){
$options .= "<option value='{$result2["name"]}'>{$result2["name"]}</option>";
}
?>
And JS part :
...
var option = "<?php echo $options; ?>";
...
This line:
var option = "<?php echo "<option value='$name'>$name</option>"; ?>";
must be in your .php file, because php code won't be executed in a .js file (that's why it's called .php)...
You can wrap that line in a <style> tag in your .php file
Also, don't forget to add these things --> "
And to remove this one --> }

Retrieve HTML drop down list value with AJAX

I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<script type="text/javascript">
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];

How to call/activate the 2nd select list only after 1st select list was selected?

I have the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,

Categories