Swap data between two checked elements - javascript

Here is a somewhat simplified version of the code I am currently using:
https://jsfiddle.net/2zauty83/8/
Javascript
function checkboxlimit(checkgroup) {
var checkgroup = checkgroup
for (var i = 0; i < checkgroup.length; i++) {
checkgroup[i].onclick = function() {
var checkedcount = 0
for (var i = 0; i < checkgroup.length; i++)
checkedcount += (checkgroup[i].checked) ? 1 : 0
if (checkedcount > 2) {
this.checked = false
}
}
}
}
var sort_form = document.forms.sortus;
var sort_checkboxes = sort_form.elements['squarepick[]'];
checkboxlimit(sort_checkboxes);
CSS
input.square {
margin: 0;
padding: 0;
display: none;
}
.sorttile {
cursor: pointer;
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid #CCCCCC;
margin: 1px;
}
.sorttile:hover {
border: 2px solid #AAAAAA;
}
HTML
<form enctype='multipart/form-data' method='POST' id='sortus'>
<input id='1-1' class='square' type='checkbox' name='squarepick[]' value='1-1' />
<label class='sorttile' for='1-1' style='background-color:#FF0000;'>
<input type='hidden' name='1-1' value='#FF0000' />
</label>
<input id='1-2' class='square' type='checkbox' name='squarepick[]' value='1-2' />
<label class='sorttile' for='1-2' style='background-color:#FFFF00;'>
<input type='hidden' name='1-2' value='#FFFF00' />
</label>
<input id='1-3' class='square' type='checkbox' name='squarepick[]' value='1-3' />
<label class='sorttile' for='1-3' style='background-color:#00FF00;'>
<input type='hidden' name='1-3' value='#00FF00' />
</label>
<br/>
<input id='2-1' class='square' type='checkbox' name='squarepick[]' value='2-1' />
<label class='sorttile' for='2-1' style='background-color:#00FFFF;'>
<input type='hidden' name='2-1' value='#00FFFF' />
</label>
<input id='2-2' class='square' type='checkbox' name='squarepick[]' value='2-2' />
<label class='sorttile' for='2-2' style='background-color:#0000FF;'>
<input type='hidden' name='2-2' value='#0000FF' />
</label>
<input id='2-3' class='square' type='checkbox' name='squarepick[]' value='2-3' />
<label class='sorttile' for='2-3' style='background-color:#FF00FF;'>
<input type='hidden' name='2-3' value='#FF00FF' />
</label>
<br/>
<input id='3-1' class='square' type='checkbox' name='squarepick[]' value='3-1' />
<label class='sorttile' for='3-1' style='background-color:#000000;'>
<input type='hidden' name='3-1' value='#000000' />
</label>
<input id='3-2' class='square' type='checkbox' name='squarepick[]' value='3-2' />
<label class='sorttile' for='3-2' style='background-color:#999999;'>
<input type='hidden' name='3-2' value='#999999' />
</label>
<input id='3-3' class='square' type='checkbox' name='squarepick[]' value='3-3' />
<label class='sorttile' for='3-3' style='background-color:#FFFFFF;'>
<input type='hidden' name='3-3' value='#FFFFFF' />
</label>
</form>
Basically each colored square represents a checkbox, allowing you to select any two boxes. Additionally, each box has a hidden input field associated with it.
For simplified demonstration purposes, the demo uses "background-color", but my actual code uses "background-image".
What I would like to do is make it so that when two squares are picked, upon selecting the second box, the two boxes trade each other's "background-image" values, effectively making it appear like the two squares traded places.
In addition, however, I also need to swap the values of the hidden-type input fields.
Finally, the two checkboxes should be deselected, although that part is easy. What I'm having trouble with is the first two parts. I thought I had some idea of how to make it work, but my experiments haven't been working out (My knowledge of javascript is still fairly crude).
Any ideas on how to make this work?

