Html multiple select options to shopping cart via javascript - javascript

My fiddle : https://jsfiddle.net/o39chw9x/
I have multiple select boxes in my html like this:
<select class=".form-bestel.select" name="product">
<option value="0">Melk, vol (0,5l)</option>
<option value="1">Melk, vol (1l) </option>
<option value="2">Melk, mager (1l) </option>
</select>
<select class=".form-bestel.select" name="product">
<option value="3">Boter (250g)</option>
<option value="4">Boter (500g)</option>
<option value="5">Boter (1kg)</option>
<option value="6">Kruidenboter (125g)</option>
<option value="7">Kruidenboter (1kg)</option>
</select>
under each select box is a input field for the amount:
<input class=".form-bestel" name="amount" id="amount" placeholder="Aantal" type="number" min="0" style="width: 100%;heigt:100%;margin-bottom: 5px;"> </input>
under that input field is a button:
Voeg toe
That button is connected with javascript. When it's clicked following function runs:
addToCartBtn.on('click', function(event){
event.preventDefault();
addToCart($(this));
});
then:
function addToCart(trigger) {
var cartIsEmpty = cartWrapper.hasClass('empty');
//update cart product list
addProduct();
//update number of items
updateCartCount(cartIsEmpty);
//update total price
updateCartTotal(trigger.data('price'), true);
//show cart
cartWrapper.removeClass('empty');
}
then:
function addProduct() {
//var productid = document.getElementById('product').value;
var productid = 4;
var product = products[productid];
var price = prices[document.getElementById('product').value];
var amount = document.getElementById('amount').value;
}
NOTE: I know there are no id's product or amount in the html. That's my problem:
How can i get the chosen value from 2 or more different html select boxes if i can't give them a same id. How can I best pass it through the first js-function I call?
What I want to get is, when i select the right thing and press on the button "Voeg toe" it appears in my shopping cart. So the JS function need to know which one I selected and what the integer was in the input..

This is a common pattern for repeating components within a page.
Your demo is filled with a lot of irrelevant code so I will show you a simplified case
You want to isolate the product instance using a traverse up fom the button, and them look inside that instance for the input values
$('.cd-add-to-cart').on('click', function(e){
// isolate instance
var $row = $(this).parent(),
// look inside instance for values
qty = $row.find('input').val(),
type = $row.find('select').val();
// do something with these values
});

Related

Not able to set multiple values in select2 dropdown after page load

I am using select2 box for language selection. I am not able set selected values for edit language page
I tried to set manually all the values from array to select2
$(window).bind("load", function() {
$('#language').select2(); //key , value pair of language map
var value = $('#langList').val(); // hidden list of id "[3,1,7]" value
var result = value.substring(1, value.length-1);
var res = result.split(","); // array of ids
$('#language').val([res[0],res[1],res[2]]);
$('#language').trigger('change');
});
Wanted to set all the values to select2. Please find html code below:
<label for="language">Work Language:</label>
<input type='hidden' value="${languageList}" id="langList"/>
<select name="language" id="language" multiple="multiple">
<c:forEach items="${languageMap}" var="lang">
<option value="${lang.key}">${lang.value}</option>
</c:forEach>
</select>

Filter Drop down list by another drop down list Id ASP.Net

