How to pass a variable inside a jquery function $.each($("abc")...? - javascript

I'm trying to iterate a bunch of SELECT OPTION html drop-down fields and from the ones that are NOT empty, take the values and add a hidden field for a PAYPAL shopping cart.
My problem is that for some reason, the variable "curitem" is not passed inside the each function and I can't add the hidden field like they should. All I get is "NaN" or "undefined".
What PAYPAL expects is: item_name_1, item_name_2, etc. All numbers must iterate by +1.
How can I do this?
Thanks a bunch in advance
var curitem;
$.each($("select"), function(index, item) {
var attname = $(this).attr("name");
var nom = $(this).attr("data-nom");
var prix = $(this).attr("data-val");
var partname = attname.substring(0, 1);
var qte = $(this).val();
// i want all my <select option> items that the NAME start with "q" AND have a value selected
if (partname == "q" && isNaN(qte) == false && qte > 0) {
// item name
var inp2 = document.createElement("input");
inp2.setAttribute("type", "hidden");
inp2.setAttribute("id", "item_name_"+curitem);
inp2.setAttribute("name", "item_name_"+curitem);
inp2.setAttribute("value", nom);
// amount
var inp3 = document.createElement("input");
inp3.setAttribute("type", "hidden");
inp3.setAttribute("id", "amount_"+curitem);
inp3.setAttribute("name", "amount_"+curitem);
inp3.setAttribute("value", prix);
// qty
var inp4 = document.createElement("input");
inp4.setAttribute("type", "hidden");
inp4.setAttribute("id", "quantity_"+curitem);
inp4.setAttribute("name", "quantity_"+curitem);
inp4.setAttribute("value", qte);
// add hidden fields to form
document.getElementById('payPalForm').appendChild(inp2);
document.getElementById('payPalForm').appendChild(inp3);
document.getElementById('payPalForm').appendChild(inp4);
// item number
curitem = curitem + 1;
}
});

I think you have to initialize curitem variable.
var curitem = 1;

Related

Calculate data to an input field from 2 select fields with javascript

I want to calculate 2 options from different selects in HTML and display the result in an input field. The first select will fill from a mysql database, the second select will fill with 1 option that is the pair of the first. I want to multiply them and display the result in the last input field. Here is an example:
The table of the database the field are "id product"-id quantity price type
table view
Here is the result that i want: to display
When the user selects the quantity the corresponding value is going to be displayed to the next field.
After that in the last input field i want to calculate the previous selections
the user can only select the quantity and not the price
I made a select with php and made an array which is converted to javascript array object
<?php
$sth = $conn->prepare("SELECT quantity,price FROM eb_products_price WHERE product_id = 20");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
$json_array = json_encode($result);
print_r($result);
With this code the only thing i can do is to display the quantity with a foreach
BUT the price will remain the last one and it wont change while i change the quantity.
I found a way to display the correct price but with javascript here is the code
<script>
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity= document.getElementById("quantity");
var price= document.getElementById("price");
var arrprice = quantity.options[quantity.selectedIndex].value;
while (price.options.length) {
price.remove(0);
}
var prices = arrayObjects[arrprice];
if (prices) {
var i;
for (i = 0; i < prices.length; i++) {
var price1 = new Option(prices[i], i);
price.options.add(price1);
}
}
}
</script>
Here is the calculate function that work without the last part of code:
calculate = function()
{
var quantity= document.getElementById('quantity').value;
var price= document.getElementById('price').value;
var number = parseFloat(quantity)*parseFloat(price);
var n = number.toFixed(2);
document.getElementById('result').value = n
}
To change a HTML-Element dynamically you need event Listeners like onChange example below:
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity = document.getElementById("quantity");
var factor = document.getElementById("factor"); // added
var price= document.getElementById("price");
// Fill dropdown (quantity)
while (quantity.options.length) {
quantity.remove(0);
}
// fill by key
for( var quantity_key in arrayObjects ) {
var quantity_option = new Option(
quantity_key,
quantity_key
);
quantity.options.add(quantity_option);
}
// onChange-Listener
quantity.onchange = () => {
factor.value = arrayObjects[quantity.value];
// look for factor by key in arrayObjects
price.value = Math.round(
quantity.value *arrayObjects[quantity.value]
);
};
}
products();
<select id='quantity'></select>
KG
<input type='text' id='factor' readonly="readonly">
<input type='text' id='price' readonly="readonly">
in javascript, to get the selected element (value) of a select, use :
var e = document.getElementById("quantity");
var quantity= e.options[e.selectedIndex].text;

How to change asp.net DropDownList SelectedValue using javascript?

