Writing Conditional Drop Downs to MySQL - javascript

Hopefully this isn't too confusing..
I have a conditional form that has the user select a category, based on that category they'll need to choose from that category's sub categories. This works fine.
However, my issue is when writing to MySQL the Value that's inserted in my Sub Category column is always the last Select group's first Value (in this case it's "sandwich"). Example..
My Main Categories: Starters | Supper | Sandwiches
Starters' Sub Categories: Coastal or Southern
Supper's Sub Categories: Smokehouse or Specialties
Sanwiches' Sub Categories: Sandwich or Po-Boy
No matter which Category/Sub Category you select, it always writes the "Sandwich" subcategory in MySQL. Make sense?
So here's my code & JSFiddle if you want to play with the dropdowns. http://jsfiddle.net/kkobayashi/5f5tw4t0/
PHP to MySQL
<?php
if( isset( $_POST['create'] ) ):
$cat = $_POST['cat'];
$catsubs = $_POST['subcategory'];
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
mysql_query("INSERT INTO leDB (cat,subcategory)
VALUES('$cat','$catsubs')")
or die(mysql_error());
echo "Success."; /** success message **/
endif;
?>
HTML
<form action="" method="POST">
<!-- MAIN CATS -->
<select id="mainCat" class="source" name="cat">
<option value="starters">Starters</option>
<option value="supper">Supper</option>
<option value="sandwiches">Sandwiches</option>
</select>
<!-- SUB CATS -->
<div id="cat_starters" class="subcategory" style="display:inline;">
<select class="" id="starters" name="subcategory">
<option value="coastal">Coastal</option>
<option value="southern">Southern</option>
</select>
</div>
<div id="cat_supper" class="subcategory hidden">
<select class="" id="supper" name="subcategory">
<option value="smokehouse">Smokehouse</option>
<option value="specialties">Specialties</option>
</select>
</div>
<div id="cat_sandwiches" class="subcategory hidden">
<select class="" id="sandwiches" name="subcategory">
<option value="sandwich">Sandwich</option>
<option value="poboy">Po-Boys</option>
</select>
</div>
</form>
JS
// Conditional Drop Down
$(document).ready(function(){
$('#mainCat').on('change', function() {
// Setting this variable to add inline
var inline = document.querySelector('#cat_' + $(this).val() );
// Show/Hide
$('div.subcategory').hide();
$('#cat_' + $(this).val() ).show();
inline.style.display = "inline";
});
});
A little CSS
div.hidden {
display: none;
}
Don't know how well of a job I did describing the issue, if you're confused feel free to yell at me. Thanks y'all.

Hiding the select does not actually remove it from the DOM, as you would see if you would check the source. It only hides it from the user.
This means that every select with the same name attribute will override the last one, hence why you only get the last one.
an easy fix could be to add the name attribute to the correct select.
$(document).ready(function(){
$('#mainCat').on('change', function() {
// Setting this variable to add inline
var inline = document.querySelector('#cat_' + $(this).val() );
// Show/Hide
$('div.subcategory').hide().attr('name', '');
$('#cat_' + $(this).val() ).show().attr('name', 'subcategory');
inline.style.display = "inline";
});
});

you need to add unique names to your selects.
For example for starters, add name="starters". Add names as the option values of the category.
And after that, use: $catsubs = $_POST[$cat];

Change the subcategory names to maybe subcategory1, ...2 and ....3 or just make them unique in the form
You need the names to be unique. The reason you end up with the same sandwich no matter what you select is because you are using the same name. When the $_POST data is sent, it sends an array with the key equal to the name in the form. So to know exactly what a user clicked, selected or typed, each name must be unique

Related

Multiple Select Option in html while getting data from databse

I have to run a mysql query and make Select option to select the given data in my HTML form.
The issue is No of select option. Because I have to Select option on the basis of item quantity. For example I have one pizza and three drinks. then I need to open 1 select option for pizza and three select option for dirnks.
Here is my CODE:-
<select class="form-control" name="dealSizeName[]" id="dealSizeName">
<?php
$sql3 = mysql_query("SELECT * From `dealsubcategories` WHERE `Status` ='Y'");
while($row3 = mysql_fetch_array($sql3)) { ?>
<option value="<?=$row3['SizeName']." ".$row3['SubCategoryName']?>">
<?=$row3['SubCategoryName']?>
</option>
<?php } ?>
</select>
I have the following Table in my Database:
and I want to make select optoin in my html form like this:
If in DealA, qty of Pizza is 2 than open two select otion. For burger open 1, for Drink open 3 and for pasta open 1 select option box in my html form.
But I am getting one select option for all every time. How to make it dependable on qty filed of my table.
There is an attribute multiple for the select element which helps you choose multiple options.
Since I do not have any knowledge in PHP I will be adding html comments in what you should do in php. This is the basic gist that you should try.
<?php
$sql3 = mysql_query("SELECT * From `dealsubcategories` WHERE `Status` ='Y'");
<!-- for index = 0;index < subCategory.quantity; index ++ -->
<select class="form-control" name="dealSizeName[]" id="dealSizeName" multiple>
while($row3 = mysql_fetch_array($sql3)) { ?>
<option value="<?=$row3['SizeName']." ".$row3['SubCategoryName']?>"> <?=$row3['SubCategoryName']?></option>
</select>
<?php }?>

How keep the selected value for dropdown after submit using javascript

How do I keep the selected item after page refreshed ,i have a language in the multiple select,
i am try now this with java script here is my code its not working ,can any one guide me how to make it selected
my html code
<div class="control-group">
<label for="textfield" class="control-label">Language</label>
<div class="controls">
<select name="myLanguage" id="myLanguage" multiple="multiple">
<option value="English,">English,</option>
<option value="Arabic,">Arabic,</option>
<option value="Hindi,">Hindi,</option>
<option value="Malayalam,">Malayalam,</option>
<option value="Danish,">Danish,</option>
</select>
</div>
</div>
javascript
document.getElementById('myLanguage').value = "<?php echo $_GET['language'];?>";
If you use jQuery use this:
$(document).ready(function(){
$('#myLanguage').val("<?php echo $_GET['language'];?>");
});
Javascript doesn't use a session variables, so adding the value to the session isnt possible. Still you can do two things:
Option 1:
Add the value to a cookie with Jquery:
Set: $.cookie("test", 1);
Read: var value = $.cookie("test");
See more: How do I set/unset cookie with jQuery?
Option 2:
Post the value to the new page and request on that one:
Reading the value can be done with :
Read: $_REQUEST["my_variable"];
Note: reading value can be done like:
$("#myLanguage option:selected").text();
If you're using HTML5 as your doctype you can easily store values in the localStorage.
Reference: http://www.w3schools.com/html/html5_webstorage.asp
To set it:
localStorage.setItem("variable_name", variable_value);
To get it:
localStorage.variable_name
To remove it:
localStorage.removeItem("variable_name");
You can also use js cookies with jquery.cookie plugin, if you prefer.
As mentioned in the comments, when using the multiple attribute,
the name attribute must be an array such as:
<div class="control-group">
<label for="myLanguage[]" class="control-label">Language</label>
<div class="controls">
<select name="myLanguage[]" multiple="multiple">
<option value="English,">English,</option>
<option value="Arabic,">Arabic,</option>
<option value="Hindi,">Hindi,</option>
<option value="Malayalam,">Malayalam,</option>
<option value="Danish,">Danish,</option>
</select>
</div>
</div>
javascript // Note: I'm not so sure on the following syntax
var myLanguage[] = document.elements('myLanguage[]').value;
<?php
$languages = array(
'en' => 'english',
'vi' => 'vietnamese',
'cn' => 'chinese'
);
if (isset($_GET['lang']) AND array_key_exists($_GET['lang'], $languages))
{
include './lang/' . $languages[$_GET['lang']] . '.php';
}
else
{
include './lang/english.php';
}
?>

Add/Removing Options with JQuery

I'd like to add and remove options from one drop down menu using JQuery given a selected option in another.
HTML:
<form action='quickLook.py' method = 'post'>
First DropDown Menu
Specify Channel:
<select id='bolometer'>
<option selected id='Dual' value = 'Dual' >Dual
<option id='Top' value = 'Top' >Top
<option id='Bottom' value = 'Bottom' >Bottom
</select>
Second DropDown Menu
<br>Specify Data to Display:
<select id='target'>
<option selected id='Spectrum' value = 'Spectrum'>Spectrum
<option id='Interferogram' value = 'Interferogram'>Interferogram
<option id='SNR' value = 'SNR'>SNR
<option id='Diff_Band' value = 'Diff_Band'> Diff_Band
</select>
<input type='submit' value= 'Query Images'>
</form>
I'd like to do something like this is JQuery:
$("#Dual").click(function() {
$("#target").append("#Diff_Band");
$("#target").remove("#Interferogram");
$("#target").remove("#SNR");
});
$("#Top").click(function() {
$("#target").append("#Interferogram");
$("#target").append("#SNR");
$("#Diff_Band").remove();
});
I want to append or remove the already written html.
What is the best way to do this?
Thank you for your time!
This is a similar problem I've encountered before working with Safari. A solution is to use .detach() instead of remove() as it keeps all jQuery data associated with the removed elements. Check this jsfiddle: http://jsfiddle.net/Ueu62/

Passing value of select menu to variable

Hello I am using the following procedure to get information from drop down menu:
$('select[name=status]').change(function(){
selectstatus = $("select[name=status]").val();
Currently it is getting information from the drop down menu with name=status. In case if I have more than one drop down menus with that name the script is not working correctly. It is working only for the first select menu that appears and for the rest is not selecting anything inside the variable selectstatus, how to modify the code that it will work with any select menu it doesn't matter what name it have.
<?php echo "<select name='status' id='$ids' idc='$idc'>" ?>
<option value="">Opcion:</option>
<option value="aprobado">Aprobado</option>
<option value="cupolleno">Cupo Lleno</option>
<option value="cancelado">Curso Cancelado</option>
<option value="noacion">No Acion</option>
</select>
With $(this):
selectstatus = $(this).val();
I would add a class to make it easy to target every select that you want this handler on.
<?php echo "<select name='status' class='getstatus' id='$ids' idc='$idc'>" ?>
<option value="">Opcion:</option>
<option value="aprobado">Aprobado</option>
<option value="cupolleno">Cupo Lleno</option>
<option value="cancelado">Curso Cancelado</option>
<option value="noacion">No Acion</option>
</select>
Then use the class name as the selector. Use $(this) to reference the select that fired the change event.
$('.getstatus').change(function(){
var selectstatus = $(this).val();
});
Use $(this)
$('select[name=status]').change(function(){
selectstatus = $(this).val();
});

Drop down product, put price in text field

I need to create a simple drop-down menu with 5 items (widget1, widget2, widget3, etc..) and a corresponding value which is the price. When the user clicks the 'Price button' after selecting the widget, I need the price to show up in the text box. This is what I've pulled from other snippets, but can't figure out the second part after the 'var x' to insert it into the text area.
function displayResult()
{
var x=document.getElementById("dropdown").value;
}
And the html...
<form action="">
<select id="dropdown" >
<option value="$1">widget1</option>
<option value="$2">widget2</option>
<option value="$3">widget3</option>
<option value="$4">widget4</option>
</select>
<button type="button" onclick="displayResult()">Price</button>
</form>
<textarea = id="showprice" size="10" maxlength="10"></textarea>
Most of the examples I've found change the text box after the drop down is selected, I need it work after the button is clicked. Thanks
You're so close already. Just reverse the process you used to get the value but use the id of the textbox and set its value property:
function displayResult() {
var x=document.getElementById("dropdown").value;
document.getElementById("showprice").value = x;
}
If that is the only thing that displayResult() does you don't need the x variable:
document.getElementById("showprice").value = document.getElementById("dropdown").value;

Categories