push the current element into my array - javascript

I'm trying to push the current selected radio button into my array 'pen'. The entire collection is getting pushed. The current selections should be the shape, size, metal. I want to be able to concatenate them into an image url but I keep getting the entire array. How do I just get the current input values?
<h2>Pick a shape</h2>
<label>circle</label>
<input type="radio" name="shapes" value="circle" checked>
<input type="radio" name="shapes" value="square">
<label>square</label>
<input type="radio" name="shapes" value="heart">
<label>heart</label>
<br><br>
<hr>
<h2>Pick a metal</h2>
<input type="radio" name="metals" value="silver" checked>silver
<input type="radio" name="metals" value="bronze">bronze
<br><br>
<hr>
<h2>Pick a size</h2>
<input type="radio" name="size" value="sm">sm
<input type="radio" name="size" value="md" checked>md
<input type="radio" name="size" value="lg">lg
$('input:radio').change(function () {
var c = document.getElementById("controls");
var els = document.getElementsByTagName("input");
var pen = new Array();
//console.log(els);
for (var i = 0; i < els.length; i++) {
if (els[i].type == "radio" && els[i].checked == true) {
pen.push(els); // Should I add 'this'
console.log(pen);
}
console.log(pen[0] + "-" + pen[1] + "-" + pen[2] + ".png");
}
});

you need to add the index pen.push(els[i]); ex:
for (var i = 0; i < els.length; i++) {
if (els[i].type == "radio" && els[i].checked == true) {
pen.push(els[i]); // Should I add 'this'
console.log(pen);
}
}
console.log(pen[0] + "-" + pen[1] + "-" + pen[2] + ".png");

Related

How to find all possible combinations of radio buttons selection in js?

I have radiobuttons in radio groups. For example:
<!-- A -->
<div>A</div>
<input type="radio" name="A" value="A1" checked="checked" />
<input type="radio" name="A" value="A2" />
<input type="radio" name="A" value="A3" />
<!-- B -->
<div>B</div>
<input type="radio" name="B" value="B1" checked="checked" />
<input type="radio" name="B" value="B2" />
It is required to have one selected radio button in each group. I need to find all possible combinations of radio buttons selection. In my example it is:
A=A1, B=B1
A=A2, B=B1
A=A3, B=B1,
A=A1, B=B2,
A=A2, B=B2,
A=A3, B=B2
How can I do it in JS?
Loop through all the A radio buttons, each time looping (in another loop) through Bs.
var A = document.querySelectorAll("[name='A']");
var B = document.querySelectorAll("[name='B']");
for (var i = 0; i < A.length; i++) {
for (var j = 0; j < B.length; j++) {
console.log('A= ' + A[i].value + ', ' + 'B= ' + B[j].value);
}
}
What's the purpose? What are you going to do with those combinations?
If you just want to find all of the possible combinations, then this should do it:
function combinations(groups, numPerGroup){ //array of groups, number per group
var com = [];
for(var i = 0; i < groups.length; i++){
for(var j = 0; j < numPerGroup; j++){
com += groups[i] + i + "\n";
}
}
return com;
}

auto search with checkbox inside textbox from databases

I can able to load value from databases to text-box...so now named as auto..from this i want to create a auto search with multiple check box to select multiple value in text-box java script...its possible ...??
<form name="form1">
<input type="checkbox" name="checkboxname" value="a">
<input type="checkbox" name="checkboxname" value="b">
<input type="checkbox" name="checkboxname" value="c">
</form>
<form name="form2">
<input type="text" name="textname">
</form>
var textbox = document.getElementsByName("textname")[0];
var checkboxes = document.getElementsByName("checkboxname");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = (function(chk){
return function() {
var value = "";
for (var j = 0; j < checkboxes.length; j++) {
if (checkboxes[j].checked) {
if (value === "") {
value += checkboxes[j].value;
} else {
value += "," + checkboxes[j].value;
}
}
}
textbox.value = value;
}
})(checkbox);
}
Try this,
<form name="form1" class="form_chk">
<input type="checkbox" name="checkboxname" value="a" class="chk_box">a
<input type="checkbox" name="checkboxname" value="b" class="chk_box">b
<input type="checkbox" name="checkboxname" value="c" class="chk_box">c
</form>
$( "#txt_search" ).blur(function(e) {
var $search = $(e.currentTarget),
search_str = $search.val().toLowerCase(), $chk,
$chk_ele = $('.chk_box').filter(function(index, chk){
if($(chk).val().toLowerCase().search(search_str) !== -1){
return $(chk);
}
});
$('.chk_box').prop('checked', false);
$chk_ele.prop('checked', true);
});
See the output : http://jsfiddle.net/J7dUz/

formulization in jquery using values