HI I have a issue with filtering one drop down list with another drop down list,
in my search.cshtml file I have added
#{
List<FormCategory> formCategories = ViewBag.formCategories;
List<Form> forms = ViewBag.forms;
List<UsersVM> users = ViewBag.Users;
List<FormSearchResultsVM> results = ViewBag.Results;
}
<select id="selFormCategories" class="sc-select sc-input" onchange="onFormCategoriesChanged(this)">
<option id="0"></option>
#foreach (var formCat in formCategories)
{
<option value="#formCat.ID">#formCat.Name</option>
}
</select>
<select id="selForms" class="sc-select sc-input" onchange="onFormsChanged(this)">
<option id="0"></option>
#foreach (var form in forms)
{
<option value="#form.ID">#form.Name</option>
}
</select>
I need to filter selForms dropdown when selFormCategories onchnage event...
function onFormCategoriesChanged(sel) {
selectedFormCategory = $(sel).find(':selected').attr('value');
}
Thanks
Here's one way I could think of. First, we should store the option elements to a jquery object array then filter that array for display whenever a select is changed.
Data attributes (data-property, data-name, etc) is used for filtering.
In my example below, whenever the vehicle select is changed, it will clear and refill the brands select with corresponding brands from that vehicle type.
$(document).ready(function(){
var vehicleList = [];
var brandsList = [];
// store brands options to variable on document ready
$("#brands option").each(function(){
brandsList.push($(this));
});
// clear brands select to hide option fields
$("#brands").html("");
// vehicle select on change, refill brands with matching data-vehicle value
$("#vehicle").change(function(){
var brandsSelect = $("#brands");
var vehicleValue = $(this).val();
brandsSelect.html("");
brandsSelect.show();
$(brandsList).each(function(){
if($(this).data("vehicle") == vehicleValue){
$(brandsSelect).append($(this));
}
});
});
});
<html>
<body>
<h5>Select a Vehicle Type</h5>
<select id="vehicle">
<option>Motorcycle</option>
<option>Car</option>
</select>
<h5>Choose Brand</h5>
<select id="brands" hidden>
<option data-vehicle="Motorcycle">Yamaha</option>
<option data-vehicle="Motorcycle">Kawasaki</option>
<option data-vehicle="Car">Mercedes Benz</option>
<option data-vehicle="Car">BMW</option>
<option data-vehicle="Car">Audi</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>

How to count option values from different select options?

I have searched the web for answers and find none that I needed. So to the question. I am making a submit form (user selects fields and types an input number to determine the price of an order) which have 2 different select option fields and 1 input field.
<input type="text" id="number" placeholder="please enter a number">
(user entered 35 for example)</input>
<select id="firstpick">
<option value="50">Option 1</option>
<option value="150">Option 2</option>
<option value="100">Option 3</option>
</select>
<select id="secondpick">
<option value="10">Option 4</option>
<option value="15">Option 5</option>
<option value="20">Option 6</option>
</select>
<input disabled="disabled" type="text">(The total sum)</input>
I want to count sum of values for example: firstpick.option3 + (secondpick.option4 * number.35). In other meaning: 100 + (10 * 35) = 450. And I want to get that sum in a different disabled input field, so I can save it in database and show it to the user what is the total cost of an order by fields he selected and by number he typed in.
EDIT: The working code for you (the visitor)! http://jsfiddle.net/LoLd748n/4/
I am not entirely sure what you goal is, but this might be close. jQuery will be helpful.
function getSum() {
first = $("#firstpick").val();
second = $("#secondpick").val();
sum = first + second
return sum
}
It may be a good idea to add an event listener to your selects. This way your field will automatically update.
You do not have to have a disabled input, it could be type="hidden" instead. Then it will not show up on the page.
$("#firstpick").on("change", function() {
sum = getSum();
$("#my-hidden-input").val(sum);
});
$("#secondpick").on("change", function() {
sum = getSum();
$("#my-hidden-input").val(sum);
});

How to pass select list value in action link without using javascript and creating a model for it?