The first thing you need to do is set up an event listener so you know when a box has been checked. The second thing you need to do is to keep track of what got checked. Finally, you want to perform a series of operations based on what was checked.
var formEl = document.getElementById("sortus");
// Track our checked boxes
var checked = [];
var swap = function () {
var boxA = checked[0];
var boxB = checked[1];
// Get hidden fields using checkbox ID
var hiddenA = document.getElementsByName(boxA.id)[0];
var hiddenB = document.getElementsByName(boxB.id)[0];
var boxAbackgroundImage = boxA.style.backgroundImage;
var hiddenAvalue = hiddenA.value;
// Switch images!
boxA.style.backgroundImage = boxB.style.backgroundImage;
boxB.style.backgroundImage = boxAbackgroundImage;
// Swap hidden input values
hiddenA.value = hiddenB.value;
hiddenB.value = hiddenAvalue;
};
var reset = function () {
for (var i = 0; i < checked.length; i++) {
checked[i].checked = false;
}
checked = [];
};
var isDuplicate = function (el) {
for (var i = 0; i < checked.length; i++) {
if (checked[i] === el) {
return true;
}
}
return false;
};
formEl.addEventListener("click", function (e) {
var el = e.target;
// Was it a checkbox clicked?
if (el.className == "square") {
// Is it already checked?
if (!isDuplicate(el)) {
checked.push(el);
if (checked.length === 2) {
swap();
reset();
}
}
}
});
I didn't test this code but I hope it gives you a clear sense of what you need to do.

Basic function for your above requirement can be found in the below link,
Fiddler Link
function checkboxlimit(checkgroup)
{
var checkgroup = checkgroup
for (var i = 0; i < checkgroup.length; i++) {
checkgroup[i].onclick = function()
{
var checkedcount = 0
for (var i = 0; i < checkgroup.length; i++)
checkedcount += (checkgroup[i].checked) ? 1 : 0
if (checkedcount > 2) {
this.checked = false
}
swapImage();
}
}
}
function swapImage()
{
var prevStyle="";
var prevId="";
for (var i = 0; i < sort_checkboxes.length; i++) {
if(sort_checkboxes[i].checked)
{
if(prevId!="")
{
document.getElementById(prevId).nextElementSibling.style.backgroundColor = sort_checkboxes[i].nextElementSibling.style.backgroundColor;
document.getElementById(prevId).nextElementSibling.children[0].value = sort_checkboxes[i].nextElementSibling.style.backgroundColor;
sort_checkboxes[i].nextElementSibling.style.backgroundColor = prevStyle;
sort_checkboxes[i].nextElementSibling.children[0].value = prevStyle;
prevStyle = "";
prevId = "";
}
else
{
prevId=sort_checkboxes[i].id;
prevStyle = sort_checkboxes[i].nextElementSibling.style.backgroundColor;
}
}
}
}

Related

How to search different digits in numbers

