How to add the textbox value inside the textbox using JavaScript - javascript

I am creating a program using JavaScript that while a clicking of button it will select a seat and change its background color to green and at the same time the button value will be added to the text field and will toggle accordingly and in the same function I am passing a another value i.e. fare of the bus.
Issue: When I click a seat button its fare is adding to the textbox, but if I will click two or more seat button the fare is just added to the textbox but not doing the sum of the fare, and again when I click a selected seat the fare will be deducted from the total fare.
Here I am not using jQuery.
Please can anybody help me?
// Create a variable for the array!
var selectedSeats = new Array();
var selectedFares= new Array();
// Build a function that will update the textfield.
// Call this, whenever the array gets changed!
function updateListOfSelectedSeats() {
document.getElementById('selectedseat').value = selectedSeats.join(',');
document.getElementById('selectedfare').value = selectedFares;
}
// Removes a seat from the list of selected seats
function removeSeatFromList(seat,seatFare) {
for (var i = 0; i < selectedSeats.length; i++) {
if (selectedSeats[i] == seat) {
selectedSeats.splice(i, 1);
updateListOfSelectedSeats();
removeFareFromList(seatFare);
break;
}
}
}
function removeFareFromList(seatFares) {
for (var i = 0; i < selectedFares.length; i++) {
if (selectedFares[i] == seatFares) {
selectedFares.splice(i, 1);
updateListOfSelectedSeats();
break;
}
}
}
// Now the function that reacts to clicks on a seat
function setId(id, value,fare) {
var Seat = document.getElementById(id);
switch (Seat.style.backgroundImage) {
case 'url("themes/frontend/images/greenseat.png")':
// Seat is already selected and needs to be deselected
Seat.style.backgroundImage = 'url("themes/frontend/images/seat.png")';
removeSeatFromList(value,fare);
break;
case '':
case 'url("themes/frontend/images/seat.png")':
// Seat is empty, select it!
Seat.style.backgroundImage = 'url("themes/frontend/images/greenseat.png")';
selectedSeats.push(value);
selectedFares.push(fare);
updateListOfSelectedSeats();
break;
}
}

So if i understand you correctly , the text field for the price is appearing as a comma separated array instead of getting the sum of values , if that's the case what you can do is as follows :
document.getElementById('selectedfare').value = eval(selectedFares.join('+'));
this should get the sum of you selectedFares array .
Hope this helps.

Related

Set value/text to dropdown list

I am using the following jquery postcode lookup and I am trying to push values and hard code the process in javascript.
I am using the following to give the postcode textbox a valid postcode, and then forcing the button click to find the addresses.
document.getElementById("idpc_input").value = "LL17 0PN";
document.getElementById('idpc_button').click();
This so far works, after this a dropdownlist appears with the id of 'idpc_dropdown', I am trying to (in javascript or jquery) select an option
Here is what I have done but it does not work
var select = document.getElementById("idpc_dropdown");
document.getElementById("idpc_dropdown").text = '2 Elwy Cottages Heol Esgob';
And also:
var desiredValue = "2 Elwy Cottages Heol Esgob"
var el = document.getElementById("idpc_dropdown");
for(var i=0; i<el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.selectedIndex = i;
break;
}
}
UPDATE:
Let me explain the process and order, 1- Type in postcode and press the button to find my address 2- a dropdownlist then renders and appears .. I Think this is why it is not working for my desired dropdownlist as its not loaded when the page is loaded, it is when the button has been pressed
Provided that i is the same as the index of the item you wish to select, I'd set the dropdown's value attribute to that index:
let el = document.getElementById("idpc_dropdown");
for(let i = 1; i <= el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.value = i; // here
break;
}
}

My jquery function is pushing elements to all my arrays

