How to assign radio buttons a value in javascript - javascript

What I need to do is turn the 4 different values (when clicked) on the page into a number that I can use to calculate the output in the chart.
http://jsfiddle.net/nlem33/eyGMu/7/
var min_value = 0,
max_value = 10,
units = 0,
price = 0;
var sliderHandler = function (event, ui) {
var newdata = [],
newdata2 = []
data = [],
sum = 0;
if(this.id === 'slider1') {
$('#slider1_value').html(ui.value);
units = ui.value;
} else {
$('#slider2_value').html('$' + ui.value);
price = ui.value;
}
for(var i = 0; i < 12; i++) {
data.push(units * price);
for(var j = 0; j < i; j++)
sum += data[j];
newdata.push(229 * units * i);
newdata2.push(sum);
}
console.log(newdata);
chart.series[0].setData(newdata2);
chart.series[1].setData(newdata);
}

Add a variable called selected and use this event handler:
var selected = 1;
$(document).ready(function() {
$(".product").click(function(){
selected = this.id.replace("product", "");
alert(selected);
});
});
See the updated fiddle. Then you can use the selected variable anywhere.
In order to use the value of a radio button rather than the number in its id, use the following code instead:
var selected = 1;
$(document).ready(function() {
$("input[name=chooseProduct]").change(function(){
selected = $(this).val();
alert(selected);
});
});
See next updated fiddle for that example as well.

Related

Kendo grid change multiple selected cells value

Let's say I have few rows of data populated with numbers. I want to select multiple cells and then on click on a button outside the grid change their values to some other number, let's say '8'. See the sample.
The guys at Telerik gave me this solution:
$(".change").click(function () {
var grid = $("#Grid").data("kendoGrid");
var cellsToChange = grid.select();
for (var i = 0; i < cellsToChange.length; i++) {
var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
item.ProductName = "new value";
}
grid.refresh();
});
But the problem is that I don't know which cells will be selected, so I can't work with item.ProductName, for example. Is there a way to set the value of all selected cells directly, something like cellsToChange[i].value?
You can either get the column name from grid.columns or from the corresponding th element. use the grid.cellIndex method to select the correct column:
$("#change").click(function() {
var selected = grid.select();
var header = grid.thead;
for (var i = 0, max = selected.length ; i < max ; i++) {
var index = grid.cellIndex(selected[i]);
var th = $(header).find("th").eq(index);
// could also use grid.columns[index].field
// (not sure if this gets reordered on column reorder though)
var field = $(th).data("field");
var item = grid.dataItem($(selected[i]).closest("tr"));
item[field] = "new value";
}
grid.refresh();
});
Regarding your comment:
dataItem.set() causes the <tr> elements to get removed from their context (because grid.refresh() will create new rows for the view), and because of that, grid.dataItem() won't give you the expected result with the old DOM elements you still have a reference to.
If you want to use dataItem.set(), you can try something like this as a work-around:
$("#change").click(function () {
var selected = grid.select(),
header = grid.thead,
dataItem,
index,
field,
value,
th;
for (var i = 0, max = selected.length; i < max; i++) {
dataItem = grid.dataItem($(selected[i]).closest("tr"));
index = $(selected[i]).index();
th = $(header).find("th").eq(index);
field = $(th).data("field");
value = "new value " + i;
setTimeout(function (dataItem, field, value) {
return function () {
dataItem.set(field, value);
}
}(dataItem, field, value), 5);
}
});
(demo)
You have to retrieve the ColumnList of your grid first and then loop through it
$(".change").click(function () {
var grid = $("#Grid").data("kendoGrid");
var columnsListOfView = grid.columns;
var cellsToChange = grid.select();
for (var j = 0; i < cellsToChange.length; i++) {
var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
for (var j = 0; j < columnsListOfView.length; j++) {
//Here columnsListOfView[j].field will give you the different names that you need
var field=columnsListOfView[j].field;
item[field] = "new value";
}
}
grid.refresh();
});

How disable wrong options in selects depend on selected option?