I have a function which split the input value on space and I looped through to search them in a number but only the last value is shown (checked) not the other before it .
One solution can be by removing else that way it worked fine but this way when changing the value the checked number remain intact(last searched result are also shown).
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var reader = document.getElementsByClassName("checkbox_inputs")
for (let i = 0; i < reader.length; i++) {
var readerText = reader[i].value
var readerText1 = readerText.trim()
var reed = document.getElementById("allNumbers").value;
var reed1 = reed.trim()
var myDiffValues = reed1.split(" ");
document.getElementById("demo").innerHTML = myDiffValues
if (reed != '') {
for (var item of myDiffValues) {
if (readerText1.indexOf(item) > -1) {
reader[i].checked = true;
} else {
reader[i].checked = false;
}
}
} else {
reader[i].checked = false;
}
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
One strange behavior it is showing is when lot of space is entered in the input all checkboxes get checked
You can make it much more easily :)
Explanation
First of all you read your inputs (checkbox_inputs).
Then you
read just once the numbers (allNumbers) and you can trim and split
in one line.
Last step: for each one of your checkboxes you set the checked value if the allNumbers list includes the expected value. false otherwise.
Working Example
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var inputs = document.getElementsByClassName("checkbox_inputs");
var allNumbers = document.getElementById("allNumbers").value.trim().split(" ");
document.getElementById("demo").innerHTML = allNumbers
for (let i = 0; i < inputs.length; i++) {
inputs[i].checked = allNumbers.includes(inputs[i].value);
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>

Inserting rows to a table based on user input

I have tried to generate the rows using javascript, but i'm learning jquery and I wish to use it to implement this functionality.
HTML
<form id="sizePicker">
Grid Height:
<input type="number" id="input_height" name="height" min="1" value="1">
Grid Width:
<input type="number" id="input_width" name="width" min="1" value="1">
<input type="submit">
</form>
<table id="pixel_canvas"></table>
JAVASCRIPT/JQUERY
function makeGrid() {
var table = document.getElementById("pixel_canvas");
//var table = $('#pixel_canvas');
table.innerHTML = "";
while($('#pixel_canvas tr').length > 0)
table.deleteRow(0);
var inputHeight = $('#input_height').val();
var inputWidth = $('#input_width').val();
for(var i = 0; i < inputHeight; i++){
var row = table.insertRow(i);
for(var j = 0; j < inputWidth; j++){
var cell = row.insertCell(j);
}
}
return false;
}
sizePicker.submit(function(evt){
evt.preventDefault();
makeGrid();
});
Here, the table DOM methods such as insertRow() and insertCell() is inactive if I implement the same methods using jquery.
var table = $('#pixel_canvas');
var row = table.insertRow(i); // The browser responses not a function
insertRow is Javascript DOM function. So, with JQuery you have to fetch the DOM element and not the jquery object. Use $('#pixel_canvas').get(0) to fetch the DOM element.
function makeGrid() {
var table = $('#pixel_canvas').get(0);
table.innerHTML = "";
while($('#pixel_canvas tr').length > 0)
table.deleteRow(0);
var inputHeight = $('#input_height').val();
var inputWidth = $('#input_width').val();
for(var i = 0; i < inputHeight; i++){
var row = table.insertRow(i);
for(var j = 0; j < inputWidth; j++){
var cell = row.insertCell(j);
}
}
return false;
}
$('#sizePicker').submit(function(evt){
evt.preventDefault();
makeGrid();
});
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sizePicker">
Grid Height:
<input type="number" id="input_height" name="height" min="1" value="1">
Grid Width:
<input type="number" id="input_width" name="width" min="1" value="1">
<input type="submit">
</form>
<table id="pixel_canvas"></table>

Javascript to Select Multiple options with restrictions

I need a form with multiple steps where the first step restricts options in the successive steps.
So below is an example of use:
User selects from 4 global options
If user selects option 1
Then the user can only select 8 options (no more no less) from a multiple choice box.
If user select option 2
Then the user can only select 10 options (no more no less) from a multiple choice box.
Same is the case with options 3 and 4
After all these selections, this form has to show a final price based on the options user selected in the FIRST STEP. No matter what choices were selected in successive steps.
When this form shows final price, user has to click SUBMIT button and send this result with all these options through an email.
Can someone help me in figuring out the javascript required to do this? Most important thing right now for me is to figure out 'restrictions codes' in multiple items choice boxes.
This is the form I was thinking about:
<form action="" id="menuform" onsubmit="return false;">
<fieldset>
<legend>Select one of this four menus</legend>
<label >Menu Option</label>
<input type="radio" name="selectedmenu" value="Menu1"
onclick="calculateTotal()" />
Menu 1 - serves 8 courses ($20)
<input type="radio" name="selectedmenu" value="Menu2"
onclick="calculateTotal()" />
Menu 2 - serves 12 courses ($25)
<input type="radio" name="selectedmenu" value="Menu3"
onclick="calculateTotal()" />
Menu 3 - serves 16 courses ($35)
<input type="radio" name="selectedmenu" value="Menu4"
onclick="calculateTotal()" />
Menu 4 - serves 30 courses ($75)
<label >Filling</label>
<select id="filling" name='filling'
onchange="calculateTotal()">
<option value="dish1">Dish 1 ($1)</option>
<option value="dish2">Dish 2 ($5)</option>
<option value="dish3">Dish 3 ($5)</option>
(more...)
</select>
<br/>
<div id="totalPrice"></div>
</fieldset>
</form>
Then, for Javascript code I was trying with this to store and return some values but my problem is how to force to select an exact number of options in the SECOND STEP:
var menu_prices = new Array();
menu_prices["Menu1"]=20;
menu_prices["Menu2"]=25;
menu_prices["Menu3"]=35;
menu_prices["Menu4"]=75;
function getMenuPrice()
{
var menuPrice=0;
var theForm = document.forms["menuform"];
var selectedMenu = theForm.elements["selectedmenu"];
for(var i = 0; i < selectedMenu.length; i++)
{
if(selectedMenu[i].checked)
{
menuPrice = menu_prices[selectedMenu[i].value];
break;
}
}
return menuPrice;
}
function getTotal()
{
var menuPrice = getMenuPrice() + getOtherOptionsPrices();
document.getElementById('totalPrice').innerHTML =
"Total Price For Menu $"+menuPrice;
}
Structure your HTML markup carefully, which helps you to target elements via JavaScript easily. Especially, using data-attributes on radio buttons for quantity and price which could be then easily retrieved in respective event handlers. Something like this:
<form action="" method="post" id="menuform" name="menuform">
<fieldset>
<legend>Select menu option</legend>
<label>
<input type="radio" name="selectedmenu" checked value="menu01" data-qty='3' data-price='20' />
<span>1 - serves 3 courses ($20)</span>
</label>
...
<fieldset>
<legend id='fillingsPrompt'>Select fillings</legend>
<select id="fillings" name="fillings" size="6" multiple>
<option value="1">Dish 1 ($1)</option>
...
<fieldset>
<legend>Checkout</legend>
<div id="totalPrice"></div>
<input type="submit" value="Submit" />
</fieldset>
<fieldset>
<legend>Messages</legend>
<p id="result"></p>
</fieldset>
</form>
Identify and select all elements that you'll need:
var menuform = document.getElementById('menuform'),
radios = document.getElementsByName('selectedmenu'),
fillings = document.getElementById('fillings'),
fillingsPrompt = document.getElementById('fillingsPrompt'),
totalPrice = document.getElementById('totalPrice'),
result = document.getElementById('result'),
fillingsAllowed = 0, currentSelection = [], currency = '$'
;
Add event listeners to your radio buttons, select, and the submit button:
menuform.addEventListener('submit', handleSubmit);
fillings.addEventListener('change', handleFillings);
for (var i = radios.length; i--; ) {
radios[i].addEventListener('change', handleLimit);
}
Code the actual event handlers:
// When radio buttons are selected, update parameters for limit
function handleLimit(e) { updateParameters(e.target); }
// When options are selected in the dropdown,
// check against the limit and reset the selection if it exceeds
function handleFillings(e) {
var count = getSelectedCount();
if (count > fillingsAllowed) { resetSelect(); }
else { currentSelection = getSelectedValues(); }
}
// When submit button is clicked,
// check the count of selection against the limit, and
// show appropriate error message
function handleSubmit(e) {
var count = getSelectedCount();
e.preventDefault();
if (count != fillingsAllowed) {
result.textContent = 'Must select exactly ' + fillingsAllowed + ' fillings!';
} else {
result.textContent = 'Ok. ';
}
}
And then code all the helper functions used in the handlers above:
function updateParameters(elem) {
// update the limit based on quantity data attribute on radio
fillingsAllowed = elem.getAttribute('data-qty');
// show the amount based on price data-attribute
totalPrice.textContent = 'Amount: ' + currency + elem.getAttribute('data-price');
// show the hint on legend of fieldset for selecting options
fillingsPrompt.textContent = 'Select ' + fillingsAllowed + ' fillings';
}
// iterate options and get count of selected ones
function getSelectedCount() {
var options = fillings.options, count = 0;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
}
return count;
}
// iterate options and get selected values in an array
function getSelectedValues() {
var options = fillings.options, values = [0];
for (var i=0; i < options.length; i++) {
if (options[i].selected) values.push(options[i].value);
}
return values;
}
// remove selection from all options, and
// re-select based on the array used in the previous function
function resetSelect() {
var options = fillings.options;
for (var i=0; i < options.length; i++) {
options[i].selected = false;
if (currentSelection.indexOf(options[i].value) != -1) {
options[i].selected = true;
}
}
}
Everything put together, the demo looks like this:
Fiddle: https://jsfiddle.net/abhitalks/L813qudw/
Snippet:
var menuform = document.getElementById('menuform'),
radios = document.getElementsByName('selectedmenu'),
fillings = document.getElementById('fillings'),
fillingsPrompt = document.getElementById('fillingsPrompt'),
totalPrice = document.getElementById('totalPrice'),
result = document.getElementById('result'),
fillingsAllowed = 0, currentSelection = [], currency = '$'
;
// listen to events
menuform.addEventListener('submit', handleSubmit);
fillings.addEventListener('change', handleFillings);
for (var i = radios.length; i--; ) {
radios[i].addEventListener('change', handleLimit);
}
// event handlers
function handleLimit(e) { updateParameters(e.target); }
function handleFillings(e) {
var count = getSelectedCount();
if (count > fillingsAllowed) { resetSelect(); }
else { currentSelection = getSelectedValues(); }
}
function handleSubmit(e) {
var count = getSelectedCount();
e.preventDefault();
if (count != fillingsAllowed) {
result.textContent = 'Must select exactly ' + fillingsAllowed + ' fillings!';
} else {
result.textContent = 'Ok. ';
}
}
// fire initial update based on the first radio
updateParameters(radios[0]);
// helper functions
function updateParameters(elem) {
fillingsAllowed = elem.getAttribute('data-qty');
totalPrice.textContent = 'Amount: ' + currency + elem.getAttribute('data-price');
fillingsPrompt.textContent = 'Select ' + fillingsAllowed + ' fillings';
}
function getSelectedCount() {
var options = fillings.options, count = 0;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
}
return count;
}
function getSelectedValues() {
var options = fillings.options, values = [0];
for (var i=0; i < options.length; i++) {
if (options[i].selected) values.push(options[i].value);
}
return values;
}
function resetSelect() {
var options = fillings.options;
for (var i=0; i < options.length; i++) {
options[i].selected = false;
if (currentSelection.indexOf(options[i].value) != -1) {
options[i].selected = true;
}
}
}
fieldset {
margin: 1vw; font-family: monospace;
display: inline-block; width: 40vw; vertical-align: top;
}
legend { color: #d33; padding: 0px 4px; }
legend::before { content: '[ '; }
legend::after { content: ' ]'; }
fieldset > label { display: block; margin: 4px 0px; }
fieldset input, fieldset span { vertical-align: middle; }
fieldset > select { width: 100%; font-family: monospace; }
input[type=submit] { margin-top: 12px; }
#totalPrice, #result {
height: 24px; line-height: 24px;
background-color: #dde; padding: 4px;
font-family: monospace;
}
#result { color: #d33; font-family: monospace; }
<form action="" method="post" id="menuform" name="menuform">
<fieldset>
<legend>Select menu option</legend>
<label>
<input type="radio" name="selectedmenu" checked
value="menu01" data-qty='3' data-price='20' />
<span>1 - serves 3 courses ($20)</span>
</label>
<label>
<input type="radio" name="selectedmenu"
value="menu02" data-qty='4' data-price='25' />
<span>2 - serves 4 courses ($25)</span>
</label>
<label>
<input type="radio" name="selectedmenu"
value="menu03" data-qty='5' data-price='35' />
<span>3 - serves 5 courses ($35)</span>
</label>
<label>
<input type="radio" name="selectedmenu"
value="menu04" data-qty='6' data-price='75' />
<span>4 - serves 6 courses ($75)</span>
</label>
</fieldset>
<fieldset>
<legend id='fillingsPrompt'>Select fillings</legend>
<select id="fillings" name="fillings" size="6" multiple>
<option value="1">Dish 1 ($1)</option>
<option value="2">Dish 2 ($5)</option>
<option value="3">Dish 3 ($5)</option>
<option value="4">Dish 4 ($1)</option>
<option value="5">Dish 5 ($5)</option>
<option value="6">Dish 6 ($5)</option>
</select>
</fieldset>
<fieldset>
<legend>Checkout</legend>
<div id="totalPrice"></div>
<input type="submit" value="Submit" />
</fieldset>
<fieldset>
<legend>Messages</legend>
<p id="result"></p>
</fieldset>
</form>
<hr>
...how can I change <option> and use <input type="checkbox">
instead for the SECOND STEP?
In order to use checkboxes instead of select, no major changes are required.
Changed mark-up:
<fieldset>
<legend id='fillingsPrompt'>Select fillings</legend>
<label>
<input type='checkbox' name='fillings' value="1" />
<span>Dish 1 ($5)</span>
</label>
...
JavaScript changes:
Adding the event-handlers for checkboxes instead of select, would require just iterating over those:
(just like the radios already done)
for (var i = fillings.length; i--; ) {
fillings[i].addEventListener('change', handleFillings);
}
In all the helper functions, remove the variable declaration for options:
(as it is now no longer required)
var options = fillings.options
And, In all the helper functions,
change: options.length and options[i].selected
to, fillings.length and fillings[i].checked respectively.
That's it.
Fiddle 2: https://jsfiddle.net/abhitalks/hp88wdfc/
Snippet 2:
var menuform = document.getElementById('menuform'),
radios = document.getElementsByName('selectedmenu'),
fillings = document.getElementsByName('fillings'),
fillingsPrompt = document.getElementById('fillingsPrompt'),
totalPrice = document.getElementById('totalPrice'),
result = document.getElementById('result'),
fillingsAllowed = 0, currentSelection = [], currency = '$'
;
// listen to events
menuform.addEventListener('submit', handleSubmit);
for (var i = fillings.length; i--; ) {
fillings[i].addEventListener('change', handleFillings);
}
for (var i = radios.length; i--; ) {
radios[i].addEventListener('change', handleLimit);
}
// event handlers
function handleLimit(e) { updateParameters(e.target); }
function handleFillings(e) {
var count = getSelectedCount();
if (count > fillingsAllowed) { resetSelect(); }
else { currentSelection = getSelectedValues(); }
}
function handleSubmit(e) {
var count = getSelectedCount();
e.preventDefault();
if (count != fillingsAllowed) {
result.textContent = 'Must select exactly ' + fillingsAllowed + ' fillings!';
} else {
result.textContent = 'Ok. ';
}
}
// fire initial update based on the first radio
updateParameters(radios[0]);
// helper functions
function updateParameters(elem) {
fillingsAllowed = elem.getAttribute('data-qty');
totalPrice.textContent = 'Amount: ' + currency + elem.getAttribute('data-price');
fillingsPrompt.textContent = 'Select ' + fillingsAllowed + ' fillings';
}
function getSelectedCount() {
var count = 0;
for (var i=0; i < fillings.length; i++) {
if (fillings[i].checked) count++;
}
return count;
}
function getSelectedValues() {
var values = [0];
for (var i=0; i < fillings.length; i++) {
if (fillings[i].checked) values.push(fillings[i].value);
}
return values;
}
function resetSelect() {
for (var i=0; i < fillings.length; i++) {
fillings[i].checked = false;
if (currentSelection.indexOf(fillings[i].value) != -1) {
fillings[i].checked = true;
}
}
}
fieldset {
margin: 1vw; font-family: monospace;
display: inline-block; width: 40vw; vertical-align: top;
}
legend { color: #d33; padding: 0px 4px; }
legend::before { content: '[ '; }
legend::after { content: ' ]'; }
fieldset:first-of-type > label { display: block; margin: 4px 0px; }
fieldset:nth-of-type(2) > label {
display: inline-block; width: 45%;
}
fieldset input, fieldset span { vertical-align: middle; }
input[type=submit] { margin-top: 12px; }
#totalPrice, #result {
height: 24px; line-height: 24px;
background-color: #dde; padding: 4px;
font-family: monospace;
}
#result { color: #d33; font-family: monospace; }
<form action="" method="post" id="menuform" name="menuform">
<fieldset>
<legend>Select menu option</legend>
<label>
<input type="radio" name="selectedmenu" checked
value="menu01" data-qty='3' data-price='20' />
<span>1 - serves 3 courses ($20)</span>
</label>
<label>
<input type="radio" name="selectedmenu"
value="menu02" data-qty='4' data-price='25' />
<span>2 - serves 4 courses ($25)</span>
</label>
<label>
<input type="radio" name="selectedmenu"
value="menu03" data-qty='5' data-price='35' />
<span>3 - serves 5 courses ($35)</span>
</label>
<label>
<input type="radio" name="selectedmenu"
value="menu04" data-qty='6' data-price='75' />
<span>4 - serves 6 courses ($75)</span>
</label>
</fieldset>
<fieldset>
<legend id='fillingsPrompt'>Select fillings</legend>
<label>
<input type='checkbox' name='fillings' value="1" />
<span>Dish 1 ($5)</span>
</label>
<label>
<input type='checkbox' name='fillings' value="2" />
<span>Dish 2 ($5)</span>
</label>
<label>
<input type='checkbox' name='fillings' value="3" />
<span>Dish 3 ($5)</span>
</label>
<label>
<input type='checkbox' name='fillings' value="4" />
<span>Dish 4 ($5)</span>
</label>
<label>
<input type='checkbox' name='fillings' value="5" />
<span>Dish 5 ($5)</span>
</label>
<label>
<input type='checkbox' name='fillings' value="6" />
<span>Dish 6 ($5)</span>
</label>
</fieldset>
<fieldset>
<legend>Checkout</legend>
<div id="totalPrice"></div>
<input type="submit" value="Submit" />
</fieldset>
<fieldset>
<legend>Messages</legend>
<p id="result"></p>
</fieldset>
</form>
<hr>

