Complicated AJAX update with two select elements - html

I have a form with two select elements where users can select a product variant (for example red, green, blue shirt) and the quantity.
When changing the variant/quantity, I do a AJAX request to get the price.
The complicated part is: each variation has its own price and its own quantities. For example red shirts are 10 USD and at a minimum quantity of 5 (10, 15…). Green shirts are 15 USD but quantity starts at 3 (6, 9…).
(Color/shirt just an example, real products are control units for streetlights :-)
The problem is, when the default is 'red' and '5' and I change to 'green' the price shows 75 USD (AJAX query was green+5). But green only has quantities of 3, 6, 9 etc.
I could return the minimum quantity from my AJAX request, but then the user can't update the price when changing the quantity select.
Only solution I see is make two doSubmit() functions and two submitAjax(). But this would mean I have a lot of duplicate code.
HTML
<form action="" id="product_selection">
<select name="product_variation">
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>
<select name="product_quantity">
<option value="">10</option>
<option value="">20</option>
<option value="">30</option>
</select>
</form>
JavaScript
// Product variation, quantity select dropdown
var product_selection = document.querySelector('#product_selection');
var product_variation = document.querySelector('#product_variation');
var product_quantity = document.querySelector('#product_quantity');
// Event listener to submit the form on change
product_selection.addEventListener('submit', submitAjax);
product_variation.addEventListener('change', doSubmit);
product_quantity.addEventListener('change', doSubmit);
// Submit form
function doSubmit(event) {
product_selection.dispatchEvent(new Event('submit')); // product_selection.submit();
}
// Handle ajax submit
function submitAjax(event) {
// Stop default form submit
event.preventDefault();
// Ajax request
$.ajax({
url: '/static/public/ajax/get_product_data.php',
type: 'POST',
data: $('#product_selection').serialize(),
success: function(result) {
if (result == 0) {
alert('Sorry');
} else {
setProductData(result);
}
},
error: function(jqxhr, status, exception) {
alert('Sorry');
}
})
}
// Update product details
function setProductData(result) {
$('#product_price').html(result.price_gross);
// Remove current quantity options
var product_quantity = document.getElementById("product_quantity");
for(i = product_quantity.options.length - 1 ; i >= 0 ; i--) {
product_quantity.remove(i);
}
// … reapply new quantity options
var c = 0;
for (var i = result.minimum; i <= result.maximum; i+=result.graduation) {
product_quantity.options[c] = new Option(i + ' ' + pwjs.product.unit, i);
if (result.product_quantity == i) {
var setselectedIndex = c;
}
c++;
}
// product_quantity.selectedIndex = setselectedIndex;
}

I think you would want to do this in steps so product_variation.addEventListener('change', doSomethingElse);
then your select would be something like:
<select name="product_variation">
<option data-increment="5" value="r">Red</option>
<option value="g">Green</option>
<option data-increment="3" value="b">Blue</option>
</select>
then when the product_variation changes doSomethingElse would rebuild the product_quantity select to take the increment value of the selected product_variation

As far I can see, you are using jQuery. So, Ill give you an example of how you can achieve this.
HTML
First of all, don't forget to specify the values for your select options, your values for product_quantity were empty. Also, I'd recommend to you that you create an extra option tag to be the default selected option and be able to validate your form later on.
<form action="" id="product_selection" name="product_selection">
<select name="product_variation">
<option value="">Select color</option>
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>
<select name="product_quantity">
<option value="">Select quantity</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
JavaScript
As for JavaScript, I'll recommend you to add the event listener for your last input, which is the product_quantity.
$("#product_selection").submit(function(e){
e.preventDefault();
var inputs = document.product_selection;
if( inputs.product_variation.value != "" && inputs.product_quantity.value != "" ){
$.ajax({
url: '/static/public/ajax/get_product_data.php',
type: 'POST',
data: $('#product_selection').serialize(),
success: function(result) {
if (result == 0) {
alert('Sorry');
} else {
setProductData(result);
}
},
error: function(jqxhr, status, exception) {
alert('Sorry');
}
});
}
});

Related

issue with set autoselect value in multiple select box with jquery

