With bind/on change how to show a Row - javascript

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);

Related

replace input type select multiple by some kind of list to force selected elements

I'm trying to achieve something like on this screenshot :
screen
it's basically a form in PHP/Html, and working nicely.
however it's not exactly what I want to do.
I want to take elements from the left and put them to the right side, and get the form validated with the right side elements.
atm, everything works nicely, but my problem is : all elements on the right side need to be "selected" before submitting the form.
is there a way of doing this without having the elements on the right side being "selected".
technically, I just want the "pushed elements" to the right side to be all selected by default in the form.
I suppose my problem comes from the fact that I'm using select instead of another kind of input (can I use a textarea, or some kind of other input ?)
thanks
FYI, here is my source code for this
javascript
<script type="text/javascript" language="Javascript">
function move(sens) {
var i, sourceSel, targetSel;
if (sens == 'right') {
sourceSel = document.getElementById('selectBoxOne');
targetSel = document.getElementById('selectBoxSecond');
} else {
sourceSel = document.getElementById('selectBoxSecond');
targetSel = document.getElementById('selectBoxOne');
}
i = sourceSel.options.length;
while (i--) {
if (sourceSel.options[i].selected) {
targetSel.appendChild(sourceSel.options[i]);
}
}
}
</script>
php/html
<tr>
<th>Associated rights</th>
<td>
<table border="0" cellspacing="0" id="table">
<tr>
<td>
Available (unused) rights (pbroles) <br />
<select name="kiki" multiple="multiple" id="selectBoxOne" size="10" style="width: 325px">
<?php
$q_pbroles = '
SELECT
p.name
FROM
firecall_pbroles p
WHERE
p.name not in (
SELECT
p.name
FROM
firecall_pbroles p,
firecall_roles r,
firecall_l_roles l,
firecall_pbroles_types t
WHERE
p.id = l.pbrole_id
AND
r.id = l.role_id
AND
t.id = p.type
AND
r.id = '.$role_id.'
)
;';
$prep = $dbh->prepare($q_pbroles);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option id="multiple'.$data['id'].'" value="'.$data['id'].'">'.$data['name'].'</option>';
}
?>
</select>
<br />
Ctrl+Click to select multiple pbroles
</td>
<td>
<input type="button" value="<<" onclick="move('left');"><br />
<input type="button" value=">>" onclick="move('right');">
</td>
<td>
pbroles in this Role<br />
<select name="pbRoles[]" multiple="multiple" id="selectBoxSecond" size="10" style="width: 325px">
<?php
$q_pbroles = '
SELECT
p.id,
p.name,
t.roletype,
t.descr
FROM
firecall_pbroles p,
firecall_roles r,
firecall_l_roles l,
firecall_pbroles_types t
WHERE
p.id = l.pbrole_id
AND
r.id = l.role_id
AND
t.id = p.type
AND
r.id = '.$role_id.'
ORDER BY
p.type;
';
$prep = $dbh->prepare($q_pbroles);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option id="multiple'.$data['id'].'" value="'.$data['id'].'" selected>'.$data['name'].'</option>';
}
?>
</select>
<br />
Ctrl+Click to select multiple pbroles
</td>
</tr>
</table>
</td>
</tr>
There are several ways to achieve this.
See Paul Dixon's answer on "how to pass array through hidden field"
You can add an event listener to the form submit event and then add each selectBoxSecond option to a hidden field inside your form like this:
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(e) {
var elements = document.getElementsByClassName('hidden_pbRoles');
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
var sourceSel = document.getElementById('selectBoxSecond');
i = sourceSel.options.length;
while (i--) {
var input_hidden = document.createElement("input");
input_hidden.setAttribute('name', 'pbRoles[]');
input_hidden.setAttribute('type', 'hidden');
input_hidden.setAttribute('value', sourceSel.options[i].text);
form.appendChild(input_hidden);
}
};
Now you can also remove name and multiple="multiple" from the second select selectBoxOne:
<select id="selectBoxSecond" size="10" style="width: 325px">
</select>
You can check my working example here: http://zikro.gr/dbg/html/listpost.php
Just move some options from the left to the right select box and then hit submit button to see the POST data result after the page refresh.

JSP giving NullPointerException for request.getParameter()