inner html radio button array value getting over written in for loop

I have written this code which should simply display the user's selection based on radio button clicked, There are multiple groups of radio buttons in the one form
<form name="makePicks">
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks1" value="Chiefs"><span>Chiefs</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks1" value="Hurricanes"><span>'Hurricanes'</span>
</label>
<label class="pink">
<input type="radio" name="picks1" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks2" value="Lions"><span>Lions</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks2" value="Stormers"><span>'Stormers'</span>
</label>
<label class="pink">
<input type="radio" name="picks2" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
</form>
<div id="dispPicks">
</div>
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
//var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
document.getElementById("dispPicks").innerHTML="YOU HAVE SELECTED "+radios[i].value
//found = 0;
//break;
}
}
//if (found == 1) {
//alert("Please Select Radio");
//}
//event.preventDefault(); // disable normal form submit behavior
return false;
}
My problem is
The value of the array radios[i].value gets over written as you can see in the image below
In this example cheifs and Stormers both needs to be displayed, since it was selected
If anyone can help me with correct implementation it would be very much appreciated
I created a fiddle at this link https://jsfiddle.net/taditdash/w8hpQ/
You can modify your JavaScript code like this:
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
myradiovalue = "";
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
if (myradiovalue=="")
myradiovalue=radios[i].value
else
myradiovalue=myradiovalue+ ", " +radios[i].value
}
}
document.getElementById("dispPicks").innerHTML = "YOU HAVE SELECTED " + myradiovalue;
return false;
}

