get select values inside div ,then show children div of main div - javascript

HTML:
<div class="question>
<select name="status">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div class="subquestion">
<input type="file name="file>
</div>
</div>
JS
$(document).ready(function () {
$(".question").each(function () {
$(".subquestion").hide();
$('select[name=status]').click(function () {
if (this.value == "1" || this.value == "2" || this.value == "3") {
// show $(this) div 'subquestion'
}
else {
$(".subquestion").hide();
}
})
})
});
I want to get select values with this select values and then if values are 1 || 2 || 3 then use this div subquestion show();
but it must be outside of if statement beacause there is selected ('select') tag and div subquestion is outside that tag.

If you need to show the subquestion related to that question use this:
$(document).ready(function () {
$(".question").each(function () {
$(".subquestion").hide();
$('select[name=status]').change(function () {
if (this.value == "1" || this.value == "2" || this.value == "3") {
$(this).next('.subquestion').show();
}
else {
$(this).next('.subquestion').hide();
}
})
})
});
Check this Demo http://jsfiddle.net/6ZxDJ/

change this:
$('select[name=status]').click(function () {
if (this.value == "1" || this.value == "2" || this.value == "3") {
// show $(this) div 'subquestion'
}
else {
$(".subquestion").hide();
}
})
to this
$('select[name="status"]').change(function () {
if ($(this).val() == "1" || $(this).val() == "2" || $(this).val() == "3") {
$(this).closest('.question').find(".subquestion").show();
}
else {
$(this).closest('.question').find(".subquestion").hide();
}
})

Related

Alternative to a lot of if statements jquery

I'm trying to validate my form using jquery before submission. The user needs to fill up the Task accordingly, they cannot submit the form with fill-up Task 2 and missing Task 1. And also the Task cannot be duplicated with other Task. I'm wondering if there any better way to compare all of this, in a simple method.
The Javascript currently I'm doing. Still not complete yet because looking for better ways.
$(function() {
$( "#create_model" ).submit(function( event ) {
if(validate_task()){
alert("Check your task.");
event.preventDefault();
} else {
$("#create_model").submit();
}
});
});
function validate_task() {
if ($('#CatTask2ID').val() !== "" && $('#CatTask2ID').val() === "") {
return "Task 1 is empty"; //return FALSE;
} else if ($('#CatTask3ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "") {
return "Task 1 or 2 is empty"; //return FALSE;
} else if ($('#CatTask4ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask5ID').val() !== "" && $('#CatTask1ID').val() === "" || $('#CatTask2ID').val() === "" || $('#CatTask3ID').val() === "" || $('#CatTask4ID').val() === "") {
return "Task 1, 2 or 3 is empty"; //return FALSE;
} else if ($('#CatTask1ID').val() === $('#CatTask2ID').val() || $('#CatTask1ID').val() === $('#CatTask3ID').val() .......and others........... ) {
return "Duplicates"; //return FALSE;
}
}
First use classes instead of IDs so you can get a collection of all selects easily, then map each select to its value to get an array of values.
Find the index of the first value which is the empty string. If any values after that one are populated, return an error saying that the index of that empty string is empty.
Otherwise, take the populated values (from indices 0 to the index of the first empty string), and check if the size of a Set of those values is equal to the length of the array:
function validate_task() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex > 0 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
// OK
}
Live demo:
document.addEventListener('change', () => console.log(validateTask()));
function validateTask() {
const taskValues = [...$('.tasks')].map(task => task.value);
const firstEmptyIndex = taskValues.indexOf('');
if (firstEmptyIndex !== -1 && taskValues.slice(firstEmptyIndex).some(val => val)) {
return `Task ${firstEmptyIndex + 1} is empty`;
}
const populatedTasks = taskValues.slice(0, firstEmptyIndex);
if (populatedTasks.length !== new Set(populatedTasks).size) {
return 'Duplicates';
}
return 'OK'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
<select class="tasks">
<option></option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>buzz</option>
</select>
function validate_task() {
var error_msg = [];
if($('#CatTask1ID').val() === ""){
error_msg.push('1');
}
if($('#CatTask2ID').val() === ""){
error_msg.push('2');
}
if($('#CatTask3ID').val() === ""){
error_msg.push('3');
}
//......
return error_msg;
}
function validate_task_msg() {
var arr = validate_task()
if(arr&& arr.length<=0){
return true;
}else if(arr.length == 10){//more
return "Duplicates";
}else {
var msg = arr.join(',');
return "Task "+ msg + " is empty"
}
}

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");
});

Updating HTML upon drop down choice and checkbox selection

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

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