Updating HTML upon drop down choice and checkbox selection - javascript

I Have a drop down list accompanied by some javascript & jquery which displays some text and a check box depending on the choice. If the checkbox is ticked then the HTML displayed will change again. Text & checkbox are being displayed however when checking the tick box html is then not changing.
HTML:
<div class="plan">
<div class="plan-details1"></div>
<div class="plan-name">
<select id="myselect">
<option value="0">Please Select Your Mobile Plan</option>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
</div>
<div class="plan-price"></div>
</div>
JS
$(function () {
$('#myselect').change(function () {
var val = $(this).val();
if (val == '1') {
$('.plan-details1').html('This Is Working 1<br/>');
$('.plan-price').html('<div id="price-m">Price: €18</div><input type="checkbox" id="handset-m" value="Car" onClick="validate()"> Handset');
}
if (val == '2') {
$('.plan-details1').html('This Is Working 2<br/>');
$('.plan-price').html('<div id="price-l">Price: €25</div><input type="checkbox" id="handset-l" value="Car" onClick="validate()"> Handset');
}
if (val == '3') {
$('.plan-details1').html('This Is Working 3<br/>');
}
if (val == '4') {
$('.plan-details1').html('This Is Working 4<br/>');
}
if (val == '5') {
$('.plan-details1').html('This Is Working 5<br/>');
}
if (val == '6') {
$('.plan-details').html('This Is Working 6<br/>');
}
});
});
function validate() {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
}
A fiddle can be found here: http://jsfiddle.net/5Y4b6/
Many thanks for your help!

This is not working because you insert the checkboxes as HTML markup. The onclick handlers is never attached to a real function. Change your code to this :
if (val == '1') {
$('.plan-details1').html('This Is Working 1<br/>');
$('.plan-price').html('<div id="price-m">Price: €18</div><input type="checkbox" id="handset-m" value="Car"> Handset');
document.getElementById("handset-m").onclick = validate;
}
if (val == '2') {
$('.plan-details1').html('This Is Working 2<br/>');
$('.plan-price').html('<div id="price-l">Price: €25</div><input type="checkbox" id="handset-l" value="Car"> Handset');
document.getElementById("handset-l").onclick = validate;
}
Now thew checkboxes is actually attached to the validate() function. BTW, change the validate function to check if the checkboxes exists / is inserted to avoid "cannot set checked of null" errors :
function validate() {
if (document.getElementById('handset-m')) {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
}
if (document.getElementById('handset-l')) {
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
}
}
forked fiddle -> http://jsfiddle.net/8upk3/

Edit:
validate is actually on the global scope, but the problem is with the validate function itself:
here is a fixed version:
function validate() {
if(document.getElementById('handset-m')) {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
}
if (document.getElementById('handset-l')) {
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
}
}