I am using skote theme and I want to set auto select value in multiple select select box when edit data I have get this multiple select box from this this for that I am trying below code
<select class="select2 form-control select2-multiple" name="assign_to[]" multiple="multiple" data-placeholder="Choose ...">
<option value="1" data-select2-id="1">Admin</option>
<option value="2" data-select2-id="2">Admin2</option>
<option value="3" data-select2-id="3">Admin3</option>
</select>
$(document).on('click','.edittodotask',function(e){
e.preventDefault();
var id = $(this).attr('id').replace('edittodotask_', '');
var url = "{{route('task_to_do.edit', ':id')}}";
url = url.replace(":id", id);
$.ajax({
type: "get",
url: url,
processData: false,
contentType: false,
success: function(response) {
//response = assign_to: "1, 2"
var assign_to = response.assign_to.split(',');
$("#edit_assign_to").val(assign_to);
},
error: function(data) {
console.log(data);
}
})
});
when I click on edit button I have get data with ajax and want to set auto select options for that I have make this code
but it is not set selected value.
can anybody help me with this
Using select2, you need to trigger the changes manually.
$("#edit_assign_to").val(response.assign_to.split(',')).trigger('change.select2');
If your data returns 1, 2 with a comma, you need to split by , with a space after the comma.

Return Selected Item Value

So I have this select block in my code:
<select id="mS" name="mealSelection" onselect="">
<optgroup label="Generell">
<option selected label="Alles" value="0" />
</optgroup>
#{
List<List<string>> kategorien = new List<List<string>>();
List<List<int>> catIDs = new List<List<int>>();
while (reader.Read())
{
if (reader["TopKategorie"].ToString().Equals(""))
{
List<string> nextList = new List<string>();
nextList.Add(reader["Bezeichnung"].ToString());
kategorien.Add(nextList);
List<int> nextCatList = new List<int>();
nextCatList.Add(Int32.Parse(reader["ID"].ToString()));
catIDs.Add(nextCatList);
}
else
{
int lastPos = kategorien.Count - 1;
kategorien[lastPos].Add(reader["Bezeichnung"].ToString());
catIDs[lastPos].Add(Int32.Parse(reader["ID"].ToString()));
}
}
for (int i = 0; i < kategorien.Count; i++)
{
<optgroup label=#kategorien[i][0]>
#for (int j = 1; j < kategorien[i].Count; j++)
{
<option label=#kategorien[i][j] value=#catIDs[i][j] />
}
</optgroup>
}
}
</select>
Short explanation: Our professor gave us the task to create a web application in which you can order food. This list is meant to filter the food by category (e.g. Asian, fast food etc.) I used a two dimensional List, because the categories are all separated in "top-categories" like snack, dessert, and so on.
I now need a button that links to a url containing the value of the selected option as parameter. However, my professor specifically demanded to use "select", "optgroup" and "option" and I haven't worked with controllers yet. Any help is appreciated.
Just use a script to get the new value. Because you getting it on the fly it will have to be a client side language. (Like Jquery or Javascript)
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var selected-val = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + selected-val;
}
</script>
Once you have the value you can do whatever it is you want to do with the info. :)

yii2 get label of optgroup when submit

I have a select box:
<select id="issue-users_id" class="form-control" name="Issue[users_id]">
<optgroup label="user">
<option value="16">user</option>
<option value="24">robo</option>
</optgroup>
<optgroup label="group">
<option value="15">123123</option>
</optgroup>
</select>
when submit form I want to have array like this:
Issue[users_id][user] = value (16, 24)
or Issue[users_id][group] = value (15)
it means I want to get value of optgroup
All is possible is manualy prepare data and send it to server. On submit get form data and replace Issue.user_id param:
var selected = $('#issue-users_id').find(":selected"),
optgroup = selected.closest('optgroup');
if ( optgroup.attr('label') == 'group' ) {
form_data.Issue.users_id = {
group: selected.val()
}
} else {
form_data.Issue.users_id = {
user: selected.val()
}
}
$.ajax(/* send form */);
You can retrieve group through user id. User id is unique and can belong to one or more groups, so you can create method for this in according model, for example:
public function getGroup()
{
// return group name string here based on $this->id
}
Getting the value of optgroup from $_POST array is illogical.

HTML tags to allow user to select multiple items and set their order

