I make shopping Cart now with vanilla javascript, html, css.
This program is when consumer click selection tag, add new tag and change count.
To Add new Tag is already working. Change count is not work. When I clicked, selectA, selectB, selectC is changed but not working on input tag.
var selectA = 0;
var selectB = 0;
var selectC = 0;
function handleOnChange(e) {
// 선택된 데이터 가져오기
let value = e.value;
let name = e.options[e.selectedIndex].text;
let itemList = document.getElementById("addItem");
var Item = document.createElement('div');
var itemName = document.createElement('div');
var itemSumA = document.createElement('input');
var itemSumB = document.createElement('input');
var itemSumC = document.createElement('input');
itemName.innerHTML = name;
if (value === "A") {
if (selectA === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumA);
itemList.appendChild(Item);
}
itemSumA.value = selectA;
} else if (value === "B") {
console.log(selectB);
if (selectB === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumB);
itemList.appendChild(Item);
}
itemSumB.value = ++selectB;
} else {
if (selectC === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumC);
itemList.appendChild(Item);
}
itemSumC.value = ++selectC;
}
document.getElementById("Sum").innerHTML = selectA * 39800 + selectB * 49800 + selectC * 59800;
}
<li class="checked">
<button class="accordion">주문 정보</button>
<div class="panel">
<p>상품 선택</p>
<select name="tent" id="tent" onchange="handleOnChange(this)">
<option value="A">A. 스피드 원터치 팝업텐트(3~4인용)</option>
<option value="B">B. 5초 원터치 텐트(3인용) (+10,000)</option>
<option value="C">C. 5초 원터치 텐트(5인용) (+20,000)</option>
</select>
<div id="addItem"></div>
</div>
</li>
I want to know why.
Related
The HTML:
<select id="SHIELD" onchange="calcCHO();" >
<option value="610" selected >CHO-SHIELD 610</option>
<option value="608" >CHO-SHIELD 608</option>
<option value="604" >CHO-SHIELD 604</option>
</select>
<input id="FILLER" type="text" disabled value="" />
The Script:
function calcCHO(){
var f_S = "Silver";
var f_N = "Nickel";
var f_SC = "Silver/Copper";
var CHOS = document.getElementById("SHIELD").value;
var FILLER = document.getElementById("FILLER").value;
if(CHOS === "610") {
FILLER = f_S;
}
else if (CHOS === "608") {
FILLER = f_N;
}
else {
FILLER = f_SC;
}
}
This looks pretty straightforward, any idea why it does not work or produce any console errors?
Thanks!
try it like that.
function calcCHO(){
var f_S = "Silver";
var f_N = "Nickel";
var f_SC = "Silver/Copper";
var CHOS = document.getElementById("SHIELD").value;
var FILLER = document.getElementById("FILLER");
if(CHOS === "610") {
FILLER.value = f_S;
}
else if (CHOS === "608") {
FILLER.value = f_N;
}
else {
FILLER.value = f_SC;
}
}
I am working on a function which allows the price of an order to be automatically calculated based off user inputs into a form. The users will be selecting the "Type" of service they want, and also inputting the "square foot" of an order.
Is the problem because I have attempted to set a string variable to have a intiger value?
When I press the button on the form there is nothing printed on the webpage.
<form>
<select id="type" required>
<option disabled selected value> Type of service </option>
<option value="Gardening">Gardening</option>
<option value="Decorating">Decorating</option>
<option value="Fencing">Fencing</option>
<option value="Flooring">Flooring</option>
<option value="Landscaping">Landscaping</option>
</select>
<input type="number" id="square_ft" placeholder="square_ft">
<button type="submit" onclick="calculatePrice()">Check Price</button>
</form>
<p id="price"> </p>
<script>
function calculatePrice() {
var hours = 4;
var totalPriceHour = 0;
var priceHour = 0;
var priceSquareFt = 0;
var totalSquareFt = 0;
var orderTotal = 0;
var materials = false;
var type = document.getElementById("type").value;
var square_ft = document.getElementById("square_ft").value;
if (type == Gardening) {
priceHour = 20;
priceSquareFt = 3;
} else if (type == Decorating) {
priceHour = 20;
priceSquareFt = 3;
} else if (type == Landscaping) {
priceHour = 30;
priceSquareFt = 2;
} else if (type == Flooring) {
priceHour = 20;
priceSquareFt = 2;
} else (type == Fencing) {
priceHour = 30;
priceSquareFt = 3;
}
totalPriceHour = hours * priceHour;
totalSquareFt = square_ft * priceSquareFt;
orderTotal = totalSquareFt + totalPriceHour;
document.getElementById("price").innerHTML = orderTotal;
}
</script>
the value of an input will return a string so make sure you compare your type variable to a string adding quotes to your validation... also if you put a submit button inside your form this will attempt to send a request to the server..
function calculatePrice() {
var hours = 4;
var totalPriceHour = 0;
var priceHour = 0;
var priceSquareFt = 0;
var totalSquareFt = 0;
var orderTotal = 0;
var materials = false;
var type = document.getElementById("type").value;
var square_ft = document.getElementById("square_ft").value;
if (type == 'Gardening') {
priceHour = 20;
priceSquareFt = 3;
} else if (type == 'Decorating') {
priceHour = 20;
priceSquareFt = 3;
} else if (type == 'andscaping') {
priceHour = 30;
priceSquareFt = 2;
} else if (type == 'Flooring') {
priceHour = 20;
priceSquareFt = 2;
} else if (type == 'Fencing') {
priceHour = 30;
priceSquareFt = 3;
}
totalPriceHour = hours * priceHour;
totalSquareFt = square_ft * priceSquareFt;
orderTotal = totalSquareFt + totalPriceHour;
document.getElementById("price").innerHTML = orderTotal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="type" required>
<option disabled selected value> Type of service </option>
<option value="Gardening">Gardening</option>
<option value="Decorating">Decorating</option>
<option value="Fencing">Fencing</option>
<option value="Flooring">Flooring</option>
<option value="Landscaping">Landscaping</option>
</select>
<input type="number" id="square_ft" placeholder="square_ft">
<button type="button" onclick="calculatePrice()">Check Price</button>
</form>
<p id="price"> </p>
I'm trying to get the button to be enabled only when all three condition are met which are at least one checkbox is selected in the 1st checkbox list and 2nd checkbox selected and option list selected.
For the 1st condition i was thinking as an alternative would javascript be able to check on strlen of the textbox ?
Somehow the pure javascript below is not working and would it be possible if selection by the user goes in reverse ?
Pure javascript:
<script type = "text/javascript">
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('termsChkbx').addEventListener("change", function(){
this.parentNode.style.color = this.checked ? "black" : "red";
}, false);
});
function change(obj) {
var selectBox = obj;
var selected = selectBox.options[selectBox.selectedIndex].value;
var retCustDetails = document.getElementById("retCustDetails");
var tradeCustDetails = document.getElementById("tradeCustDetails");
if(selected === 'ret'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else if (selected === 'trd') {
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
else if (selected === '') {
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "none";
}
}
function isChecked() {
var sum = 0; //store a running sum
//find all price elements: class "CDPrice" within element of class "item"
[].forEach.call(document.querySelectorAll(".item .CDPrice"), function(item) {
//get the corresponding checkbox
var chosen = item.parentElement.querySelector('[type="checkbox"]');
//if checked, add to the running sum
if (chosen.checked) {
var value = parseFloat(item.innerHTML) || 0; //if parseFloat() returns none, default value to zero
sum += value;
}
});
//update the total
var total = document.getElementById("total");
total.value = sum.toFixed(2);
}
function Checked() {
var checkedRadioButtons = document.querySelector('[name="deliveryType"]:checked');
document.getElementById("total").value = checkedRadioButtons.getAttribute("title");
}
//conditions for submit button to be enable
//var firstCondition = document.querySelectorAll('name=CDPrice');
//var termsCheckbox = document.getElementById('termsChkbx');
var show = document.getElementById('show');
var button = document.getElementById('sub1');
var conditions = {
// cond1: false,
// cond2: false,
cond3: false
};
//function setCondition1(e) {
// conditions.cond1 = e.target.checked;
// enableButton(conditions);
//}
//function setCondition2(e) {
// conditions.cond2 = e.target.checked;
// enableButton(conditions);
//}
function setCondition3(e) {
conditions.cond3 = e.target.value && e.target.value.length > 0;
enableButton(conditions);
}
function enableButton(options) {
if (options.cond3) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', true);
}
}
//for(i=0 ; i< firstCondition.length ; i++){
// firstCondition[i].addEventListener("click", setCondition1, false);
//}
//termsCheckbox.addEventListener('change', setCondition2, false);
show.addEventListener('change', setCondition3, false);
</script>
1st condition -> Checkbox list or textbox:
<?php
include_once('database_conn.php');
$sqlCDs = 'SELECT CDID, CDTitle, CDYear, catDesc, CDPrice FROM nmc_cd b inner join nmc_category c on b.catID = c.catID WHERE 1 order by CDTitle';
$rsCDs = mysqli_query($conn, $sqlCDs);
while ($CD = mysqli_fetch_assoc($rsCDs)) {
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}'onchange='isChecked();'/></span>
</div>\n";
}
?>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
2nd condition -> 2nd checkbox:
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
3rd condition -> Option List:
<section id="placeOrder">
<h2>Place order</h2>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
Submit Button:
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
You can attach event listeners on each input and listen for changes.
var firstCondition = document.querySelectorAll('input[name="testName"]');
var termsCheckbox = document.getElementById('termsChkbx');
var show = document.getElementById('show');
var button = document.getElementById('sub1');
Object to hold all the conditions
var conditions = {
cond1: false,
cond2: false,
cond3: false
}
Declared functions to use with addEventListener
function setCondition1(e) {
conditions.cond1 = e.target.checked;
enableButton(conditions);
}
function setCondition2(e) {
conditions.cond2 = e.target.checked;
enableButton(conditions);
}
function setCondition3(e) {
conditions.cond3 = e.target.value && e.target.value.length > 0;
enableButton(conditions);
}
Enable button
function enableButton(options) {
if (options.cond1 && options.cond2 && options.cond3) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', true);
}
}
Add event listeners
for(i=0 ; i< firstCondition.length ; i++){
firstCondition[i].addEventListener("click", setCondition1, false);
}
termsCheckbox.addEventListener('change', setCondition2, false);
show.addEventListener('change', setCondition3, false);
example: http://jsfiddle.net/qjo9rqgc/
The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
i have a problem in html and javascript. i have tried different approach but everything didnt worked. so this is my sample code.
<select id = "testselect" name = "testselect">
<option> </option>
<option id = "o1" name = "testselect" value = "1" onselect='document.getElementById("os1").disabled = true;'> 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>
ok, that's the code. what i want to happen is, when i selected o1(option id), os1(checkbox id) must be disabled and when i selected o2(option id), os2(checkbox id) must be disabled, and so on. so can anyone help me?
Try this:
Using plain javascript:
var select;
function changeIt() {
var allCheckboxes = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < allCheckboxes.length; i++) {
allCheckboxes[i].removeAttribute('disabled');
}
var value = select.options[select.selectedIndex].value;
var checkBox = document.querySelector('input[id=os' + value + ']');
checkBox.disabled = true;
}
window.onload = function () {
select = document.getElementById('testselect');
select.onchange = changeIt;
changeIt();
}
Demo
Using jQuery:
$('select').change(function () {
$('input[type=checkbox]').removeAttr('disabled');
$('input[id=os' + this.value + ']').attr('disabled', true);
});
Demo
My own suggestion would be to move the event-handling outside of the HTML (for ease of future maintenance and change), and take the following approach:
function disableCheck(event) {
// get the element that was the target of the 'change' event:
var that = event.target,
/* find the option tags, and retrieve the option that was selected
from that collection (nodeList) of elements: */
opt = that.getElementsByTagName('option')[that.selectedIndex];
/* find the element whose 'id' is equal to the 'id' of the 'option'
once the 's' is inserted, and set the 'disabled' property to 'true': */
document.getElementById(opt.id.replace('o', 'os')).disabled= true;
}
// bind the onchange event-handler to the element with the id of 'testselect':
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
To toggle which elements are disabled (rather than simply increase the number of disabled elements):
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o','os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++){
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
Well, this is ugly...and suggests I really need to rethink the approach above, however it does work (though it doesn't properly support IE as yet). This uses a trigger function which is fired upon the window.load event which triggers the change event from the select element-node:
function trigger(event, source) {
var newEvent;
if (document.createEvent) {
newEvent = document.createEvent("HTMLEvents");
newEvent.initEvent(event, true, true);
} else {
newEvent = document.createEventObject();
newEvent.eventType = event;
}
newEvent.eventName = event;
if (document.createEvent) {
source.dispatchEvent(newEvent);
} else {
source.fireEvent("on" + newEvent.eventType, newEvent);
}
}
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o', 'os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++) {
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
window.addEventListener('load', function(){
trigger('change', document.getElementById('testselect'));
});
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
onselect should go into the select
<script>
function onSelect(obj){
var x = document.getElementsByName("othser[]");
for (var i in x) x[i].disabled = false;
document.getElementById("os"+obj.value).disabled=true;
}
</script>
<select id = "testselect" name = "testselect" onchange='onSelect(this)'>
<option> </option>
<option id = "o1" name = "testselect" value = "1" > 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>