I have a shopping cart and I created a simple select list for quantity via Html. I would like to use an Html.ActionLink to get the value of that select list, however if I use JavaScript in will not work as it is inside a PartialView called product and there are multiple number of product on the page.
How could I get the value of that select list without JavaScript? I did look around, but did not find anything useful. Is there any other way?
PartialView
<p>#Model.Description</p>
<p id="price">#Model.Price</p>
<p class="id hidden">#Model.GadgetID</p>
<select name="Select" id="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<p>
Html.ActionLink("Add To Cart", "AddOrder", "Home",new { qty = ?? , id = Model.GadgetID, price = Model.Price }, null )
</p>
Or if I use JavaScript how can I get the right details as there are multiple products on the page.
View that includes that PartialView.
<div class="col-lg-10 products">
<div class="pad">
#foreach (var item in Model)
{
foreach (var gadget in item.Gadgets)
{
#Html.Partial("Gadget", gadget)
}
}
</div>
</div>
JQuery
<script type="text/javascript">
$(document).ready(function () {
$(".AddToCartBtn").click(function () {
var _qty = $(this).find("#quantity").val();
var _id = $(this).find(".id").val();
var _price = $("#price").html();
alert("qty: " + _qty + " id: " + _id + " price: " + _price);
});
});
You cannot do it without client side javascript because user can change the selection of your quantity dropdown at client side.
With Javascript / jQuery, you can read the value of selected option and append to the query string when the link is clicked. Also since you will have the same markup generated from the partial view, you should not use hardcoded static ids. Id's should be unique for html elements. With your current code, it will generate same id for all the quantity select elements. You can use a css class and use the closest() and find() method to get access to the quantity select element of the link clicked.
<div class="gadgetItem">
<select name="Select" class="qtySelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
#Html.ActionLink("Add To Cart", "AddOrder", "Home",
new { #id = Model.GadgetID, price = Model.Price }, new { id="addToCart"} )
</div>
and in JavaScript, listen to the click event on the link. Assuming jQuery is available to the page,(this code should go in the main page,not in the partial view)
$(function(){
$(document).on("click","#addtoCart",function(e){
e.preventDefault(); // Stop the normal link click behaviour
var currentUrl = $(this).attr("href"); // Get the url
// Append the quantity value to query string
var newUrl = currentUrl + "?qty =" + $(this).closest(".gadgetItem")
.find(".qtySelect").val();
window.location.href=newUrl; ///Load the new page with all query strings
});
});
Also I suggest you not read the price from the client request. You should always read it back from the db in server based on the Id of the item. If not, I can update the price in the query string to "0.0001" and order thousands of your products!

Trying to create a drop-down of form fields, that is based on a number

Good afternoon!
I am building a contact form in Contact Form 7 in Wordpress. And I need a functionality where one of the form fields is a number selector (for example, 1-10) and I need the number that is selected to be calculated and drop down the number of fields to be inputted.
I'll try to explain the best I can. So if someone types in the 4...I need a drop down of four input fields.
I have looked for some jquery script for this functionality, but I'm basically at a deadend. If anyone has any suggestions, I would much appreciate it!
Here's an option using jQuery (jsFiddle)
HTML
Number of inputs:
<select class="numInputs" onChange="buildInputs(this);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div class="inputs"></div>
Javascript (jQuery)
$(document).ready(function () {
// set onchange event for the select box.
$('.numInputs').change(function () {
// clear any inputs added to the div.
$('.inputs').empty();
// get number of inputs to add from select box.
var num = $('.numInputs option:selected').text();
// build the inputs.
for (var i = 1; i <= num; i++) {
$('<input type="text"/><br/>').appendTo('.inputs');
}
})
});
You would use javascript, I wrote a simple sample for you. I haven't ever worked with wordpress, but this just works on it's own, and I would think you should be able to just put it in.
Javascript
<script type="text/javascript">
function thing(){
var num = document.getElementById("number").value; //Get the number out of the number field
document.getElementById("select").innerHTML = ''; //Get rid of the placeholder, or the old ones
for (var i = 0; i < num; i++){
var newOpt = document.createElement('option');
newOpt.innerHTML = i; //It'll just have a dropdown for 0 to the number
newOpt.value = i;
document.getElementById("select").appendChild(newOpt);
}
}
</script>
HTML
<form>
Number: <input type="number" name="number" id="number" onblur="thing();">
<select id="select">
<option value="no">Enter a number first</option>
</select>
<input type="submit" value="Submit">
</form>
Also, instead of using onblur, you could use onkeyup or something. onblur is for when it loses focus.

Categories