I'm looking for a way to add another value into my input text. I have a read only input box, two radio buttons, and three checkboxes.
<div class="radios">
<label>
<input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
</label>
<label>
<input type="radio" name="extratreats" data-target="#extratreat"> Extra-Treats
</label>
</div>
<div id="extratreat" class="extratreat tab-pane collapse">
<label><h2>Extra Treats</h2></label>
<br />
<label><input id="treats" name="treats[]" value="Sweet Corner" type="checkbox" > Sweet Corner & Choco Fountain</label>
<label><input id="treats" name="treats[]" value="Popcorn Maker" type="checkbox" > Popcorn Maker</label>
<label><input id="treats" name="treats[]" value="Hotdog Roller" type="checkbox" > Hotdog Roller</label>
</div>
<div id="pricing">
<label><h2>Price</h2></label>
<br />
<input type="text" name="price-total" value="" autocomplete="off" readonly>
</div>
I've added a javascript to my radio button where if I click on non-exlusive the value of pricing will change to 279. But I don't know how to add more value to if I add from treats. For example the price of Sweet Corner is 2,500 and they also clicked on Non-Exlusive which has 279 as it's default value, how do I add 2,500 to the already specified 279?
Here's the script I tried using:
<script>
$(document).ready(function(){
$('[name=packages]').click(function() {
var val = $(this).val();
if (val == "non-exclusive") {
$('[name=price-total]').val('PHP 279');
} else if (val == "package1") {
$('[name=price-total]').val('PHP 300');
} else if (val == "package2") {
$('[name=price-total]').val('PHP 400');
}
});
$('[id=treats').click(function() {
var val1 = $(this).val();
var val = $('[name=price-total]').val();
if (val1 == "Sweet Corner") {
$('[name=price-total]').val(val.val+' 2500');
} else if (val1 == "package1") {
$('[name=price-total]').val('PHP 300');
} else if (val1 == "package2") {
$('[name=price-total]').val('PHP 400');
}
});
});
</script>
It gives me an "undefined value" if I click one of the checkboxes instead of adding it's value to the first value.
The problem was that you made a variable called val and then tried to access it with val.val + ' 2500' when it should have just been val + ' 2500'. val.val implies that there is a val object with a val property. Since there isn't, you got undefined.
You also have a syntax error with this:
$('[id=treats').click(function() {
As it should be:
$('[id=treats]').click(function() {
Also, I think that because of what your are testing, switch statements are more appropriate.
Lastly, you have multiple items with the same id, which isn't valid. After making them all unique, you should change your second click handler so that it accesses all the checkboxes by using the name attribute instead of id.
$(document).ready(function(){
$('[name=packages]').click(function() {
switch($(this).val()){
case "non-exclusive":
$('[name=price-total]').val('PHP 279');
break;
case "package1":
$('[name=price-total]').val('PHP 300');
break;
case "package2":
$('[name=price-total]').val('PHP 400');
break;
}
});
$('[name="treats[]"]').click(function() {
// Strip out non-numeric portion:
var val = $('[name="price-total"]').val().replace("PHP ", "");
switch($(this).val()){
case "Sweet Corner":
// Check to see if checkbox is checked...
if(this.checked){
// Must convert the value to a number and then you can do math
$('[name=price-total]').val("PHP " + (+val + 2500)); // <-- The problem was here
} else {
$('[name=price-total]').val("PHP 279");
}
break;
case "package1":
$('[name=price-total]').val('PHP 300');
break;
case "package2":
$('[name=price-total]').val('PHP 400');
break;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radios">
<label>
<input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
</label>
<label>
<input type="radio" name="extratreats" data-target="#extratreat"> Extra-Treats
</label>
</div>
<div id="extratreat" class="extratreat tab-pane collapse">
<label><h2>Extra Treats</h2></label>
<br />
<label><input id="treats1" name="treats[]" value="Sweet Corner" type="checkbox" > Sweet Corner & Choco Fountain</label>
<label><input id="treats2" name="treats[]" value="Popcorn Maker" type="checkbox" > Popcorn Maker</label>
<label><input id="treats3" name="treats[]" value="Hotdog Roller" type="checkbox" > Hotdog Roller</label>
</div>
<div id="pricing">
<label><h2>Price</h2></label>
<br />
<input type="text" name="price-total" value="" autocomplete="off" readonly>
</div>
Related
I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>
H, I have 4 checkboxes that i need to set values when clicked and unclicked. I have code that works for the first one but struggling to make it work with the other 3?
The code is
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" id="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" id="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" id="female"> Female driver</label></div>
and the js that works for the first on is :
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.checked){
document.getElementById("return_required").value = "YES";
}
else {
document.getElementById("return_required").value = "NO";
}
});
});
Because they don't have a value like the first one. They have an id.
You are getting the input value and working on it, so if the input don't has a value, you won't be able to select it.
var inputValue = $(this).attr("value"); // Offending line, because only your first input has a value.
$("." + inputValue).toggle();
The easiest way would be to check the name of the clicked element using this.name and manually match it to the checkboxes, then code the logic for each checkbox. An example is provided below:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.name == "colorCheckbox")
if (this.checked) {
document.getElementById("return_required").value = "YES";
} else {
document.getElementById("return_required").value = "NO";
}
else if (this.name == "signs") {
console.log("signs"); // replace with logic
} else if (this.name == "disabled") {
console.log("disabled"); // replace with logic
} else if (this.name == "female") {
console.log("female"); // repalce with logic
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" value="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" value="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" value="female"> Female driver</label></div>
<br>
<input id="return_required" value="NO"></input>
I have three radio buttons on my page, and a text input:
<div class="row-fluid" style="padding-bottom: 5px;">
<label class="radio inline"><input type="radio" name="optionsRadios" id="optionsRadios1" value="Name" checked>Search By Name </label>
<label class="radio inline"><input type="radio" name="optionsRadios" id="optionsRadios2" value="City">Search By City </label>
<label class="radio inline"><input type="radio" name="optionsRadios" id="optionsRadios3" value="Code">Search By code </label>
</div>
<div class="row-fluid">
<span class="row-fluid">
<input type="text" id="txtSearch" name="txtSearch" />
<input type="button" id="btnSubmit" value="Search" class="btn btn-primary" />
</span>
</div>
I'm trying to validate the length of the input on txtSearch based on the selected radio button, as the database fields are different lengths for those columns:
Updated:
$("#frmSearch").validate({
debug: false,
rules: {
'txtSearch': {
required: true,
maxlength: function () {
var sel = $('input[name=optionsRadios]:checked', '#frmSearch').val();
if (sel == 'City') {
return 25;
}
else {
return 50;
}
},
minlength: 2
}
}
});
I put the alerts in to tell me the lengths of the values, and all the alerts return what I expect, but the validation message displayed on every entry, no matter the length, is "Please enter no more than 1 characters."
Delete the depends and replace with this:
maxlength: (function(){
var sel = $('input[name=optionsRadios]:checked', '#frmOfficeSearch').val();
if (sel == 'Name') {
return 50;
}
if (sel == 'City') {
return 25;
}
if (sel == 'Code') {
return 50;
}
})()
This creates a self executing function that returns the correct integer based on the selected radio.
I want to make an online test, but i have some problems with the code below.
I want it to mark the correct and wrong answers, and show the score, when the button is pressed.
Now I have the following problem: I want the first switch statement to be only for the first group of radio buttons, the second switch statement for the second group of buttons, and so on.
How could I do that? When I run the code now, the colors change even though none of the radio buttons is checked, or when a button in only one of the groups is checked.
function showScore() {
var check;
var total = 0;
var yourmark = "your score is ";
switch (document.getElementById('q12').checked) {
case true:
total = total + 1;
document.getElementById('text1').style.color = "green";
break;
case false:
document.getElementById('text0').style.color = "red";
document.getElementById('text2').style.color = "red";
document.getElementById('text1').style.color = "green";
break;
}
switch (document.getElementById('q13').checked) {
case true:
document.getElementById('text0.1').style.color = "green";
total = total + 1;
break;
case false:
document.getElementById('text1.1').style.color = "red";
document.getElementById('text1.2').style.color = "red";
break;
}
alert(yourmark + total);
}
<input type="radio" name="question1" id="q11" value="false">
<text id="text0">Question 1-first option</text>
<br>
<input type="radio" name="question1" id="q12" value="true">
<text id="text1">Question 1- second option</text>
<br>
<input type="radio" name="question1" value="false">
<text id="text2">Question 1- third option</text>
<br>
<br>
<input type="radio" name="question2" id="q13" value="false">
<text id="text0.1">Question 1-first option</text>
<br>
<input type="radio" name="question2" id="q12" value="true">
<text id="text1.1">Question 1- second option</text>
<br>
<input type="radio" name="question2" value="false">
<text id="text1.2">Question 1- third option</text>
<br>
<button onclick="showScore();">Show my score</button>
Try this:
var questions = document.forms.myForm.getElementsByClassName('question');
document.getElementById('showScore').onclick = function showScore() {
var total = 0,
correct = 0;
for(var i=0; i<questions.length; ++i) {
var chosen = questions[i].querySelector(':checked');
if(chosen) {
questions[i].classList.add('show-score');
correct += chosen.value == 'true';
++total;
}
}
alert("Your score is " + correct + " out of " + total);
};
.question {
margin: 1em 0; /* Separation between questions */
}
.question > label:after { /* Line-break after each answer */
content: '';
display: block;
}
.question.show-score > input[value=true]+label {
color: green;
}
.question.show-score > input[value=false]+label {
color: red;
}
<form name="myForm">
<div class="question">
<input type="radio" name="question1" id="q-1-1" value="false">
<label for="q-1-1">Question 1 - first option</label>
<input type="radio" name="question1" id="q-1-2" value="true">
<label for="q-1-2">Question 1 - second option</label>
<input type="radio" name="question1" id="q-1-3" value="false">
<label for="q-1-3">Question 1 - third option</label>
</div>
<div class="question">
<input type="radio" name="question2" id="q-2-1" value="false">
<label for="q-2-1">Question 2 - first option</label>
<input type="radio" name="question2" id="q-2-2" value="true">
<label for="q-2-2">Question 2 - second option</label>
<input type="radio" name="question2" id="q-2-3" value="false">
<label for="q-2-3">Question 2 - third option</label>
</div>
<button id="showScore">Show my score</button>
</form>
Note those changes:
I have removed inline event listener from HTML, and added it using JS
I removed those ugly <br> and used CSS instead
I used <label> instead of invalid <text>. With <label>, you can also check a radio by clicking the text.
Instead of setting the color of correct/wrong answers with JS, I used CSS.
Well, ehr: group them. There's a lot wrong with your code and html. Id's are inconsistent, you are using inline event handlers, the code itself is bulky etc.
If you group the radiobuttons with a surrounding div, use consistent id's, labels instead of the <text> tag, leave the label-formatting to css and use querySelector[All], the code can be much shorter, really. Something like:
document.querySelector('body').addEventListener('click', showScore);
function showScore(e) {
var from = e.target || e.srcElement, fromtype = from.type;
if ( !(fromtype && /radio/i.test(fromtype)) ) { return true; }
var score = document.querySelectorAll('input:checked[value=true]').length;
// .. do stuff with [score]
}
It's demonstrated in this jsFiddle
When the user selects a radio button in the 2 categories Plan details and Plan Duration the input field should populate with the relevant data through JavaScript.
Please check the html markup and JavaScript below and suggest corrections or an alternate method that would work.
<h3 class="fltClear">Plan Details</h3>
<div id="spryradio1">
<dt>Plan Type: <span class="required">*</span></dt>
<dd>
<label>
<input type="radio" name="RadioGroup1" value="Silver" id="RadioGroup1_0" onClick="changeplanprice();" class="RadioGroup1" />
Silver</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Gold" id="RadioGroup1_1" onClick="changeplanprice();" class="RadioGroup1" />
Gold</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Platinum" id="RadioGroup1_2" onClick="changeplanprice();" class="RadioGroup1" />
Platinum</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="All-in-one" id="RadioGroup1_3" onClick="changeplanprice();" class="RadioGroup1" />
All-in-one</label>
<br>
<span class="radioRequiredMsg">Please make a selection.<span class="hint-pointer"> </span></span>
</dd>
</div>
<!--Plan Duration-->
<div id="spryradio2">
<dt>Plan Duration: <span class="required">*</span></dt>
<dd>
<label>
<input type="radio" name="RadioGroup2" value="Yearly" id="RadioGroup2_0" onClick="changeplanprice();" class="RadioGroup2" />
Yearly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Quaterly" id="RadioGroup2_1" onClick="changeplanprice();" class="RadioGroup2" />
Quaterly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Monthly" id="RadioGroup2_2" onClick="changeplanprice();" class="RadioGroup2" />
Monthly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Other" id="RadioGroup2_3" onClick="changeplanprice();" class="RadioGroup2" />
Other</label>
<br>
<span class="radioRequiredMsg">Please make a selection.<span class="hint-pointer"> </span></span>
</dd>
</div>
<!--Plan Price-->
<div>
<script>
function changeplanprice() {
var plantype=document.getElementByClassName('RadioGroup1').value;
var planduration=document.getElementByClassName('RadioGroup2').value;
if(plantype=="Silver") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 39.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 79.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 124.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
}
else if(plantype=="Gold") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 49.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 99.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 179.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
}
else if(plantype=="Platinum") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 59.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 199.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 279.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
} }
</script>
<div>
<dt><label for="Price">Plan Price:</label></dt>
<dd class="bg"><input type="text" name="Price" id="Price" size="80" class="input" readonly="readonly" />
</dd>
</div>
First suggestion that I will give is to have single
document.getElementById('Price').readOnly=true;
This will make your code more readable.
Second suggestion is that you can have 2 arrays one for plantype and other for planduration, and the radio-buttons instead of text, have array index as value.
This will not only make your code more readable, but also more manageable.
Suppose if you have to add one planduration, you will have to add the same condition for all plantypes, where there is a possibility of missing out one case.
Your function could use a little bit of cleanup, but there is one problem that I see. You are using document.getElementByClassName(' ... ').value;. This isn't correct. The function is actually document.getElementsByClassName (note Elements is plural). This function returns an array of all elements with that class name. So you cannot call .value directly on that. You would need to loop through the array of elements to find which element is checked and take the value of that.
Given that all the radio buttons of one group have the same name, and there is another function, document.getElementsByName, there is no reason to use getElementsByClassName.
I would change your function. This is tested and works, and is more easily scalable, in case you come up with new pricing options. All you would have to do is add on to the prices object:
function changeplanprice() {
var plantype;
var plantypes = document.getElementsByName('RadioGroup1');
for (var i=0; i < plantypes.length; i++) {
if (plantypes[i].checked)
plantype = plantypes[i].value;
}
var planduration;
var plandurations = document.getElementsByName('RadioGroup2');
for (i = 0; i < plandurations.length; i++) {
if (plandurations[i].checked)
planduration = plandurations[i].value;
}
if (plantype === undefined || planduration === undefined)
return;
document.getElementById('Price').readOnly = (planduration != "Other");
var prices = {
"Silver":{
"Monthly":"£ 39.98",
"Quarterly":"£ 79.98",
"Yearly":"£ 124.98",
"Other":""
},
"Gold":{
"Monthly":"£ 49.98",
"Quarterly":"£ 99.98",
"Yearly":"£ 179.98",
"Other":""
},
"Platinum":{
"Monthly":"£ 59.98",
"Quarterly":"£ 199.98",
"Yearly":"£ 279.98",
"Other":""
},
"All-in-one":{
"Monthly":"...", /* prices weren't provided for All-in-one in the example */
"Quarterly":"...",
"Yearly":"...",
"Other":""
}
};
document.getElementById('Price').value = prices[plantype][planduration];
}