Javascript: Radio button and displaying images based on a vaule - javascript

I am currently working with displaying images based on the value chosen from a radio button. But I am currently running into a wall with making the code as short and efficient as possible. I have several categories to choose from and they way i am approaching the issue will require for me to write several check_value#. Is there a way to combine those two functions? so in the future if i have 5 or 7 categories i wont have to have a function for each. EXAMPLE
<script>
function check_value(val) {
var el = document.getElementById("imgBox1");
var img = imgs[val];
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/bike" + val + ".jpg";
el.style.display = "";
}
}
function check_value1(val) {
var el = document.getElementById("imgBox2");
var img = imgs[val];
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/tire" + val + ".jpg";
el.style.display = "";
}
}
</script>
HTML
<h2>Choose a bike</h2>
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(0)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(2)'/> Aprilia RSV4<br />
</form>
<img id="imgBox1" src="#" style="display:none">
<h2>Choose a tire</h2>
<form name="tire">
<input type="radio" name="field" value="1" onclick='check_value1(0)'/> Michelin Pilot Road 3 Tires<br />
<input type="radio" name="field" value="2" onclick='check_value1(1)'/> Dunlop Roadsmart Sport-Touring Tires<br />
<input type="radio" name="field" value="3" onclick='check_value1(2)'/> Pirelli Scorpion Trail Tires<br />
</form>
<img id="imgBox2" src="#" style="display:none">

try this, updated
make image name as bike#.jpg , tire#.jpg
bike0.jpg, bike1.jpg, bike2.jpg....
function check_value(val, id, type) {
var el = document.getElementById("imgBox" + id);
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/"+ type + val + ".jpg";
el.style.display = "";
}
}
<h2>Choose a bike</h2>
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(0, 1, "bike")'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1, 1, "bike")'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(2, 1, "bike")'/> Aprilia RSV4<br />
</form>
<img id="imgBox1" src="#" style="display:none">
<h2>Choose a tire</h2>
<form name="tire">
<input type="radio" name="field" value="1" onclick='check_value(0, 2, "tire")'/> Michelin Pilot Road 3 Tires<br />
<input type="radio" name="field" value="2" onclick='check_value(1, 2, "tire")'/> Dunlop Roadsmart Sport-Touring Tires<br />
<input type="radio" name="field" value="3" onclick='check_value(2, 2, "tire")'/> Pirelli Scorpion Trail Tires<br />
</form>
<img id="imgBox2" src="#" style="display:none">

Here is a fiddle for you, using custom HTML attributes, and the jQuery Javascript library:
Obviously you'd want to actually set the image's source, rather than displaying the url in a paragraph, but you get the idea, I'm sure.
// html
<input type="radio" name="tire" img-preview="tire-preview" img-loc="tire/1.jpg" /> First<br>
<input type="radio" name="tire" img-preview="tire-preview" img-loc="tire/2.jpg" /> Second<br>
<p id="tire-preview">
Load: -
</p>
<input type="radio" name="wheel" img-preview="wheel-preview" img-loc="wheel/1.jpg" /> Uno<br>
<input type="radio" name="wheel" img-preview="wheel-preview" img-loc="wheel/2.jpg" /> Dos<br>
<p id="wheel-preview">
Load: -
</p>​
// js
$("input[type=radio]").click(function(){
var imageUri = "http://site.com/images/" + $(this).attr("img-loc");
$("#" + $(this).attr("img-preview") ).text("Load: " + imageUri);
});​