Scope problem.
You can either try to put listeners on your checkboxes, or declare your function in your document.ready
validate = function() {
if (document.getElementById('handset-m').checked) {
document.getElementById('price-m').innerHTML = 'Price: €20';
} else {
document.getElementById('price-m').innerHTML = 'Price: €18';
}
if (document.getElementById('handset-l').checked) {
document.getElementById('price-l').innerHTML = 'Price: €35';
} else {
document.getElementById('price-l').innerHTML = 'Price: €25';
}
};
I updated your fiddle here
Note that your function is not really efficient, you should test the presence of your elements ('handset-m', ''handset-l'...) before testing if they are checked.
EDIT
Here's an other way to do it, with jQuery listeners :
$('#plan').on('click','#handset-m, #handset-l', function(){console.log('test');
$this = $(this);
id = this.id;
var lbl = 'Price: €';
if(true === $this.prop('checked')){
lbl += ('handset-m' === id) ? '20' : '35';
}
else {
lbl += ('handset-m' === id) ? '18' : '25';
}
$this.prev('div').html(lbl);
});
fiddle here

Related

Jquery - dont run function if value of selected option is set to specific value

I have a jquery function that detects and formats currency if datatype of an input field is set to currency. how do i make this function not run if another select field value is set to BTC here are codes.
JS
$("input[data-type='currency']").on({
keyup: function() {
formatCurrency($(this));
},
focusout: function() {
formatCurrency($(this), "blur");
}
});
and here is my formatCurrency Function
function formatNumber(n) {
return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
} // format number 1000000 to 1,234,567
function formatCurrency(input, blur) {
var input_currency = ""; //the currency symbol that shows beofore the amount
var input_val = input.val();
if (input_val === "") { return; }
var original_len = input_val.length;
var caret_pos = input.prop("selectionStart");
if (input_val.indexOf(".") >= 0) {
var decimal_pos = input_val.indexOf(".");
var left_side = input_val.substring(0, decimal_pos);
var right_side = input_val.substring(decimal_pos);
left_side = formatNumber(left_side);
right_side = formatNumber(right_side);
if (blur === "blur") {
/* right_side += "00"; */
}
right_side = right_side.substring(0, 2);
input_val = input_currency + left_side + "." + right_side;
} else {
input_val = formatNumber(input_val);
input_val = input_currency + input_val;
if (blur === "blur") {
input_val += ".00";
}
}
input.val(input_val);
HTML
<input data-type="currency" name="amount">
<select class="" name="currency" id="currency" >
<option value="$" selected>USD</option>
<option value="₿">Bitcoin</option>
</select>
You need to add an if statement inside the .on callback function. For example you can modify your code like this
$("input[data-type='currency']").on({
keyup: function() {
if($("#currency").val() != "₿"){
formatCurrency($(this));
}
},
focusout: function() {
if($("#currency").val() != "₿"){
formatCurrency($(this), "blur");
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-type="currency" name="amount">
<select class="" name="currency" id="currency" >
<option value="$" selected>USD</option>
<option value="₿">Bitcoin</option>
</select>
Put a check in the beginning of formatCurrency and return if needed.
const formatCurrency = function(el, action) {
// option one: checking the requirement could be here in one place
if (!isShouldBeFormatted()) {
return;
}
console.log(`do formatCurrency`);
}
const isShouldBeFormatted = () => {
// select select element
const elCurrency = document.querySelector(`#currency`);
// value that we will check
const valueToCheck = `₿`;
return elCurrency.value !== valueToCheck;
}
$("input[data-type='currency']").on({
keyup: function() {
// option two: checking the requirement could be in every place you need it
if (isShouldBeFormatted()) {
formatCurrency($(this));
}
},
focusout: function() {
// option two: checking the requirement could be in every place you need it
if (isShouldBeFormatted()) {
formatCurrency($(this), "blur");
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-type="currency" name="amount">
<select class="" name="currency" id="currency" >
<option value="$" selected>USD</option>
<option value="₿">Bitcoin</option>
</select>

jquery change text once on change function

The problem is that when i change the option it keeps summing, and i would like for it to only sum one time the value of 10.00, and subtract only once if the value is AR .
LIVE LINK: http://jsfiddle.net/A3qLG/1/
JQUERY:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
HTML:
<label id="subt0">8.90</label>
<select id="country">
<option value="US">USA</option>
<option value="BR">Brasil</option>
<option value="AR">Argentina</option>
<option value="CU">Cuba</option>
</select>
I would change the HTML to this to store the original value:
<label id="subt0" data-original="8.90">8.90</label>
And then adjust the Javascript to this:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
//Changed the following line to get the original value
var subt_value = $('#subt0').attr('data-original');
//Changed this to say, NOT AR and has a choice per the comments.
if($(this).val() != 'AR' && $(this).val().length > 0) {
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
} else {
//Otherwise put it back to the original value
$('#subt0').text(subt_value);
}
});
});
try this code
$(document).ready( function() {
$('#country').on('keypress change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
You need to remember previous #country select value, and use it when making decision:
$(document).ready(function () {
var prevValue = '';
$('#country').on('keyup change', function (e) {
var newValue = $(this).val();
var subt_value = parseFloat($('#subt0').text());
if ((newValue == 'AR' || newValue == '')) {
if (prevValue != '' && prevValue != 'AR') {
$('#subt0').text((subt_value - 10).toFixed(2));
}
} else {
if (prevValue == 'AR' || prevValue == '') {
$('#subt0').text((subt_value + 10).toFixed(2));
}
}
prevValue = newValue;
});
});
http://jsfiddle.net/A3qLG/5/
Simply remove the onkeyup and onchange event handler functions after they have done their work.
$('#country').off('keyup change');
Jquery provide a .change() specifically for <select>
You want to sum only one time and substract only one time base on the condition of the selected value AR. Therefore you only need to check the selected value if there is change and do the math within the if-else statement. Finally attach the result with .toFixed(2)
var subt_value = $('#subt0').text();
var add_sub = 0, f=10.00;
$('#country').change(function(){
if ($(this).val() != 'AR'){
add_sub = parseFloat(subt_value)+f;
}else{
add_sub = parseFloat(subt_value)-f;
}
$('#subt0').text(add_sub.toFixed(2));
});
JSFiddle Demo

How to refresh the second hidden dropdown menu based on first one

How to refresh the second hidden dropdown menu based on first one?When i select an option from first dropdown the second dropdown appears and after selecting from second one i got text content but again when i select an option from first dropdown, previous text content didn't hide.Next text content appears below first one. Demo http://jsfiddle.net/pratyush141/VtFCR/
<select id="circle">
<option value="">select </option>
<option value="Bihar">Bihar </option>
<option value="Assam">Assam</option>
</select>
<select id="assam" style="display:none" >
<option value="">Pick one</option>
<option value="1">Top up</option>
<option value="2">sms</option>
<option value="3">data</option>
</select>
<select id="bihar" style="display:none">
<option value="">Pick one</option>
<option value="1">data</option>
<option value="2">sms</option>
<option value="3">top up</option>
</select>
<div id="brtopup" style="display:none">topup</div>
<div id="brsms" style="display:none">sms</div>
<div id="brdata" style="display:none">data</div>
<div id="astopup" style="display:none">topup</div>
<div id="assms" style="display:none">sms</div>
<div id="asdata" style="display:none">data</div>
$("#circle").change(function() {
var control = $(this);
if (control.val() == "Assam") {
$("#assam").show();
} else {
$("#assam").hide();
}
if (control.val() == "Bihar") {
$("#bihar").show();
} else {
$("#bihar").hide();
}
});
$("#bihar").change(function() {
var control = $(this);
if (control.val() == "1") {
$("#brdata").show();
} else {
$("#brdata").hide();
}
if (control.val() == "2") {
$("#brsms").show();
} else {
$("#brsms").hide();
}
if (control.val() == "3") {
$("#brtopup").show();
} else {
$("#brtopup").hide();
}
});
$("#assam").change(function() {
var control = $(this);
if (control.val() == "1") {
$("#astopup").show();
} else {
$("#astopup").hide();
}
if (control.val() == "2") {
$("#assms").show();
} else {
$("#assms").hide();
}
if (control.val() == "3") {
$("#asdata").show();
} else {
$("#asdata").hide();
}
$('#assam').trigger("chosen:updated");
});
Demo http://jsfiddle.net/pratyush141/VtFCR/
add a class to the different groups of assam and bihar :
<div id="brtopup" class ="bihar" style="display:none">topup</div>
<div id="brsms" class ="bihar" style="display:none">sms</div>
<div id="brdata" class ="bihar" style="display:none">data</div>
<div id="astopup" class ="assam" style="display:none">topup</div>
<div id="assms" class ="assam" style="display:none">sms</div>
<div id="asdata" class ="assam" style="display:none">data</div>
and then you can hide the whole class groups instantly:
if (control.val() == "Assam") {
$("#assam").show();
} else {
$("#assam").hide();
$(".assam").hide();
}
if (control.val() == "Bihar") {
$("#bihar").show();
} else {
$("#bihar").hide();
$(".bihar").hide();
}
});
jsfiddle demo here
Make these changes in JS
$("#circle").change(function() {
var control = $(this);
if (control.val() == "Assam") {
$("#assam").show();
} else {
$("#assam").hide();
$("#astopup").hide();//add three lines
$("#assms").hide();
$("#asdata").hide();
}
if (control.val() == "Bihar") {
$("#bihar").show();
} else {
$("#bihar").hide();
$("#brtopup").hide();//add three lines
$("#brsms").hide();
$("#brdata").hide();
}
});
$("#bihar").change(function() {
var control = $(this);
if (control.val() == "1") {
$("#brdata").show();
} else {
$("#brdata").hide();
}
if (control.val() == "2") {
$("#brsms").show();
} else {
$("#brsms").hide();
}
if (control.val() == "3") {
$("#brtopup").show();
} else {
$("#brtopup").hide();
}
});
$("#assam").change(function() {
var control = $(this);
if (control.val() == "1") {
$("#astopup").show();
} else {
$("#astopup").hide();
}
if (control.val() == "2") {
$("#assms").show();
} else {
$("#assms").hide();
}
if (control.val() == "3") {
$("#asdata").show();
} else {
$("#asdata").hide();
}
$('#assam').trigger("chosen:updated");
});

How do I hide a form element when all of a set of elements have a certain value?

On a form I have 3 questions with Yes/No radio options. If ANY of them are Yes, then a 4th question appears. I'm struggling to make the 4th question hide again if all 3 questions are reset to No. Probably a non-existent case, but I would prefer to be thorough.
I wrote a custom function triggered on click (when value != 'Yes') for each question to check the rest of the values and then update the 4th, but it seems like their values are not getting updated. q6, q7, and q8 in the function stay = 'Yes'. I thought my function would have access to the live form, but I must be doing something wrong?
//question_6exp
$("[name = question_6]").change(function()
{
if ( $(this).val() == 'Yes' )
{
$("#question_6exp").show();
$("#question_9").show();
}
else
{
$("#question_6exp").hide();
$("#question_9").hide_question9();
}
});
//question_7exp
$("[name = question_7]").change(function()
{
if ( $(this).val() == 'Yes' )
{
$("#question_7exp").show();
$("#question_9").show();
}
else
{
$("#question_7exp").hide();
$("#question_9").hide_question9();
}
});
//question_8exp
$("[name = question_8]").change(function()
{
if ( $(this).val() == 'Yes' )
{
$("#question_8exp").show();
$("#question_9").show();
}
else
{
$("#question_8exp").hide();
$("#question_9").hide_question9();
}
});
//function hide_question9()
$.fn.hide_question9 = function()
{
var q6 = $("[name = question_6]").val();
var q7 = $("[name = question_7]").val();
var q8 = $("[name = question_8]").val();
//alert('TEST: '+q6+q7+q8);
if ( (q6 == 'No') && (q7 == 'No') && (q8 == 'No') )
{
//$("#question_9").hide();
return this.hide();
}
else
return false;
}
UPDATE:
I updated my code based on the 2 responses I received below. Unfortunately, neither worked. I added a class to the 3 questions to make it easier to select just those 3. I tweaked JoDev's layout mostly. I commented out the code within the else state and tried Aguardientico code there - it is currently commented out.
$(".temp1").change(function()
{
var myName = $(this).attr('name');
if ( $(this).val() == 'Yes' )
{
$("#question_9").show();
$("#"+myName+"exp").show();
}
else
{//alert($(this).val());
$("#"+myName+"exp").hide();
var alltoNo = true;
$(".temp1").each(function()
{
if ( $(this).val() == 'Yes' )
{
alltoNo = false;
}
//return;
});
if ( alltoNo )
$("[name = question_9]").hide();
/*if ( $("[name=question_6][value=Yes]:checked").length == 0 )
$("[name = question_9]").hide();*/
}
});
This is an simpliest way to do it (just a beginning)
$('[name^="question_"]:not([name="question_9"])').change(function() {
if ( $(this).val() == 'Yes' )
{
$("#question_9").show();
$("#question_"+$(this).attr('name').replace('question_', '')+"exp").show();
} else {
$("#question_"+$(this).attr('name').replace('question_', '')+"exp").hide();
var alltoNO = true;
$('[name^="question_"]:not([name="question_9"])').each(function() {
if($(this).val() == 'Yes') {
alltoNo = false;
}
return;
});
if(alltoNo) {
$('[name="question_9"]').hide();
}
}
});
Try with something like this:
HTML:
<input type="radio" name="question_6" value="Yes"/> 6 Yes
<input type="radio" name="question_6" value="No"/> 6 No
<input type="radio" name="question_7" value="Yes"/> 7 Yes
<input type="radio" name="question_7" value="No"/> 7 No
<input type="radio" name="question_8" value="Yes"/> 8 Yes
<input type="radio" name="question_8" value="No"/> 8 No
<div id="question_6exp">Q6</div>
<div id="question_7exp">Q7</div>
<div id="question_8exp">Q8</div>
<div id="question_9exp">Q9</div>
JS:
$('[name=question_6], [name=question_7], [name=question_8]').change(function(){
if (this.value=="Yes") {
$("#" + this.name + "exp").show();
$("#question_9exp").show();
} else {
$("#" + this.name + "exp").hide();
if ($("[name=question_6][value=Yes]:checked, [name=question_7][value=Yes]:checked, [name=question_8][value=Yes]:checked").length == 0) {
$("#question_9exp").hide();
}
}
});

Removing input value on focus when the value was dynamically set before

With the code below, the value of .srch-inpt is changing according to the selected option's class.
I need to remove the value of the .srch-inpt on focus and have it back on blur.
The code I've written does not work properly.
//Changing search value on select-box option change
$(function(){
$('.srchopts').change(function () {
var optclass = "";
$("select option:selected").each(function () {
optclass += $(this).attr('class');
});
if (optclass == 'bookopt' || 'thesisopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ ISBN');
}
if (optclass == 'articleopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ Doi');
}
if (optclass == 'journalopt' ) {
$('.srch-inpt').val('Title/ ISSN');
}
});
$('.srch-inpt').focus(function() {
if ($(this).val() == $(this).attr('defaultValue'))
$(this).val('');
}).blur(function() {
if ($(this).val() == '')
$(this).val( $(this).attr('defaultValue') );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select class="srchopts">
<option class="bookopt">Book Option</option>
<option class="articleopt">Article Option</option>
<option class="thesisopt">Thesis Option</option>
<option class="journalopt">Journal Option</option>
</select>
<input type="text" name="" class="srch-inpt" value="Title / Author / Keywords / ISBN" defaultValue="" />
JSFiddle Demo
$('.srch-inpt').data('defaultValue','My default value').focus(function () {
if (this.value === $(this).data('defaultValue')) this.value = "";
}).blur(function () {
if (!this.value.length) this.value = $(this).data('defaultValue');
}).blur();
DEMO
I got the answer with the point A. Wolff mentioned.
As we don't have "DefaultValue" attribute in new jQuery, I have to create it by myself, and update it's value each time I change .srch-inpt value.
So, this is my new jQuery piece of code :
//Changing search value on select-box option change
$(function(){
$('.srchopts').change(function () {
var optclass = "";
$("select option:selected").each(function () {
optclass += $(this).attr('class');
});
if (optclass == 'bookopt' || 'thesisopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ ISBN');
}
if (optclass == 'articleopt' ) {
$('.srch-inpt').val('Title/ Author/ Keyword/ Doi');
}
if (optclass == 'journalopt' ) {
$('.srch-inpt').val('Title/ ISSN');
}
$('.srch-inpt').attr('defaultValue', $('.srch-inpt').val());
});
$('.srch-inpt').focus(function() {
if ($(this).attr('defaultValue') == '')
$(this).attr('defaultValue', $(this).get(0).defaultValue);
if ($(this).val() == $(this).attr('defaultValue'))
$(this).val('');
}).blur(function() {
if ($(this).val() == '')
$(this).val( $(this).attr('defaultValue') );
});
});
DEMO

Categories

Resources