I'm new to jsp and am creating a webpage that has a form with a select box and a few other input boxes.
I'm populating these input boxes automatically with values from properties file:
NumConfig.properties
SELECT= , ,
ONE=1,I,FIRST
TWO=2,II,SECOND
THREE=3,III,THIRD
Here is my form:
<html>
<body>
<form name="NumDetail" id="NumDetail" method="post">
<div>
<table>
<tr>
<th rowspan="2">Select
<select id="SelectText" name="SelectText" onchange="this.form.submit()">
<option value="ONE">ONE</option>
<option value="TWO">TWO</option>
<option value="THREE">THREE</option>
</select>
</th>
<th align="center">Number</th>
<th align="center">Roman</th>
<th align="center">Position</th>
</tr>
<tr>
<td align="center">
<input type="text" size=10 id="number">
</td>
<td align="center">
<input type="text" id="roman">
</td>
<td align="center">
<input type="text" id="position">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
And this is the JS code I'm using to load values from properties file:
< script type = "text/javascript" >
<%
ResourceBundle resource = ResourceBundle.getBundle("NumConfig");
String dbname;
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
dbname = request.getParameter("SelectText");
String[] num = resource.getString(dbname).split(","); %>
var number = "<%= num[0]%>";
var rom = "<%= num[1]%>";
var pos = "<%= num[2]%>";
document.getElementById("number").value = number;
document.getElementById("roman").value = rom;
document.getElementById("position").value = pos; < /script>
I can indirectly open this page by appending ?SelectText value in the URL.
But when opening this page directly I get NullPointerException at the line
String[] num = resource.getString(dbname).split(",");
Two Questions:
How do I perform a null check or give the request parameter a default value so that page does not error out?
Once I select a value from the dropdown and the form submits, the select box does not retain its value and goes back to the default. How to resolve this?
You just need an else statement
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
else
dbname = request.getParameter("SelectText");
To make an option selected by default, you should try this selected="selected". Stock the value somewhere and change your selected option dynamically.
<option value="ONE" selected="selected">ONE</option>
Firstly my recommendation would be not to mix Java code within HTML code in a JSP page. Try using a Java Servlet to manage your request and respose so you don't end up having a messy code.
I'll answer your questions below:
You are checking whether the parameter "SelectText" is null, and if that's the case then giving to 'dbname' a default value but the next instruction is replacing this given value with null.
The code should look like this:
String dbname = "SELECT";
String requestValue = request.getParameter("SelectText");
if (requestValue != null) {
dbname = requestValue;
}
Have you tried replacing your form request method with GET instead of POST?

when option selected do stuff ( btw, all the elments have dynamic id)

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!

Trouble cloning a set of selects dependent on each other

I am trying to create a dynamic table that allows the user to select from around 100 variables. These variables have been split into categories and I have been displaying them in a second select that depends on the user selecting a value in the first select. I have been searching the web for answers and have come up blank. I realize that the clone() call will duplicate all data and for that reason id's are a poor choice for the rows.
Here is what I currently have for HTML:
<body>
<table name='myTable' class="dynatable">
<thead>
<tr>
<th class='idCol' >ID</th>
<th>Category</th>
<th>Metric</th>
<th>Conditional</th>
<th><button class="add">Add</button></th>
</tr>
</thead>
<tbody>
<form name='myForm'>
<tr class="first">
<td class="id idCol"><input type="text" name="id[]" value="0" /></td>
<td><select name='categories' onChange='updatemetrics(this.selectedIndex)' style="width: 260px">
<option selected>--Select Category--</option>
<option value='1'>Customer Experience</option>
<option value='2'>Key Satisfaction Identifiers</option>
<option value='3'>Personnel Costs</option>
<!-- I have cut the rest out for the sake of brevity. -->
</select></td>
<!-- This is the select that populates based on the user's choice. -->
<td><select style="width: 310px"name='metrics'></select></td>
</tr>
</form>
</tbody>
</table>
</body>
The Javascript that I am working with is as follows.
$(document).ready(function() {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function() {
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone(true);
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live("click", function() {
$(this).parents("tr").remove();
});
});
//script for dynamically populating the metrics select
var metricCategories=document.myForm.categories;
var metricList=document.myForm.metrics;
var metrics=new Array()
metrics[0]=" "
metrics[1]=['Wait time average|waitInLine','Mystery Shopper Scores|mysteryScores']
metrics[2]=['Referral Rate|ref_rate','Facebook Shares|facebook_shares','Twitter Followers|twit_followers','Customer Complaint Calls|comp_calls']
metrics[3]=['Pension Payouts|pension_pay', 'Full Time Employees|ftes', 'Part Time Employees|ptes', 'Contractor Costs|contract_costs']
function updatemetrics(selectedMetricGroup){
metricList.options.length=0
if (selectedMetricGroup>0) {
for (i=0; i<metrics[selectedMetricGroup].length; i++)
metricList.options[metricList.options.length]=new Option(metrics[selectedMetricGroup][i].split("|")[0], metrics[selectedMetricGroup][i].split("|")[i])
}
}
Any help would be appreciated. To reiterate the reason I am asking for help, I need to add/ remove rows that hold select nodes that interact with each other. Thanks in advance.

total price according to quantity written for multiple items [closed]

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>

Categories

Resources