I am creating a Temperature Converter and I am having trouble with it as I am not able to automatically change the output when an option has been selected.
An example of what I want is that the user enters a number into the the text field and and then they will be able to select the current unit for example celsius. Then they will select the unit they want to be outputted. However, I want that if the input value is celsius then the output celsius value should be removed from the output option select menu.
Hope this makes sense :/
Here is the HTML code.
<body>
<h3>Convert Temperature</h3>
<table>
<tbody>
<tr>
<td>Enter a value</td>
<td>
<input type="text">
<select id ="to">
<option value="far">Farhenheight (F°)</option>
<option value="cel">Celsius (C°)</option>
<option value="kel">Kelvin (K°)</option>
</select>
</td>
</tr>
<tr>
<td>To</td>
<td>
<input type="text" readonly>
<select id="from">
<option value="far">Celsius (C°)</option>
<option value="cel">Farhenheight (F°)</option>
<option value="kel">Kelvin (K°)</option>
</select>
</td>
</tr>
<tr>
</tbody>
</table>
Here is the JSFiddle link to make things a little clearer.
https://jsfiddle.net/jw6c67vr/4/
Thanks in advance :)
I have created the fiddle with your sample demo converting temperature in celsius to temperature in fahrenheit. For others,follow the same procedures.
Below is the js Code:
$('#txtTemperature').on('change', function () {
var tempValue = $.trim($(this).val());
var inputUnit = $.trim($('select#to option:selected').val());
var outputVal = '';
if (inputUnit === 'cel') {
outputVal = cel_faren(parseFloat(tempValue));
}
$('#txtResult').val(outputVal);
});
$('select#to').on('change', function () {
var options = $("select#to>option").map(function () {
return $(this).val();
}).get();
var unit = $.trim($('option:selected', this).val());
var outputUnit = $.trim($('select#from option:selected').val());
if (unit === outputUnit) {
if ($.inArray(outputUnit, options) > -1) {
options.splice($.inArray(outputUnit, options), 1);
}
$('select#from').val(options[0]);
}
});
function cel_faren(tempInCel) {
return (tempInCel * (9 / 5) + 32);
}
Here is the jsfiddl link:
Related
This is my table row within the tbody of my table. I get dropdown value, text value but I can't get selected row value. My row value returns "undefined".
$(document).on("click", "#skorKartDegerle", function() {
$("#modal_evaluation").modal("show");
});
$(document).on("click", "#btnKaydet", function() {
var arrList = [];
var isEmptyAnswer = false;
$("#evaluationTable > tbody > tr").each(function() {
var line = $(this).find(".answerLine").val();
var ddlVal = $(this).find(".answerddl").val();
var txtVal = $(this).find(".answertxt").val();
var obj = '{"line":"' + line + '","ddlVal":"' + ddlVal + '","txtVal":"' + txtVal + '"}';
arrList.push(obj);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="answerLine" value="2">
<td>FR002</td>
<td>Koton Mağazacılık</td>
<td>1800</td>
<td>A</td>
<td>Kabul</td>
<td class="select" value="0">
<select class="answerddl">
<option value="1">Kabul</option>
<option value="2">Ret</option>
</select>
</td>
<td><input type="text" class="answertxt"></td>
</tr>
</tbody>
</table>
Part of the issue is because tr elements do not have a value attribute. To do what you require you could use a data attribute instead, to store custom metadata on the element. The other part is that this is a reference to the tr element. You're then calling find() on the element you're looking to target, so it will not be found as that method looks for descendants only.
In addition it's worth noting that you can make the logic more succinct by using map() to build the array instead of explicitly looping with each() and also that it would be better practice to store objects in the array and only JSON encode it before transferring via AJAX.
$(document).on("click", "#btnKaydet", function() {
var isEmptyAnswer = false;
let arrList = $("#evaluationTable > tbody > tr").map((i, tr) => {
let $tr = $(tr);
return {
line: $tr.data('value'),
ddlVal: $tr.find(".answerddl").val(),
txtVal: $tr.find(".answertxt").val()
}
}).get();
console.log(arrList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="evaluationTable">
<tbody>
<tr class="answerLine" data-value="2">
<td>FR002</td>
<td>Koton Mağazacılık</td>
<td>1800</td>
<td>A</td>
<td>Kabul</td>
<td class="select" value="0">
<select class="answerddl">
<option value="1">Kabul</option>
<option value="2">Ret</option>
</select>
</td>
<td><input type="text" class="answertxt"></td>
</tr>
</tbody>
</table>
<button id="btnKaydet">Click me</button>
I searched for similar questions, I found some but their solution did't help me.
For example:
First question
Second question
My problem is:
I have a table that the user can add rows dynamically, so I am creating a unique id for each row and all elements inside as well.
each row have two text fields and select with two options, and when you select one of the option the text feild should be dislpay:block and the second will be display: "none", depending on your choice.
I built here some example that will shows the general structure (JSFiddle)
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>
<input id="description-first-1" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-1" name="description-second-2" type="text" placeholder = "second">
<select id="select-1">
<option>
<option id="first-opt-1">1</option>
<option id="second-opt-1">2</option>
</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="description-first-2" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-2" name="description-second-2" type="text" placeholder = "second">
<select id="select-2">
<option>
<option id="first-opt-2">1</option>
<option id="second-opt-2">2</option>
</option>
</select>
</td>
</tr>
$(function() {
$("#select-1").change(function() {
if ($("#first-opt-1").is(":selected")) {
$("#description-first-1").show();
$("#description-second-1").hide();
} else {
$("#description-first-1").hide();
$("#description-second-2").show();
}
}).trigger('change');
});
http://jsfiddle.net/8vz121rq/9/
In my example for that matter you can seen that there are only 2 rows but it can also be 10 rows with different id's.
How to get jquery identify which row and all the elements inside of it i'm changing if the id's of all elements is dynamic ?
First of all, you need event delegation as the rows are dynamically generated, such as:
$("table").on("change", "[id^='select']", function() {
// do your stuf
});
Or in your case:
$("table").on("change", "#select-1", function() {
// do your stuf
});
So, is this what you needed?
$(function() {
$("table").on("change", "[id^='select']", function() {
var $this = $(this);
var $row = $this.closest("tr");
var ID = this.id.replace(/^[^\-]+\-(\d+)$/gi, '$1');
var sIndex = $this.prop('selectedIndex');
var part = sIndex === 2 ? "second" : "first";
if (!sIndex) {
$row.find("input").show();
return;
}
$row.find("input").hide();
$row.find("#description-" + part + "-" + ID).show();
});
});
Demo#Fiddle
P.S. The above is purely based on your markup and ID structure!
I have a script that should automatically change the value when drop down list selection is changed, and it works first time I change the value, but second time it does not work (after I try to select different value from the one I selected previously)
Here is the HTML:
<input id="search" placeholder="Search..." type="text"/>
<label for="showbrand" class="filter">Brand:<select id="showbrand" data-bind=''>
<option value="">--select--</option>
<option value="">All</option>
</select></label>
<label for="showfrom" class="filter">From:<input type="date" id="showfrom"></label>
<label for="showto" class="filter">To:<input type="date" id="showto"></label>
<a id="filterList" class="btn btn-primary pull-right" onclick="clickFilter();">Find</a><table id="dataTable" class="table table-condensed table-bordered">
<thead>
<tr>
<th>Campaign</th>
<th>Brand</th>
<th>Starts On</th>
<th>Ends On</th>
<th>Files</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="msg"></div>
JS:
$("#showbrand").change(function(){
var info = new Array();
info[0] = $("#showbrand").val();
if($("#showfrom").val() !== '' &&
$("#showto").val() !== ''){
info[1] = 'yes';
}
else{
info[1] = 'no';
}
info[2] = $("#showfrom").val();
info[3] = $("#showto").val();
info[4] = $("#search").val();
listCampaignsFiltered(info, 'dataTable', 0);
});
unction listCampaignsFiltered(info, tableName, limit){
var params = "&brand="+info[0]+
"&daterange="+info[1]+
"&from="+info[2]+
"&to="+info[3]+
"&limit="+limit+
"&search="+info[4];
$.getJSON(LOCAL_URI+"?action=campaignfiltered"+params, function(result) {
//console.log(JSON.stringify(result));
$('#'+tableName+" tbody").html('');
if(result.length > 0){
$("#msg").html(result.length+ " Records found.");
$.each(result, function(){
var $tr = '<tr><td>'+ this.campaign + "</td><td>"+
this.brandName+"</td><td>"+this.startson+
"</td><td>"+ this.endson +"</td></tr>";
$('#'+tableName+" tbody").append($tr);
});
}
else{
$("#msg").html('No records found.');
}
});
}
For your select element to change, you might need distinct values, otherwise no matter what you choose as your option, it'll always have the same value.
I've never setup a select element without values so I'm not 100% sure this is your issue. Please let me know if this happens to be the issue, otherwise I'll remove the answer.
Also, your JS needs a closing ) to be valid.
Yes you should assign the value in dropdown and also correct your syntax in jquery.
I think below code will help you
<script type="text/javascript" language="javascript" >
$(document).ready(function () {
$("#showbrand").change(function () {
var info = new Array();
info[0] = $("#showbrand").val();
alert(info[0]);
});
});
</script>
<label for="showbrand" class="filter">Brand:
<select id="showbrand" data-bind=''>
<option value="1">--select--</option>
<option value="2">test</option>
<option value="3">All</option>
</select>
</label>
I have a form using coldfusion that currently is using binding to generate a value. After a user selects from a pull down a selection is automatically generates a value 'Y' or 'N' generated from a table. What I need to do is use that value, in this case if value is 'Y' to display more questions to be answered. Here is what the current coding looks like.
<td>Select Category:
<cfselect name="catdesc"
title="Select category to generate related services"
bind="cfc:servicetype2.cat_description()"
bindonload="true"/><br />
</td>
</tr>
<tr id="serv_ty2" style="display: inline;">
<td></td>
<td>Select Service:
<cfselect name="service_type"
bind="cfc:servicetype2.getServiceType2({catdesc})"
bindonload="false"/></td>
</tr>
<tr id="lr_verify" style="display: inline;">
<td></td>
<td>Labor Relations Required:
<cfinput name="lr_needed" <!---
onchange="document.getElementById('lr_question').style.display = (this.selectedIndex == Y) ? 'inline' : 'none'"--->
bind="cfc:servicetype2.getLR({service_type})"
onchange="editLR()"
bindonload="false"/></td>
</tr>
Here is the additional questions I want to show if Y is generated
<TR id="lr_question" name="lr_question" style="display: none;">
<td align="left" nowrap>nbsp;<b>Additional Question:</b><br>(Hold Ctrl to select multiple)</td>
<td align="left">Question:<br><br>
<select id="lr_quest" name="lr_quest" multiple="multiple" required="NO" size="5">
<option name="abc" id="abc">
Choice 1</option>
<option name="abc2" id="abc2">
Choice 2</option>
</select>
From my research I tried two solutions but neither work I am assuming I have the incorrect syntax or my thinking is correct.
Here is what the attempt java function was:
function editLR()
{
// if 'Y' then additional questions for service type should show
var lrshow = document.getElementById("lr_needed");
if( lrshow == 'Y' ) {
lr_question.style.display = "inline";
}
else if ( lrshow == 'N' ) {
lr_question.style.display = "none";
}
else if ( lrshow == '' ) {
lr_question.style.display = "none";
}
}
Let me know if you have any suggestion I apologize if I did not explain myself correctly. Thanks in advance for any assistances I am still new to javascript and coldfusion so learning all the elements that are available still.
To start, you have this:
var lrshow = document.getElementById("lr_needed");
Add this line after it and see what you get.
alert("lrshow is " + lrshow);
Then see if this makes any difference:
var lrshow = document.getElementById("lr_needed").value;
alert("lrshow is " + lrshow);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
hello i am making a shopping cart system but i am stuck in the calculations of total products with number of quantities i want that a user selects a price from drop down and then on entering the quantity it updates the total instant and same goes for the other items . i made a js fiddle for the structure can anyone help me achieve this via simple javascript ?
http://jsfiddle.net/nVCY4/25/
the drop down structure is like
<select id="TIPR1" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
function CalculateTotal(frm) {
var order_total = 0
// Run through all the form fields
for (var i=0; i < frm.elements.length; ++i) {
// Get the current field
form_field = frm.elements[i]
// Get the field's name
form_name = form_field.name
// Is it a "product" field?
if (form_name.substring(0,4) == "TIQT") {
// If so, extract the price from the name
//item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))
var test = "TIPR1,TIPR2";
//test = test + i;
var e = document.getElementById(test);
item_price = e.options[e.selectedIndex].value;
// Get the quantity
item_quantity = parseInt(form_field.value)
// Update the order total
if (item_quantity >= 0) {
order_total += item_quantity * item_price
}
}
}
// Display the total rounded to two decimal places
document.getElementById("order_total").firstChild.data = "$" +
}
I do encourage you to try something yourself, the absolute best way to learn, is by doing.
If you include jQuery or a similar library, it's very easy.
Here's an example: http://jsfiddle.net/nVCY4/26/
var selects = $('select');
var inputs = $('input');
selects.change(calculate);
inputs.keyup(calculate);
function calculate(){
var runningTotal = 0;
selects.each(function(i){
var val = parseInt($(this).val());
var qty = inputs.eq(i).val();
runningTotal += (val*qty);
});
$('#grandtotal').html("Grand-total: "+runningTotal);
}
Add the logic you want to your onchange event, like this:
<select id="TIPR1" onchange="f()" class="table-select" title="Please select">
Where f is the function you want to invoke when something is selected.
Here is a possible solution.. actually, several possible solutions. I don't know how these fields look in the context of the entire form. So one of the methods I show below may work better for you than another one.
I have updated your HTML code only a tiny bit: I made the IDs on the SELECT elements unique so that they could be called easily from the JS.
In the JS code there are three different ways to call your fields and get the values. ONLY ONE must be allowed to run. The others need to be removed or commented out.
This also goes for the bottom portion where you set the value of the total. You did not provide HTML that shows what the order total looks like. So I provided samples for several different ways.
This code is untested, and provided as a way to show you possible solutions to this issue. There are at least 10 more that I can think of off the top of my head, but these are (I think) the best match for the HTML code sample you have provided.
<div id="content">
<table border="1">
<tr>
<th>Book Cover</th>
<th>Title & Author</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td class="image">
<img alt="Book Cover" src="images/covers/2artfielding.png" />
</td>
<td class="title">
<p class="table"><b>The Art of Fielding</b></p>
<p class="table"><i>by Chad Harbach</i></p>
</td>
<td class="price">
<select id="TIPR1" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
</td>
<td class="quantity">
<input type="text" id="artquantity" value="1" /><br />
</td>
</tr>
<tr>
<td class="image"><img alt="Book Cover" src="images/covers/18thelovers.png" /></td>
<td class="title">
<p class="table"><b>The Lover's Dictionary</b></p>
<p class="table"><i>by David Levithan</i></p>
</td>
<td class="price">
<select id="TIPR2" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
</td>
<td class="quantity">
<input type="text" id="loverquantity" value="1" /><br />
</td>
</tr>
<tr>
<td class="image"><img alt="Book Cover" src="images/covers/11nightcircus.png" /></td>
<td class="title">
<p class="table"><b>The Night Circus</b></p>
<p class="table"><i>by Erin Morgenstern</i></p>
</td>
<td class="price">
<select id="TIPR3" class="table-select" title="Please select">
<option value="31">Field Box $31</option>
<option value="29">Lodge Box $29</option>
<option value="19">Bleachers $19</option>
</select>
</td>
<td class="quantity">
<input type="text" id="nightquantity" value="1" /><br />
</td>
</tr>
</table>
<br />
<p class="totals" id="grandtotal">Grand-total:</p>
</div>
<script type="text/javascript">
function CalculateTotal(frm) {
var order_total = 0.00;
var form_select, form_input;
//*****************************************************************
//Option 1: Call the fields directly
//*****************************************************************
form_select = document.getElementById("TIPR1");
form_input = document.getElementById("artquantity");
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
form_select = document.getElementById("TIPR2");
form_input = document.getElementById("loverquantity");
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
form_select = document.getElementById("TIPR3");
form_input = document.getElementById("nightquantity");
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
//*****************************************************************
//*****************************************************************
//Option 2: Create an array and loop through them
//*****************************************************************
var selectIDs = ["TIPR1", "TIPR2", "TIPR3"];
var inputIDs = ["artquantity", "loverquantity", "nightquantity"];
foreach(var i in selectIDs) {
form_select = document.getElementById(selectIDs[i]);
form_input = document.getElementById(inputIDs[i]);
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
}
//*****************************************************************
//*****************************************************************
//Option 3: Assuming there are the same number of SELECTs as INPUTs
//*****************************************************************
var selects = document.getElementById("content").getElementsByTagName("select");
var inputs = document.getElementById("content").getElementsByTagName("input");
foreach(var i in selects) {
form_select = selects[i];
form_input = inputs[i];
order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
}
//*****************************************************************
//*****************************************************************
//Display the total rounded to two decimal places
//*****************************************************************
tot_val = "$" + parseFloat(order_total).toFixed(2);
//I don't know what "order_total" is here since you didn't show it in an example...
// - Here is the code to set it if it's an input
document.getElementById("order_total").value = tot_val;
// - ...if it's a block level element like a DIV or P
document.getElementById("order_total").innerHTML = tot_val;
// - ...or if it's a block level child of the element
document.getElementById("order_total").firstChild.innerHTML = tot_val;
//*****************************************************************
}
</script>