I'd like to create a simple math practising js script.
For example:
The sum is given (=10) and there are four select with numbers from 0 to 10.
And if I choose a number I should disable the wrong options. I mean, the sum of selected options can not bigger then 10.
I tried this way: click here
$(document).on("change", "select.number", function(){
var sum = 10;
var number = $(this).children("option:selected").val();
var sum_number = 0;
$("select.number option:selected").each(function(){
sum_number = parseInt($(this).val(),10) + parseInt(sum_number,10);
});
$("select.number option").attr("disabled", false);
if(sum_number>0){
var act_person = act_max_person = 0;
$("select.number").each(function(){
$(this).children("option:not(:first)").each(function(){ // first is 0
if(parseInt($(this).val(),10) + parseInt(sum_number,10) > sum) $(this).attr("disabled", true);
});
});
}
});
But it's vary far from the perfect...
Try
$(document).on("change", "select.number", function () {
var sum = 10;
var number = $(this).children("option:selected").val();
var sum_number = 0;
$("select.number option:selected").each(function () {
sum_number += parseInt($(this).val(), 10);
});
$('select.number option').prop('disabled', false);
if (sum_number > 0) {
var diff = sum - sum_number;
$('select.number').each(function () {
var idx = parseInt($(this).val(), 10) + diff + 1;
$(this).find('option').slice(idx).prop('disabled', true)
})
}
});
Demo: Fiddle

Array not resetting when input changed

I'm trying to populate select box using value from input text. So far I've been doing good in populating the select box. But the problems came when I change the input field into another value. The select box won't reset the array instead of adding the option value in the end of array. Here's my code:
HTML:
<input type="text" name="ttc_list" id="ttc_list" />
<select name="priority_list" id="priority_list">
<option value="">Choose TTC First...</option>
</select>
Javascript:
$(document).ready(function(){
$("select#priority_list").attr("disabled","disabled");
$('input[name="ttc_list"]').change(function() {
var arr = [];
arr.length = 0;
var ttc = $("#ttc_list").val();
if(ttc == 100 || ttc == 101)
{
var prty100_Start = 40;
var prty100_End = 80;
while(prty100_Start < prty100_End+1){
arr.push(zeroPad(prty100_Start++,2));
}
}
else
{
var prty200_Start = 1;
var prty200_End = 5;
while(prty200_Start < prty200_End+1){
arr.push(zeroPad(prty200_Start++,2));
}
}
var selectOptions = {
100: arr,
101: arr,
200: arr,
204: arr,
210: arr
}
$("select#priority_list").removeAttr("disabled");
console.log($(this).val());
if(selectOptions[$(this).val()])
{
console.log(selectOptions[$(this).val()]);
$.each(selectOptions[$(this).val()], function() {
$('select[name="priority_list"]').append('<option>' + this + '</option>');
});
}
});
});
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+n;
}
Example: When user filled '100' in input text, it works fine in populating select box from '40' to '80', but when user changes the input text to '200' without refreshing the page, the select box show options from '40' to '80' and '01' to '05' instead of only '01' to '05'.
Expected result: When user changes the input text to '200' without refreshing the page, the select box shows options only from '01' to '05'
Here's my working demo http://jsfiddle.net/danc32/6UqYS/1/.
Where should I put my arr.length = 0 to reset my array?
Because you are using .append('<option>' + this + '</option>');, every time you change you add the new options to the existing list. Instead you could use:
.html('<option value="">Choose TTC First...</option>'); // remove old options
to reset the select and remove the old options, then use:
.append('<option>' + this + '</option>'); // add new options
to add the new ones.
See this JSFiddle for complete code.
You need to clear the contents of the select element before adding new items... also there is no need to recreate the selectOptions object within the change handler.. it is a static object so it can be created only once as given below
$(document).ready(function () {
var $priority_list = $("#priority_list").prop("disabled", true);
var selectOptions = {};
var arr_40_80 = arrays(40, 80);
selectOptions['100'] = arr_40_80;
selectOptions['101'] = arr_40_80;
var arr_1_5 = arrays(1, 5);
selectOptions['200'] = arr_1_5;
selectOptions['204'] = arr_1_5;
selectOptions['210'] = arr_1_5;
$('input[name="ttc_list"]').change(function () {
var ttc = $(this).val(), arr = selectOptions[ttc];
$priority_list.prop("disabled", false).empty();
if (arr) {
$.each(arr, function () {
$priority_list.append('<option>' + this + '</option>');
});
}
});
});
function arrays(start,end){
var arr = [];
while (start <= end) {
arr.push(zeroPad(start++, 2));
}
return arr;
}
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length);
var zeroString = Math.pow(10, zeros).toString().substr(1);
if (num < 0) {
zeroString = '-' + zeroString;
}
return zeroString + n;
}
Demo: Fiddle