You can use this
<script>
function call(formNo,val)
{if()//give your checkings here according to what you want
{}
alert(formNo+" "+val); //just for example what values you are getting
}
</script>
<h2>Choose a bike</h2>
<form name="builder" id="1">
<input type="radio" name="field" value="1" onclick='check_value(1,0)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1,1)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(1,2)'/> Aprilia RSV4<br />
</form>
<img id="imgBox1" src="#" style="display:none">
<h2>Choose a tire</h2>
<form name="tire" id="2">
<input type="radio" name="field" value="1" onclick='check_value1(2,0)'/> Michelin Pilot Road 3 Tires<br />
<input type="radio" name="field" value="2" onclick='check_value1(2,1)'/> Dunlop Roadsmart Sport-Touring Tires<br />
<input type="radio" name="field" value="3" onclick='check_value1(2,2)'/> Pirelli Scorpion Trail Tires<br />
</form>
<img id="imgBox2" src="#" style="display:none">

Related

Event listeners for both radio buttons and text input

I have a group of radio buttons and a text input field:
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
And I wanna the result of final price calculated by Price * Discount and updating the <p id="resultToast"> </p>.
So I did
const radios = document.querySelector('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
From the console, the radios.value not updated correctly after clicking the radio buttons. What I did wrong?
Just change:
const radios = document.querySelector('input[name="discount"]:checked');
To:
const radios = document.querySelectorAll('input[name="discount"]:checked');
See working snippet:
const radios = document.querySelectorAll('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
Reason for this is because you stored the initial
document.querySelector('input[name="discount"]:checked');
value as radios. Now that we look for all, it changes accordingly.
You are referring to a constant you defined at the beginning of your script. This will always give you the same radio button value (the one being checked at the beginning). Do something like
let discount=document.querySelector("input[name=discount]:checked").value
within your event handler function to get the current value of the radio button group.
You could also declutter(=shorten) your code a bit and make it reusable for multiple input sections that way, see below:
function qs(sel,el){return (el||document).querySelector(sel);}
function makeInteractive(frmsel){
const frm=qs(frmsel),
prc=qs("[name=price]",frm),
res=qs(".result",frm);
frm.onchange=calc;
frm.oninput= calc;
function calc(){
res.textContent=
(prc.value * qs("[type=radio]:checked",frm).value)
.toFixed(2);
}
}
makeInteractive("#frm1");
makeInteractive("#frm2");
<form id="frm1">
the first item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>
<form id="frm2">
the second item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>

Changing Submit Button from "button" to "submit" Broke My Google Apps Script

I used this to build a form in Google Apps that allows employees to fill out a form and attach a document that all feeds into a spreadsheet.
My issue now is I need to make certain fields required. I did so by adding the "required" attribute to those fields. That didn't work, so I realized I need to change my submit button from type="button" to type="submit," however, upon doing THAT...my form now doesn't work.
I can't find anything in any of the code that points to only type="button" working to submit the form.
I've included my code below, as well as a link to my sheet/script if anyone wants to poke around in there!
Code.gs
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var email = template.email = theForm.email;
var brand = template.brand = theForm.brand;
var date = template.date = theForm.date;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var manufacturer = template.manufacturer = theForm.manufacturer;
var pace = template.pace = theForm.pace;
var reason = template.reason = theForm.reason;
var category = template.category = theForm.category;
var subcategory = template.subcategory = theForm.subcategory;
var message = template.message = theForm.message;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 13).setValues([[name, email,brand,date,amount,split,manufacturer,pace,reason,category,subcategory,message,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
Form.html
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//Toggle Secondary Categories
$(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
//Calculate Split
function check(split)
{
var split=document.forms[0].split.value
var amount=document.forms[0].amount.value
var tip = (amount*split)
document.forms[0].manufacturer.value=tip
var tip2 = (amount-tip)
document.forms[0].pace.value=tip2
}
</script>
<div id="formDiv" class="form">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
<div class="row">
<h1>Co-op Submission Form</h1>
<h2>Please fill out the form completely, including uploading any documentation associated with your co-op claim.</h2>
</div>
<h3>Your Information</h3>
<h4>Name:</h4> <input name="name" type="text" class="form-control" required/><br/>
<h4>Email:</h4> <input name="email" type="text" class="form-control"required/><br/>
<h3>Co-Op Information</h3>
<h4>Brand:</h4>
<select name="brand" class="form-control" required>
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Jonsered</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
<h4>Invoice Date:</h4> <input name="date" type="text" class="form-control"/><br/>
<h4> Total Co-Op Amount</h4> <input type="text" name="amount" class="form-control"/><br />
<h4>Co-Op Split:</h4>
<input type="radio" name="split" onclick="check(this.value)" value="1">100%<br>
<input type="radio" name="split" onclick="check(this.value)" value=".5">50/50<br>
<input type="radio" name="split" onclick="check(this.value)" value=".75">75/25<br />
<input type="radio" name="split" onclick="check(this.value)" value=".25">25/75 (Dealer Pays 50%)<br />
<h4>Manufacturer Amount:</h4> <input type="text" name="manufacturer" style="border:none;font-weight:bold;"><br />
<h4>Pace Amount:</h4> <input type="text" name="pace" style="border:none;font-weight:bold;" >
<h4>Description:</h4> <input name="reason" type="text" cols="20" rows="5" class="form-control" required/><br />
<h4>Co-Op Category:</h4>
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" class="form-control"/><br />
<!--Dealer Advertising-->
<div class="dealer box" style="display:none;">
<h4>Dealer Advertising:</h4>
<input type="radio" name="subcategory" value="Billboards">Billboards<br />
<input type="radio" name="subcategory" value="Logo Merch">Logo Merch (hats, shirts, pens, etc.)<br />
<input type="radio" name="subcategory" value="Magazine/Newspaper">Magazine/Newspaper<br />
<input type="radio" name="subcategory" value="Open House/Trade Show">Open House & Dealer Trade Show<br />
<input type="radio" name="subcategory" value="POP">POP (lit, posters,displays, etc)<br />
<input type="radio" name="subcategory" value="Radio">Radio<br />
<input type="radio" name="subcategory" value="PACE Trade Show">PACE Trade Show<br />
<input type="radio" name="subcategory" value="TV">TV<br />
<input type="radio" name="subcategory" value="Direct Mail">Direct Mail (post cards, flyers)<br />
<input type="radio" name="subcategory" value="Sponsorships">Sponsorships<br />
</div>
<!--Digital/Online Advertising-->
<div class="online box" style="display: none;">
<h4>Digital/Online Marketing:</h4>
<input type="radio" name="subcategory" value="CMS/Advertising">CMS/Dealer Website Advertising<br />
<input type="radio" name="subcategory" value="TRM Digital Marketing">TRM Digital Marketing (google, facebook, retargeting, demo site, youtube)
</div>
<!--Meetings and Schools-->
<div class="meetings box" style="display: none;">
</div>
<!--PACE Advertising-->
<div class="advertising box" style="display: none;">
<h4>PACE Advertising:</h4>
<input type="radio" name="subcategory" value="Billboards">Billboards<br />
<input type="radio" name="subcategory" value="Logo Merch">Logo Merch (hats, shirts, pens, etc.)<br />
<input type="radio" name="subcategory" value="POP">POP (lit, posters,displays, etc)<br />
<input type="radio" name="subcategory" value="PACE Trade Show">PACE Trade Show<br />
</div>
<!--Program Pricing Promotions-->
<div class="pricing box" style="display: none;">
<h4>Program Pricing Promotions:</h4>
<input type="radio" name="subcategory" value="Promo Prices, Discounts, Rebates - Unassigned">Promo Prices, Discounts, Rebates - Unassigned<br />
<input type="radio" name="subcategory" value="Promo Pricing">Promo Pricing<br />
<input type="radio" name="subcategory" value="Demo">Demo<br />
<input type="radio" name="subcategory" value="Fleet">Fleet<br />
<input type="radio" name="subcategory" value="Spiffs and Rebates">Spiffs and Rebates<br />
</div>
<!--PACE-to-Dealer Correspondence-->
<div class="correspondence box" style="display: none;">
<h4>PACE-to-Dealer Correspondence:</h4>
<input type="radio" name="subcategory" value="Pacesetter Catalog">Pacesetter Catalog<br />
<input type="radio" name="subcategory" value="Dealer Programs (updates, reprints)">Dealer Programs (updates, reprints)<br />
</div>
<h4>Message:</h4> <textarea name="message" class="form-control"></textarea><br/>
<h4> Supporting Documentation:</h4><input name="myFile" type="file"/><br />
<input type="submit" value="Submit" class="btn" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</div>
<!--Begin Footer-->
<div class="footer">
<div class="bottomStrip">
<div class="col-lg-3 col-lg-push-1">© <script type="text/javascript"> document.write(new Date().getFullYear());</script>, PACE, Inc. All rights Reserved.</div>
<div class="col-lg-4 col-lg-push-5">PACE, Inc., 739 S. Mill St., Plymouth, MI 48170-1821</div>
</div>
</div>
<!--End Footer-->
</body>
</html>
The Sheet (I did remove everything from the 'Name' and 'Email' columns, as that contained several of my co-workers' full names and email addresses!)
There's an onclick handler on the input 'submit' button:
google.script.run.withSuccessHandler(updateOutput).processForm(this.parentNode)
Submitting the form will use this script, not the default input submit behaviour. So when you change the type from button to submit, you have to change the script to prevent the default submit behaviour from triggering.

Totalling the value of two radio buttons as a shopping cart

The issue is:
I have four radio buttons and a check box.
Two radio buttons are with one name and two with another.
The last radio buttons with same name appear only when the check box is checked.
What I want is add the value of first radio button and the value of radio button that appears after the checkbox is checked.
So how do I total the two values using javascript or any other technique. I need it asap as I am working on a project. I need that to be done as in a shopping cart. It means if the user selects another radio button then the value of earlier one should be subtracted and the value of new one added.
<script>
// get list of radio buttons with name 'size'
var sz = document.forms['de'].elements['type'];
// loop through list
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var m=this.form.elements.total.value = this.value;
};
}
var sa = document.forms['de'].elements['glass'];
// loop through list
for (var i=0, len=sa.length; i<len; i++) {
sa[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var n=this.form.elements.total1.value = this.value;
};
}
$(document).ready(function () {
$('.a').hide();
$('#checkb').click(function () {
var $this = $(this);
if ($this.is(':checked')) {
$('.a').show();
} else {
$('.a').hide();
}
});
});
</script>
<form action="sum.php" method="post" name="de">
<fieldset>
<table align="center">
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<tr><td colspan="100sp"><label>Do You want a screen guard or a tempered glass?</label><input type="checkbox" name="screen" value="yes" id="checkb" />
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
</table>
<p><label>Repair: Rs. <input type="text" name="total" value="0" readonly="readonly" /></label></p>
<p><label>Glass: Rs. <input type="text" name="total1" value="0" readonly="readonly" /></label></p>
<p><label>Total: Rs. <input type="text" name="total2" value="0" readonly="readonly" /></label></p>
</fieldset>
</form>
You can do this with the Jquery event Change(). I have added ID names to the input text elements and this Jquery lines:
Check the comments for each line.
$(document).ready(function() {
//HIDE AND SHOW EXTRA OPTIONS
$('.a').hide();
$('#checkb').change(function() {
$('.a').toggle();
});
//CHECK WHEN ANY RADIO INPUT CHANGES
$('fieldset').on('change','input[type=radio]',function(){
//Get the Value and wich field text will change
var value = $(this).attr('value'),
target = $(this).attr('name');
$('#'+target).val(value);
//Show the total
var total = parseInt($('#type').val(),10) + parseInt($('#glass').val(),10);
$('#total').val(total);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<label>
<input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<br>
<label>
<input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<br>
<input type="checkbox" name="screen" value="yes" id="checkb" />
<label>Do You want a screen guard or a tempered glass?</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
<br>
<p>
<label>Repair: Rs.
<input type="text" id="type" name="total" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Glass: Rs.
<input type="text" id="glass" name="total1" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Total: Rs.
<input type="text" id="total" name="total2" value="0" readonly="readonly" />
</label>
</p>
</fieldset>
</form>
You can do it by using a facility given by jquery. Please check the below code
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<script type="text/javascript">
var total = 0;
$('.myradio').on('click',function(){
//Here you can get the checkbox value from data-value attribute
alert($(this).data('value');
//Total the Values
total = total + $(this).data('value');
});
</script>
In above code you can easily get the data from checkbox when it is clicked...

Dropdownchecboxes selected value validation in javascript

I have a DropDownCheckBoxes where I can CHECK multiple items from the list. Now what I want is,
A validation on button click for multiple Items selected must be from the same month if the selected items are not from the same month then it should prompt an alert message for selecting the items as for same month.
For ex:- If first selected item from the list is of April then the user has to select the next item from April only, if other month selected than it should throw an alert message.
Here is the screenshot of my DropDownCheckBoxes
[![DropDownCheckBoxes][1]][1]
Below is my code which I tried first for getting selected value of the list but got an error as
Line: 13
Error: 'options' is null or not an object
See the js fiddle for my code [HERE][2]
kindly suggest what is wrong and how to validate the user on button click for the same.
So I took a look at your code. And since I didn't know it you wanted it in plain Javascript or jQuery, I took the liberty of doing it in jQuery (since it's easier).
Also I don't know the true purpose of your code, so I based it upon your example and the information you gave us. This might give you an idea on how to complete your task.
Either run the snippet below or take a look at this fiddle.
/* Slide open menu and change arrow direction */
$("#caption").click(function() {
$("#cmbEmp_Name_dv").slideToggle();
$("#down, #up").toggle();
});
/* On change disable all checkboxes from different months */
$("input[type='checkbox']").change(function() {
var amountChecked = $("input[type='checkbox']:checked").length;
if (amountChecked === 1) {
var month = getMonth($(this).next().html());
$("input[type='checkbox']").each(function() {
var myMonth = getMonth($(this).next().html());
if (month !== myMonth) {
$(this).prop("disabled", true);
$(this).next().css("background-color", "gray");
}
});
}
if (amountChecked === 0)
$("input[type='checkbox']").prop("disabled", false).next().css("background-color", "transparent");
});
/* Function to check if all checked options are from the same month */
$("#btnSubmit").click(function() {
var firstSelected = $("input:checked").first().next().html();
if (firstSelected !== undefined && firstSelected !== "undefined" && firstSelected && firstSelected != "") {
var firstMonth = getMonth(firstSelected);
var isNotEqual = false;
$("input:checked").each(function() {
var month = getMonth($(this).next().html());
if (firstMonth !== month)
isNotEqual = true;
});
if (isNotEqual)
alert("Please check items from the month " + firstMonth);
else
alert("Validation complete - good to go!");
}
else
{
alert("Select an option first!");
$("#cmbEmp_Name_dv").slideDown();
}
});
/* Function to strip off all characters and return the month */
function getMonth(html) {
var monthPart = html.split("(").length > 1 ? html.split("(")[1] : "-";
return monthPart.substr(0, monthPart.indexOf("-")).trim();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cmbEmp_Name_sl" class="dd_chk_select" style="display:inline-block;position:relative;width:55%;">
<div id="caption">
Select <span id="down">↓</span><span id="up" style="display: none;">↑</span>
</div>
<div id="cmbEmp_Name_dv" class="dd_chk_drop" style="display:none;position:absolute;width:500px;">
<div id="checks" style="height:45%;">
<input id="cmbEmp_Name_0" type="checkbox" name="cmbEmp_Name$0" />
<label for="cmbEmp_Name_0">--Select--</label><br />
<input id="cmbEmp_Name_1" type="checkbox" name="cmbEmp_Name$1" />
<label for="cmbEmp_Name_1">ANIL VITTHAL GAWADE-312(April - 2016)</label><br />
<input id="cmbEmp_Name_2" type="checkbox" name="cmbEmp_Name$2" />
<label for="cmbEmp_Name_2">ANURADHA A. DESHMUKH-53(April - 2016)</label><br />
<input id="cmbEmp_Name_3" type="checkbox" name="cmbEmp_Name$3" />
<label for="cmbEmp_Name_3">ASMA SIDDIQUI-83(April - 2016)</label><br />
<input id="cmbEmp_Name_4" type="checkbox" name="cmbEmp_Name$4" />
<label for="cmbEmp_Name_4">DEEPTI MAITHIL-1250(April - 2016)</label><br />
<input id="cmbEmp_Name_5" type="checkbox" name="cmbEmp_Name$5" />
<label for="cmbEmp_Name_5">GAURAV JHUNJHUNWALA-2222(March - 2016)</label><br />
<input id="cmbEmp_Name_6" type="checkbox" name="cmbEmp_Name$6" />
<label for="cmbEmp_Name_6">HITESH PANCHAL-253(April - 2016)</label><br />
<input id="cmbEmp_Name_7" type="checkbox" name="cmbEmp_Name$7" />
<label for="cmbEmp_Name_7">JAGDISH UBARE-362(April - 2016)</label><br />
<input id="cmbEmp_Name_8" type="checkbox" name="cmbEmp_Name$8" />
<label for="cmbEmp_Name_8">JAIDEEP MAHAKAL-134(April - 2016)</label><br />
<input id="cmbEmp_Name_9" type="checkbox" name="cmbEmp_Name$9" />
<label for="cmbEmp_Name_9">JASMINE RATHOD-228(April - 2016)</label><br />
<input id="cmbEmp_Name_10" type="checkbox" name="cmbEmp_Name$10" />
<label for="cmbEmp_Name_10">JIGAR SHAH-358(April - 2016)</label><br />
<input id="cmbEmp_Name_11" type="checkbox" name="cmbEmp_Name$11" />
<label for="cmbEmp_Name_11">Junaid Chaudhary-2487(April - 2016)</label><br />
<input id="cmbEmp_Name_12" type="checkbox" name="cmbEmp_Name$12" />
<label for="cmbEmp_Name_12">KAMAL MATALIA-17(April - 2016)</label><br />
<input id="cmbEmp_Name_13" type="checkbox" name="cmbEmp_Name$13" />
<label for="cmbEmp_Name_13">KETAN NALAWADE-2478(April - 2016)</label><br />
<input id="cmbEmp_Name_14" type="checkbox" name="cmbEmp_Name$14" />
<label for="cmbEmp_Name_14">KRUPA DAVE-349(April - 2016)</label><br />
<input id="cmbEmp_Name_15" type="checkbox" name="cmbEmp_Name$15" />
<label for="cmbEmp_Name_15">NEHA ARUN KHANNA-2145(March - 2016)</label><br />
<input id="cmbEmp_Name_16" type="checkbox" name="cmbEmp_Name$16" />
<label for="cmbEmp_Name_16">NILESH GAIKWAD-903(March - 2016)</label><br />
<input id="cmbEmp_Name_17" type="checkbox" name="cmbEmp_Name$17" />
<label for="cmbEmp_Name_17">PALLAVI KATHAL-2465(April - 2016)</label><br />
<input id="cmbEmp_Name_18" type="checkbox" name="cmbEmp_Name$18" />
<label for="cmbEmp_Name_18">RAMESH SANAP-1855(March - 2016)</label><br />
<input id="cmbEmp_Name_19" type="checkbox" name="cmbEmp_Name$19" />
<label for="cmbEmp_Name_19">SAKINA VIVIAN DSILVA-2392(April - 2016)</label><br />
<input id="cmbEmp_Name_20" type="checkbox" name="cmbEmp_Name$20" />
<label for="cmbEmp_Name_20">SAMANTHA SAXENA-2442(April - 2016)</label><br />
<input id="cmbEmp_Name_21" type="checkbox" name="cmbEmp_Name$21" />
<label for="cmbEmp_Name_21">SANGEETA JIJI RANE-314(April - 2016)</label><br />
<input id="cmbEmp_Name_22" type="checkbox" name="cmbEmp_Name$22" />
<label for="cmbEmp_Name_22">SARVESH SUBHASH CHAUDHARY-2462(March - 2016)</label><br />
<input id="cmbEmp_Name_23" type="checkbox" name="cmbEmp_Name$23" />
<label for="cmbEmp_Name_23">SAYED SOHAIL JAVED AKHTAR-2014(April - 2016)</label><br />
<input id="cmbEmp_Name_24" type="checkbox" name="cmbEmp_Name$24" />
<label for="cmbEmp_Name_24">SHALIBHADRA HAKANI-2158(April - 2016)</label><br />
<input id="cmbEmp_Name_25" type="checkbox" name="cmbEmp_Name$25" />
<label for="cmbEmp_Name_25">SONAL RAVINDRA AMBEDE-2533(March - 2016)</label><br />
<input id="cmbEmp_Name_26" type="checkbox" name="cmbEmp_Name$26" />
<label for="cmbEmp_Name_26">SRINIVAS VENKANNA SAMUDRALA-2525(March - 2016)</label><br />
<input id="cmbEmp_Name_27" type="checkbox" name="cmbEmp_Name$27" />
<label for="cmbEmp_Name_27">SUNIL DESAI-2484(March - 2016)</label><br />
<input id="cmbEmp_Name_28" type="checkbox" name="cmbEmp_Name$28" />
<label for="cmbEmp_Name_28">UMANG DARJI-2239(March - 2016)</label><br />
<input id="cmbEmp_Name_29" type="checkbox" name="cmbEmp_Name$29" />
<label for="cmbEmp_Name_29">UMESH VASHISTH-1900(March - 2016)</label><br />
<input id="cmbEmp_Name_30" type="checkbox" name="cmbEmp_Name$30" />
<label for="cmbEmp_Name_30">VISHAL SUBHASH PAWADE-1881(March - 2016)</label>
</div>
</div>
</div>
&nbsp&nbsp
<input type="submit" name="btnSubmit" value="Process" id="btnSubmit" />
Notice
I did implement #Freak his suggestion, by disabling all the options different from the user his first choice.
On the other hand, I also implemented the check on the Validate button, where as it will check if the user may or may not have checked a different month. Just in case.

Javascript, how can i make tick boxes required when an answer is placed in a text box

<tr>
<td><b>If the registration is for either a Consultant or End User Business</b></td>
<td> </td> <td>Please tick box (multiple choice) their area of business</td></tr Question being asked
<td align="right"><b>Consultant or End User: </b>
<td><font color="red">*</font></td>
<td><input type="checkbox" name="Data" value="Yes">Data Centres
<br />
<input type="checkbox" name="Power" value="Yes">Power Plants
<br />
<input type="checkbox" name="Mining" value="Yes">Mining
<br />
<input type="checkbox" name="Telecom" value="Yes">Telecom
<br />
<input type="checkbox" name="Governmental" value="Yes">Governmental
<br />
<input type="checkbox" name="Airports" value="Yes">Airports
<br />
<input type="checkbox" name="Hotel" value="Yes">Hotel/Residential
<br />
<input type="checkbox" name="Healthcare" value="Yes">Healthcare
<br />
<input type="checkbox" name="Shopping" value="Yes">Shopping Complex
<br />
<input type="checkbox" name="Industries" value="Yes">Industries / Manufacturing
<br />
<input type="checkbox" name="Transport" value="Yes">Transport
<br />
<input type="checkbox" name="Utilities" value="Yes">Utilities
<br />
<input type="checkbox" name="Water" value="Yes">Water Treatment
<br />
<input type="checkbox" name="Construction" value="Yes">Construction
<br />
<input type="checkbox" name="Other" value="Yes">Other
<br />
</td> </tr> <tr> <td colspan="3" align="center" bgcolor="#dadada"> </tr>
<tr>
checkboxes to be ticked if answer provided
UPDATE : Here is the code for textfield
<tr>
<td align="right"><strong>Consulting Company Name: </strong><font color="red">*</font></td>
<td><input size="30" name="ConCompany" class="required"/></td>
</tr>
in first step I would add an id to your textfield, that you can add an eventhandler via JavaScript.
<td><input id="company" size="30" name="ConCompany" class="required"/></td>
Add Eventhandler:
document.getElementById('company').addEventListener('change', setCheckboxesRequired);
Create function to set all checkboxes required:
function setCheckboxesRequired() {
var allInputs, allCheckboxes, textValue, bSetRequired, tmpInput, tmpCheckbox;
// Retrieve all input elements
allInputs = document.getElementsByTagName('input');
allCheckboxes = [];
// put all inputs with type = checkbox in allCheckboxes variable
for (var i = 0; i < allInputs.length; i++) {
tmpInput = allInputs[i];
if (tmpInput.type === 'checkbox') {
allCheckboxes.push(tmpInput);
}
}
// determine if class should be set
textValue = document.getElementById('company').value;
if (textValue === null || textValue === "") {
bSetRequired = false;
} else {
bSetRequired = true;
}
// iteration through all checkboxes
for (var j = 0; j < allCheckboxes.length; j++) {
tmpCheckbox = allCheckboxes[j];
// set or delete class
if (bSetRequired) {
tmpCheckbox.className = tmpCheckbox.className + ' required';
} else {
tmpCheckbox.className = tmpCheckbox.className.replace('required', '');
}
}
}
Or if you want to set HTML5 required-attribute instead of your 'required'-class change the last for-loop to the following:
for (var j = 0; j < allCheckboxes.length; j++) {
tmpCheckbox = allCheckboxes[j];
tmpCheckbox.required = bSetRequired;
}
use a button with some id like submitbtn button like
<input type="button" id="submitbtn" value="Submit" />
Add id to your textbox like id=ConCompany
dd ids to your checkboxes like this:
<input type="checkbox" name="Data" id="10" value="Yes">Data Centres
<br />
<input type="checkbox" name="Power" id="11" value="Yes">Power Plants
<br />
<input type="checkbox" name="Mining" id="12" value="Yes">Mining
<br />
<input type="checkbox" name="Telecom" id="13" value="Yes">Telecom
<br />
<input type="checkbox" name="Governmental" id="14" value="Yes">Governmental
<br />
<input type="checkbox" name="Airports" id="15" value="Yes">Airports
<br />
<input type="checkbox" name="Hotel" id="16" value="Yes">Hotel/Residential
<br />
<input type="checkbox" name="Healthcare" id="17" value="Yes">Healthcare
<br />
<input type="checkbox" name="Shopping" id="18" value="Yes">Shopping Complex
<br />
<input type="checkbox" name="Industries" id="19" value="Yes">Industries / Manufacturing
<br />
<input type="checkbox" name="Transport" id="20" value="Yes">Transport
<br />
<input type="checkbox" name="Utilities" id="21" value="Yes">Utilities
<br />
<input type="checkbox" name="Water" id="22" value="Yes">Water Treatment
<br />
<input type="checkbox" name="Construction" id="23" value="Yes">Construction
Now use the following javascript :
document.getElementById('submitbtn').onclick = function () {
if(document.getElementById('ConCompany').value != "")
{
var count = 0;
for ( var i = 10 ; i <= 23 ; i++)
{
if(document.getElementById(i).value == "Yes")
count++;
}
if(count == 0)
{
alert("Please select the area of business ");
return;
}
}
document.FormName.submit();
}

Categories