I have three dropdownlist controls in my asp.net web app project from which the user will choose items. What I want is that the user must not choose the same values, meaning that the value selected in the one Dropdownlist can not be selected in the other dropdownlist, and if the user tries to select the same value I want to reset the selectedValue property to that dropdownlist. Is there anyway I can achieve this using javascript? It's better to make it on the client side.
Thank you!
The Dropdownlist Looks like this: Image here
First add same class name in all three dropdowns. e.g
'class=dropdownClass'
Add dropdown Number as attribute in all
three dropdowns -> 'dropdownNo=1' , 'dropdownNo=2' , 'dropdownNo=3'
Also add ids (it must be different)-> dropdownId1 , dropdownId2 ,
dropdownId3 respectivitely
<script>
$(document).ready(function () {
$('.dropdownClass').on('change', function () {
//when ever any dropdown change (class name is same)
//get the attribe no
var CurrentdropdownNo = $(this).attr('dropdownNo')
var CurrentdropdownValue = $(this).val();
if (CurrentdropdownNo == 1) {
var value2 = $('#dropdownId2').val() ;
var value3 = $('#dropdownId3').val() ;
//check with dropdown 2,3
if (CurrentdropdownValue == value2 || CurrentdropdownValue == value3)
{
//reset the current dropdown
//do stuff here , what you want
}
}
if (CurrentdropdownNo == 2) {
var value1 = $('#dropdownId1').val();
var value3 = $('#dropdownId3').val();
//check with dropdown 1,3
if (CurrentdropdownValue == value1 || CurrentdropdownValue == value3) {
//reset the current dropdown
//do stuff here , what you want
}
}
if (CurrentdropdownNo == 3) {
var value1 = $('#dropdownId1').val();
var value2 = $('#dropdownId2').val();
//check with dropdown 1,2
if (CurrentdropdownValue == value1 || CurrentdropdownValue == value2) {
//reset the current dropdown
//do stuff here , what you want
}
}
})
})
Note: Change class name Or id name as want ..
Use change Event of every dropdownlist
this is just one change event that i use for Dropdownlist. Do same thing for other drowpdownlists.
var firstDropVal="";
var SecndDropVal="";
var ThrdDropVal ="";
$("#dropOne").change(function () {
var firstDropVal = $("#dropOne").val();
var firstDropVal = $("#dropTwo").val();
var firstDropVal = $("#dropThree").val();
if(firstDropVal == SecndDropVal){
$("#dropOne").val(0)// Or Do what you want to do
}
});

Need text in input to not display user input once sent

Here is my jQuery, I have it working properly but once my row is added the user input in the inputs are still there and not cleared. How do I fix this?
// Removing menu rows
$('.menu-items').on('click', '.delete', function(){
$(this).closest('.menu-row').remove();
});
// HTML
var MENU_ROW_TEMPLATE = '<div class="menu-row"><span class="item-description">$description</span><div class="control-items"><span class="item-price">$price</span><span class="delete">X</span></div></div>'
// Adding menu rows
$('.menu-category').on('click', 'button', function(){
var $row = $(this).closest('.add-item');
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
var newRowHtml = MENU_ROW_TEMPLATE.replace('$description', name).replace('$price', price);
var $newRow = $(newRowHtml);
var $lastMenuRow = $row.closest('.menu-category').find('.menu-row').last();
$newRow.insertAfter($lastMenuRow);
});
Sorry for my poor explaining skills.
Clear the name and price after you get the values...
...
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
$row.find('input').first().val('');
$row.find('input').last().val('');
...

get all checked checboxes and add their names and values in array

I have large form mainly drop down lists and checkboxes. Checkboxes are created dynamically so i don't know their id's before they are created. I use drop down onChange event to do create them on the fly.
How can i loop trough the form and get all the checkboxes that are checked, that is their id and their value? I need to do this only for check boxes that are checked. All checkboxes share the same name, that is: categoriesfilters[]. Currently i have on click event on the checkbox which invoke the javascript function.
Here is the code:
function update_number_of_adds_found(field_dropdown,selected_value) {
selected_value="";
var addtypeid = $("#addtypeid").val();
// trying to store the values of the checkboxes
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
alert(value);
}
);
var selected_value = {
addtypeid: addtypeid,
// need to add the ids and the values here as well
};
var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
$.post(url, selected_value, function(r){
if(r) {
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(r.result);
} else {
// alert(selected_value);
}
}, 'json')
}
Regards, John
Try this :
var categories = [];
$("input[name='categoriesfilters[]']:checked").each(
function() {
var id = $(this).attr("id");
var value = $(this).val();
categories[categories.length] = {id : value};
}
);
console.log(categories);
$.post(url, categories, function(r){
...
Try this :
$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
}
);
});
I guess you want to check that on form submit.
var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
var obj = {
id: $(this).attr('id');
value: $(this).val();
};
arr.push(obj);
});
console.log(arr); // show us the array of objects
Would you like to use Jquery?
Add a class to each of the checkbox i.e "class_chk";
$(function(){
$('.class_chk').each(function(){
if($(this).is(':checked')){
var id = $(this).attr('id');
var val = $(this).val();
alert("id = "+id+"---- value ="+val);
}
});
});
The above way you can get all the check box id and value those are checked.
Thanks..

Jquery doesnt update in forms

I made the following code to replace form fields in a page that I can't edit but only manipulate. However, the code does nothing. In chrome console when I print a variable it works fine. The code is below:
//GET val from drop DROP DOWN
var office_id = FieldIDs["OfficeName"];//Gets the input id
var offices;//gets the value from the drop down
$("#FIELD_"+office_id).change(function(){
offices = $(this).val();
}).change();
//The below gets the id's of all the input fields
var address_id = FieldIDs["Address"];
var address2_id = FieldIDs["Address2"];
var city_id = FieldIDs["City"];
var state_id = FieldIDs["State"];
var zip_id = FieldIDs["Zip"];
var phone_4id = FieldIDs["Number4"];//phone
var phone_id = FieldIDs["Number1"];//fax
var pdfm4 = FieldIDs["pdfm4"];
var pdfm = FieldIDs["pdfm"];
if(offices == "SoCal Accounting"){
$('#FIELD_'+address_id).val("7421 Orangewood Avenue");
$('#FIELD_'+address2_id).val("");
$('#FIELD_'+city_id).val("Garden Grove");
$('#FIELD_'+state_id).val("CA");
$('#FIELD_'+zip_id).val("92841");
$('#FIELD_'+phone_4id).val("+1 714.901.5800");//phone
$('#FIELD_'+phone_id).val("+1 714.901.5811");//fax
}

Categories

Resources