How to sort a random div order in jQuery?

On page load, I am randomizing the order of the children divs with this Code:
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
I cannot seem to figure out how to get the posts back in the original order. Here's the demo of my current code http://jsfiddle.net/JsJs2/
Keep original copy like following before calling reorder() function and use that for reorder later.
var orig = $("#team-posts").children();
$("#undo").click(function() {
orderPosts();
});
function orderPosts() {
$("#team-posts").html( orig ) ;
}
Working demo
Full Code
var orig = $("#team-posts").children(); ///caching original
reorder();
$("#undo").click(function(e) {
e.preventDefault();
orderPosts();
});
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
function orderPosts() {
// set original order
$("#team-posts").html(orig);
}
How about an "undo" plugin, assuming it applies?
Just give each item a class with the corresponding order and then get the class name of each div and save it to a variable
$("#team-posts div").each(function() {
var parseIntedClassname = parseInt($(this).attr("class");
arrayName[parseIntedClassname] = $("#team-posts div." + parseIntedClassname).html()
});
You can reorder them from there by saving their html to an array in order
$("#team-posts").html();
for(var i=0;i<arrayName.length;i++){
$("#team-posts").append('<div class="'+i+'">'+arrayName[i]+'</div>');
}
The solution with saving away the original order is probably the best but if you have to dynamically sort it, you can use this:
http://www.w3schools.com/jsref/jsref_sort.asp
function orderPosts() {
var $grp = $("#team-posts"),
ordered = $grp.children().toArray().sort(function(a, b) {
return parseInt($(a).text()) > parseInt($(b).text());
});
$grp.empty().append(ordered);
}

Value of selected checkbox

I am trying to find the sum of checkbox values (23.75 and 142.75)
Poaten
Checkbox1: 2012-01-17, Porti, 1.760, 23.75
Checkbox2: 2012-01-17, Kopien, 10.560, 142.55
Checkbox3: 2012-01-17, Honorar, 33.600, 453.60
Checkbox4: 2012-01-17, Telefon, 0.640, 8.65
The output is in "Restbetrag". I used the following function but I receive the sum of primary key's value of selected checkbox items in "Posten".
In posten I see four values for each checkbox which are separated by comma. Where should I start to have the 4th value of each clicked checkbox (23.75, 142.55...)? Could you please advice where to find a similar solutions?
Thanks
mpol
function showTotal() {
document.frechnungenadd.x_Restbetrag.value = '';
//document.write("test");
var sum = 0;
var elements = document.getElementsByName("x_Posten[]");
for (i=0;i < elements.length;i++) {
if (elements[i].checked) {
sum = sum + +elements[i].value;
}
}
document.frechnungenadd.x_Restbetrag.value = sum;
}
Not sure if this is what you are looking for...
if (elements[i].checked) {
var myarr = elements[i].value.split(",");
sum += parseFloat(myarr[3]);
}
I solved my problem. Thanks for your support. Here your the code for solution.
Regards
mpol_ch
function showTotal() {
document.frechnungenadd.x_Summe.value = '';
document.frechnungenadd.x_MwSt.value = '';
//document.write("test");
var Summe = 0;
var MwSt = 0
var splitted
var elements = document.getElementsByName("x_Posten[]");
for (i=0;i < elements.length;i++) {
if (elements[i].checked) {
splitted = elements[i].nextSibling.nodeValue.split(",");
MwSt = MwSt+ + parseFloat(splitted[2]);
Summe = Summe+ + parseFloat(splitted[3]);
}
}
document.frechnungenadd.x_MwSt.value = MwSt.toFixed(2);
document.frechnungenadd.x_Summe.value = Summe.toFixed(2);
}
setInterval('showTotal()',1000);

Categories

Resources