I m learning jquery a bit so i created this fiddle here http://jsfiddle.net/8FXFE/17/
this is my html code
<div class="textForm">
<input type="radio" name="txtNumber" value="100" checked="checked" />100
<input type="radio" name="txtNumber" value="200" />200
<input type="radio" name="txtNumber" value="500" />500
<input type="radio" name="txtNumber" value="1000" />1000
<input type="radio" name="txtNumber" value="10000" />10000
<input type="radio" name="txtNumber" value="other" />other
<input type="text" name="other_field" id="other_field" onblur="checktext(this);"
/>
</div>
<div class="formText">
<input type="radio" name="txtSpace" value="RJ" checked="checked"
/>Space 1.
<br />
<input type="radio" name="txtSpace" value="SM" />Space 2.
<br />
</div>
<h3>Output:</h3>
this is css
#other_field {
display: none;
}
this is jquery
$(document).ready(function () {
console.log("parsed");
$("input[name='txtNumber'],input[name='txtSpace']").change(function () {
$("#output").text("Changed to "+$("input[name='txtNumber']:checked").val() + " " +$("input[name='txtSpace']:checked").val() + " +++++SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER++++++"
);
});
});
$(':radio').on('change', function () {
$('#other_field')[$(this).val() === 'other' ? 'show' : 'hide']();
});
$('#other_field').on('blur', function () {
var val = $(this).val();
if(isNaN(val)) {
alert('only numbers are allowed..');
}
else if(parseInt(val, 10) % 10 > 0) {
alert('only multiples of 10..');
}
});
How can i achieve actual output those shown in capital letters inside +++++++++++
SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER
Also How can i add dynamic value of hidden other_field (if selected)
var value = $("input[name='txtNumber']:checked").val();
if(value == "other"){
value = parseInt($("#other_field").val());
}
if(!value || isNaN(value)) value = 0;
var type = $("input[name='txtSpace']:checked").val();
var fixedMultiplier;
switch(type){
case "RJ": fixedMultiplier = 100; break;
case "SM": fixedMultiplier = 50; break;
default: fixedMultiplier = 1; break;
}
var computedValue = value * fixedMultiplier;
$("#output").text("Changed to "+ value + " " + type + " (" + computedValue + ")");
http://jsfiddle.net/8FXFE/19/
Maybe you should also add a handler to the textfield to update output on keyup.

How to make different calculations based on the same radio button values?

I'm a novice. I've made a code based on this post:
SUM radio button values and checkboxes values in one calculation - javascript and html
I've made two groups of radio buttons with the values 1-5 (first group), and 100-500 (second group).
I need the value of the selected button from each groups to make different calculations with them and display the results.
Here I've multiplied the value of the first group with 2 and added the value of the second group. Now I want to display the result of an other calculation. For example:
var sum=parseInt(val1-3) + parseInt(val2*4)
How can I display both the results at the same time in separate "cells".
<form name="form1" id="form1" runat="server">
<legend>Header 1</legend>
<p><input id="rdo_1" type="radio" value="1" name="price" onClick="DisplayPrice(this.value);"><label for="radio1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="2" name="price" onClick="DisplayPrice(this.value);"><label for="radio2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="3" name="price" onClick="DisplayPrice(this.value);"><label for="radio3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="4" name="price" onClick="DisplayPrice(this.value);"><label for="radio4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="5" name="price" onClick="DisplayPrice(this.value);"><label for="radio5">Radio 5</label></p>
</form>
<hr>
<form name="form2" id="form2" runat="server">
<legend>Header 2</legend>
<p><input id="rdo_1" type="radio" value="100" name="price2" onClick="DisplayPrice(this.value);"><label for="rad1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="200" name="price2" onClick="DisplayPrice(this.value);"><label for="rad2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="300" name="price2" onClick="DisplayPrice(this.value);"><label for="rad3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="400" name="price2" onClick="DisplayPrice(this.value);"><label for="rad4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="500" name="price2" onClick="DisplayPrice(this.value);"><label for="rad5">Radio 5</label></p>
</form>
<p><label for="valueTotal">Value$:</label>
<input type="text" name="valueTotal" id="valueTotal" value="" size="2"readonly="readonly"> </p>
<script type="text/javascript">
function DisplayPrice(price)
{
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ )
{
if( document.form1.price[i].checked == true )
{
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ )
{
if( document.form2.price2[i].checked == true )
{
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1*2) + parseInt(val2);
document.getElementById('valueTotal').value=sum;
}
</script>
Simply define different input fields for your results.
<p>
<label for="valueTotal1">Value1$:</label>
<input type="text" name="valueTotal1" id="valueTotal1"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal2">Value2$:</label>
<input type="text" name="valueTotal2" id="valueTotal2"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal3">Value3$:</label>
<input type="text" name="valueTotal3" id="valueTotal3"
value="" size="2" readonly="readonly" />
</p>
function DisplayPrice() {
for (i = 0; i < document.form1.price.length; i++) {
if (document.form1.price[i].checked == true) {
val1 = document.form1.price[i].value;
}
}
for (i = 0; i < document.form2.price2.length; i++) {
if (document.form2.price2[i].checked == true) {
val2 = document.form2.price2[i].value;
}
}
if (val1 != null && val2 != null) {
document.getElementById('valueTotal1').value = parseInt(val1) * 2 + parseInt(val2);
document.getElementById('valueTotal2').value = parseInt(val1) * 3 + parseInt(val2);
document.getElementById('valueTotal3').value = parseInt(val1) * 4 + parseInt(val2);
}
}
If you are allowed to use jQuery, you could simplyfy the function:
function DisplayPrice() {
var val1 = $('input[name=price]:radio:checked').val();
var val2 = $('input[name=price2]:radio:checked').val();
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}
I created two fiddles: with jQuery and without
Please note one other thing: Don't write parseInt(val1-3). You can't subtract 3 before the string is converted to an integer.
Edit
If you want to have default values, you can write them into the variables before searching for the checked radio button. If no checked button in found, the default value will stay the same. An other solution would be to check whether the variable is still empty and fill it with the default value after searching for the checked button.
function DisplayPrice() {
//Default values - solution I
var val1 = 1;
var val2 = 1;
val1 = $('input[name=price]:radio:checked').val();
val2 = $('input[name=price2]:radio:checked').val();
//Default values - solution II
if(val1 == null) {
val1 = 1;
}
if(val2 == null) {
val2 = 1;
}
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}

Adding form verification in this case

I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail

Categories

Resources