On my website, users can click on some text to open up a Modal. This Modal allows users to choose a bunch of toppings to add to their Pizza.
Through Javascript, I add each selected topping to an array and change the text display to match their selected toppings. This more or less works, but the problem is for some reason, whenever they add a topping, it is added to ALL arrays, not just the item it's selected for. Can someone help me find why this is happening?
// Open Toppings Modal
$(document).ready(function() {
var count = -1
var tplist = []
$(".order").each(function(){
count += 1
tplist.push([])
var listeners = 0
setModal(count, tplist, listeners)
});
function setModal(count, tplist, listeners) {
$("#openModal" + count).click(function(){
console.log("clicked")
$("#toppingModal" + count).modal()
if (listeners == 0) {
listeners += 1
$("input[type='checkbox']").change(function() {
// TODO: Fix Bug
// Adding to all javascript lists
if (this.checked) {
tplist[count].push($(this).val());
console.log(tplist)
}
else {
ele = $(this).val();
pos = $.inArray(ele, tplist[count])
if ( ~pos ) tplist[count].splice(pos, 1);
}
// Change text to list
if (tplist[count].length > 0) {
$("#openModal" + count).text(tplist[count])
}
else {
$("#openModal" + count).text("Select Toppings")
}
})
}
});
};
});
I am suspecting your $("input[type='checkbox']").change(function() {} is called for every model. Try setting count number somewhere when you click select topping and compare inside $("input[type='checkbox']").change(function() {} to prevent adding of toppings in all arrays

Checkbox check/tick not showing up though checked attribute returns true

I have a piece of code that creates check boxes in a table in a loop and calls their onclick function. In the onclick function, I try to populate a global array that will be a position holder for the checked check boxes of the table. Also if a row is checked, I have to sum the numbers in a text field of that row(I add this to a variable percentage) and if the variable crosses 100 I have to alert the user and ask him to enter values in the checkbox such that the sum is less than 100.
My problem is that each time I click a check box, the global array gets populated, sum is stored in the variable as expected, but the 'tick' on the check box doesn't come/disappears immediately.
How do I solve this issue?
Code:
{
var tabId=document.getElementById("AmnestyTransTbl");
var tabrows = tabId.getElementsByTagName('tr');
var percentage=0,c,n;
var ar=[];
for(var i=1,c=2;i<=tabrows.length-3;i++,c=c+2)
{
// Create CheckBox
ar[i]=c;
var checkBox = document.createElement("input");
checkBox.setAttribute("type", "checkbox");
checkBox.id='CB'.concat(i);
checkBox.onclick = function ()
{
var tabId1=document.getElementById("AmnestyTransTbl");
var rowInd=getRowIndex(this);
CBValue[rowInd]=this.checked;
n=ar[rowInd-1];
percentage=(parseInt(percentage) + parseInt(tabId1.getElementsByTagName("input")[n].value));
if(parseInt(percentage)>100)
{
alert("Amnesty Percentage,"+percentage+", greater than 0!. Plesase check again.");
this.checked=false;
}
if(this.checked==false)
percentage=parseInt(percentage)-parseInt(tabId1.getElementsByTagName("input")[n].value);
} }
var td = document.createElement("td");
td.appendChild(checkBox);
tabrows[i+1].cells[1].appendChild(td);
}
function getRowIndex(el)
{
while((el=el.parentNode) && el.nodeName.toLowerCase() != 'tr');
if (el)
return el.rowIndex;
}
Got the culprit i guess,
Plz try replacing this
if(parseInt(percentage,10)>100) {
this.checked=false;
}
if(this.checked=false)
{
percentage=parseInt(percentage)-parseInt(tabId1.getElementsByTagName("input")[n].value);
}
with this
if(parseInt(percentage,10)>100) {
this.checked=false;
}
else
{
this.checked=true;
}
if(this.checked==false)
{
percentage=parseInt(percentage)-parseInt(tabId1.getElementsByTagName("input")[n].value);
}

Having trouble hiding/disabling elements when using timeouts

I'm trying to disable a button, hide a select list & show some text once a button is clicked... because of how long the javascript can take I am using timeouts to prevent the browser locking & the browser ending it prematurely or presenting a warning... however the code I have doesn't seem to be hiding/disabling/showing the elements once the button is clicked.
Edit: I have confirmed that the elements ARE getting hidden & then reshown, however they are being reshown too early.... the javascript hasn't finished doing what it's doing & they are reshown almost instantly after they are hidden.
Edit 2: Fixed it by moving the code that reshows the select list etc from the "addCatsSICMain" function to the "addCatsSIC" function as so..
if (spot < cats.options.length) {
other code here...
} else {
reshow select list etc code here
}
Here is the code:
This first function is the one that is called once the button is clicked.
function addCatsSICMain() {
// Set elements
var addBtn = document.getElementById('add');
var cat_sel = document.getElementById('cat_sic_sel_wrapper');
var addWait = document.getElementById('addWait');
// Disable add button
addBtn.disabled = true;
// Hide selected list
cat_sel.style.display = 'none';
// Show waiting text
addWait.style.display = 'block';
// Use a timeout function so button can be hid/show when we want successfully & not on function completion
setTimeout(function(){
// Add selected cats
addCatsSIC(0);
// Reshow selected list, reenable add button & hide wwaiting text
addWait.style.display = 'none';
cat_sel.style.display = 'block';
addBtn.disabled = false;
}, 10);
}
function addCatsSIC(spot) {
// Set the search results box
var cats = document.getElementById('cat_sic_list');
// Set the selected categories list that we are adding to..
var sel_cats = document.getElementById('cat_sic_sel');
// Set selcted counter var
var sel_count = 0;
// Set category add failed var
var failed = 0;
// Set batch size for looping
var batchSize = 50;
// Still more to do?
if (spot < cats.options.length) {
// Loop through categories from the search results select box
for (var i = spot; i < spot + batchSize && i < cats.options.length; i++) {
// Check if the cat is selected
if (cats.options[i].selected == true) {
// Set this category's values to some variables
var cat_id = cats.options[i].getAttribute('value');
var cat_name = cats.options[i].text;
if (checkCatSICAdd(cat_id) === false) {
// Now we create the new element
var new_option = document.createElement('option');
// Add attribute
new_option.setAttribute('value',cat_id);
// Create text node
var new_text_node = document.createTextNode(cat_name);
// Append new text node to new option element we created
new_option.appendChild(new_text_node);
// Append new option tag to select list
sel_cats.appendChild(new_option);
} else {
failed++;
}
}
}
var nextBitOfWork = function() { addCatsSIC(spot + batchSize) };
// Hand control back to the browser so it can update the page & not timeout & then restart the function
setTimeout(nextBitOfWork, 50);
}
if (failed > 0) {
// Find out if more than 2 cats were selected
for (var i = 0; i < cats.options.length; i++) {
if (cats.options[i].selected == true) {
sel_count++;
}
if (sel_count == 2) {
break;
}
}
// Give them an alert they have added that category already
/*addedCatSICAlert(sel_count);*/
}
}
Any reason why you are not using jQuery for this. You can disable button, hide select box and show elements by doing the following
$('button').click(function() {
$(this).attr('disabled', 'disabled');
$('select').hide();
$('p').show();
})
check working example at http://jsfiddle.net/N697c/1/
Fixed it by moving the code that reshows the select list etc from the "addCatsSICMain" function to the "addCatsSIC" function as so..
if (spot < cats.options.length) {
other code here...
} else {
reshow select list etc code here...
}

Setting dropdown to first value

I have an .aspx hidden control that stores a defaultId for this dropdown. However, the values in the dropdown can change and sometime the defaultId is listed as one of the selections, other times it isn't. When the drop down clears we run this to reset it:
Global.getComponent("ddlVehicleType").setValue(Global.getComponent("DefaultVehicleTypeId").getValue());
Now when it sets that, if the dropdown doesn't have a value associated with that Id, it displays the actual Id in the field. I have a check for isNumeric now to see when that happens, but how do I make the field display the first value in the list of Id's it DOES have:
var displayedValue = Global.getComponent("ddlVehicleType").getRawValue();
if (IsNumeric(displayedValue)) {
}
Put together a unique little way of doing it, by going through the current populated store of that dropdown on the page:
var newId = 0;
var firstId = 0;
var typeStore = Global.getComponent("ddlVehicleType").getStore();
firstId = typeStore.getAt(0).get('LookupID');
typeStore.each(function(rec) {
if (rec.get('LookupID') == Global.getComponent("DefaultVehicleTypeId").getValue())
{
newId = Global.getComponent("DefaultVehicleTypeId").getValue();
}
});
if (newId != 0) {
Global.getComponent("ddlVehicleType").setValue(newId);
} else {
Global.getComponent("ddlVehicleType").setValue(firstId);
}

Categories