I have this input to allow user to select (with multiple choices) a product:
<select multiple="yes" name="products[]">
<option value="wood">Wood</option>
<option value="iron">Iron</option>
<option value="gold">Gold</option>
<option value="dust">Dust</option>
<option value="food">Food</option>
</select>
User can select several stuff in that list, and I can get in server-side using, for instance, PHP:
$_GET['products'] ← array('wood', 'iron', 'food');
Now, I would like to allow users to specify an order for the selection they made. So, I want the user to be able to not only set the list of items to select (like a <select multiple="yes">) but also in which order I will treat them.
In other words, let's say a user want the list to be ordered to:
$_GET['products'] ← array('gold', 'iron', 'wood', 'dust');
Currently, using the <select multiple="yes"> I can only ask user to unorderedly pick up items from a list but
what's the HTML tags I should use to allow user to select multiple options and specify its order?
I don't want to sort the options inside the <select>, I want the user to be able to tell the server in which order it should treat the selected items list.
I picked PHP example as server-side treating code (and it's the language I will use) but actually, the answer should not rely on server side language: I'm looking for the "html-client-side" code to use.
The following answer isn't exactly elegant but it get's the job done. I havn't been doing Web development long but I'm learning.
The JavaScript could be better as I'm used to jQuery (crutch I know).
Pure js (easier if you can use jQuery)
var products = [];
function add(val) {
if (!contains(products, val))
{
products.push(val);
document.getElementById('list').setAttribute('name', products);
}
}
// checks if arr 'a' has the element 'obj'
// thanks to someone at stack overflow for how to do that :)
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
html
// add the onclick='add()' function to your html
<select id='list' multiple="yes" name="" value='heyo'>
<option onclick='add("wood")' value="wood">Wood</option>
<option onClick='add("iron")' value="iron">Iron</option>
<option onClick='add("gold")' value="gold">Gold</option>
<option onClick='add("dust")' value="dust">Dust</option>
<option onClick='add("food")' value="food">Food</option>
</select>
Working jsfiddle here: http://jsfiddle.net/TcGt5/
<!-- language: lang-js -->
<script>
var jproducts = [];
var selectCount= 0;
function myFunction() {
var select = document.getElementById("mySelect");
// test if select value already exist
options = select.getElementsByTagName('option'),
for (var i=options.length; i--;) {
if (options[i].selected)
selectCount +=1;
if (function 'is_not_in_products_array')
jproducts.push(options[i].value)
}
// remove unselected products
for (var j=0; j< (jproducts.length-selectCount); j++;)
jproducts.shift();
}
</script>
Finnaly the products array will containt only the last selected
<select id="myselect" multiple="yes" name="products[]" onchange="myFunction()">
<option value="wood">Wood</option>
<option value="iron">Iron</option>
<option value="gold">Gold</option>
<option value="dust">Dust</option>
<option value="food">Food</option>

change the value of a select tag using jquery

I am working on a wordpress site. I have an html with select tag and some options. When the form is submitted, I want to replace the value of option 'Other' with this value 'Rosemont' if option 'Other' is selected. Below is my html.
<select class="expand" name="field_19" id="field_19">
<option value="Bryn Mawr">Bryn Mawr</option>
<option value="Devon">Devon</option>
<option value="Gladwyne">Gladwyne</option>
<option value="Haverford">Haverford</option>
<option value="Other">Other</option>
</select>
Now I want that if the option 'Other' is selected then the selected value should be changed to text 'Rosemont'. So that the value 'Rosemont' should be saved into the database instead of 'Other'. I have written some jquery code but its not working.
Here is my code
jQuery(function(){
jQuery('#signup_submit').click(function(){
var city_name = jQuery('select[name="field_19"]').val();
alert(city_name)// this alerts 'Other'
if(city_name=='Other'){
valr = 'Rosemont';
jQuery('select[name="field_19"]').val(valr);
var vals = jQuery('select[name="field_19"]').val();
alert(vals);// again this alerts 'Other'. this should alert Rosemont
}
});
Something like this? jsBin demo
jQuery(function($) {
$('#signup_submit').click(function(e){
e.preventDefault();
var $f19 = $('select[name="field_19"]');
var f19Val = $f19.val();
if(f19Val=='Other'){
var $oth = $('[value=Other]',$f19);
var newVal = "Rosemont";
$oth.val(newVal).text(newVal);
}
});
});