Make a matrix with input inside a DIV by mixing input values

Take a look at this:
<div id="main">
<div id="a">
<input value="1" />
<input value="2" />
<input value="3" />
</div>
<div id="b">
<input value="4" />
<input value="5" />
</div>
</div>
I need to get each input value inside div#a and each input value in div#b and build a matrix/mixing of those values, taking the same example as before, this is what the code should return:
<div id="mixed">
<input value="1" /><input value="4" />
<input value="1" /><input value="5" />
<input value="2" /><input value="4" />
<input value="2" /><input value="5" />
<input value="3" /><input value="4" />
<input value="3" /><input value="5" />
</div>
I have tried to move inside div#main using this code:
$("#main div").each(function() {
var that = $(this);
console.log("that.attr('id')");
});
But console.log() never logs something so I must doing something wrong. This is a advanced topic for me and need some help, any?
UPDATE
At this point I have this maded:
$("#choices div").each(function() {
var that = $(this);
that.each(function() {
var thati = $(this);
console.log(thati);
});
});
And I think in the second .each() is where I can get the input values and try to build the matrix
Should help:
var arr = [];
$('#a input').each(function () {
var that = $(this);
$('#b input').each(function () {
arr.push(that.val());
arr.push($(this).val());
});
});
Then go through the array and dynamically generate the HTML. You can treat this like a matrix by stepping every 2 values.
var a = $('#a input');
var b = $('#b input');
var html = '';
a.each(function () {
var first = this;
b.each(function () {
html += '<div>' + first.outerHTML + this.outerHTML + '</div>'
});
});
$('#mix').html(html);
jsFiddle here
update: code for what's asked for in comments.
var divs = $('#main > div');
var html = '';
divs.each(function (index) {
var divsLength = divs.length,
inputs = $('input', divs[index]),
inputsLength = inputs.length;
for (var i = 0; i < divsLength; i++) {
if (i === index) {
continue;
}
for (var j = 0; j < inputsLength; j++) {
$('input', divs[i]).each(function () {
html += inputs[j].outerHTML + this.outerHTML + '<br />';
});
}
}
});
$('#mix').html(html);

Categories