I'm trying to do detection onLoad to see if a radio button is checked. If it is then I want to output some text into a div. Currently it isn't working onLoad and the functionality only works on click.
I'm using local storage to remember if a user has selected certain fields on refresh and this works fine - so whatever radio button was selected before a refresh shows after.
This is the code to change the text onLoad:
$(document).ready(function() {
var circuitNum = $('input[name="options[numberCircuitsMetre]"]:checked').val();
if (circuitNum == 'As many as possible per metre') {
$('#circuit').text('As many as possible per metre');
}
}
See full code:
// Circuit Select
// Toggle Metre Question and fill out summary
$('input[name="options[numberCircuitsMetre]"]').click(function(){
if($(this).attr("value")=="As many as possible per metre"){
$(".toggleQuestion").hide();
$('#circuit').text('As many as possible per metre');
}
if($(this).attr("value")=="Custom number"){
$(".toggleQuestion").show();
}
});
var circuitNum = $('input[name="options[numberCircuitsMetre]"]:checked').val();
if (circuitNum == 'As many as possible per metre') {
$('#circuit').text('As many as possible per metre');
}
if (circuitNum == 'Custom number') {
if($('.circuitsNum').val() == ''){
$('.circuitsValidation').html("<span class='flash'>Please add the number of circuits you want per metre</span>");
$('.circuitsNum').addClass("errorBorder");
var errorMessage = 'true';
} else {
$('#circuit').text('#circuitsNum'.value || '');
}
$(".toggleQuestion").show();
}
$("#circuitsNum").on('change keydown paste input', function() {
$('#circuit').text(this.value || '');
}).change();
$('#no').click(function() {
var term = $('#circuitsNum').val();
$('#circuit').text(term || '');
});
.radio-toggle {
margin-bottom: 30px;
}
.toggleQuestion {
display: none;
padding-top: 20px;
}
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<!-- No. of Circuit Designs -->
<fieldset>
<label>Do you want as many circuit designs per metre as possible?</label>
<div class="radio-toggle">
<div class="row collapse radio-shack">
<div class="large-6 columns">
<div class="radio-margin">
<div class="radio-zone">
<input type="radio" name="options[numberCircuitsMetre]" id="yes" class="substrate" value="As many as possible per metre" checked="checked" />
<div class="check-cover">
</div>
<div class="check"></div>
<label for="yes">
<div class="label-head"><strong>Yes</strong></div>
</label>
</div>
</div>
</div>
<div class="large-6 columns">
<div class="radio-margin">
<div class="radio-zone">
<input type="radio" name="options[numberCircuitsMetre]" id="no" class="substrate" value="Custom number"/>
<div class="check-cover">
</div>
<div class="check"></div>
<label for="no">
<div class="label-head"><strong>No</strong></div>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="toggleQuestion">
<label>How many circuit designs per metre would you like?</label>
<input type="number" name="options[numberCircuits]" step="any" placeholder="Add the number of circuits per metre..." class="circuitsNum number" id="circuitsNum">
<p class="circuitsValidation"></p>
</div>
</fieldset>
<div class="summary-row">
<div class="summary-cell summary-head">
<strong>No. of circuits:</strong>
</div>
<div class="summary-cell">
<span id="circuit"></span>
</div>
</div>
try this https://jsfiddle.net/0zzdkb32/44/ I just add this code
$(document).ready(function() {
$('input[name="options[numberCircuitsMetre]"]').each(function() {
if ($(this).val() == localStorage.getItem('selected')) {
$(this).click();
if($(this).val()=="As many as possible per metre"){
$(".toggleQuestion").hide();
setTimeout(function(){
$('#circuit').text('As many as possible per metre');
}, 100);
}
if($(this).attr("value")=="Custom number"){
$(".toggleQuestion").show();
}
}
});
})
and add
localStorage.setItem('selected', $(this).val());
in your click event
Related
I have two radio buttons:
fixed_price_option (Selected by default.)
variable_price_option (Disabled by default)
I also have two types of inputs:
fixed_price_input (Visable by default. Only one occurance.)
variable_price_input (Not present in code as it has to be added dynamically. One or more occurances.)
When fixed_price_option is selected an input called fixed_price_input should be visable and included when later running .serialize().
When fixed_price_option is selected no variable_price_input´s should be visible or included when later running .serialize().
variable_price_option should only be selectable when the difference between two date inputs are more than 12 months. (this I have solved)
When variable_price_option is selected there should be one more variable_price_input´s visable as there are whole years between the two date inputs (i.e. durationMonths + 1). They also need to be included when later running .serialize() so they need to have names like price_year_1, price_year_2, price_year_3 and so on, depending on how many whole years there are between the two date inputs.
When variable_price_option is selected fixed_price_input should not be visible or included when later running .serialize().
I have supplied the code as far as I have come. The missing logic needs to be put in the event handler at the bottom of the js code.
Any suggestions on how to solve this?
-- UPDATE --
My question needed clarification:
What I'm struggling with is to toggle the existence of the two types of inputs (fixed_price_input and variable_price_input) depending on which radio button is checked. Hiding/showing them isn't enough because I'm going to use .serialize() at a later point. Should I use .detach() and .append() somehow?
I'm also struggling with how to create one more variable_price_input's than there are years between the start and end date. Should I use <template> or .clone() somehow?
$(document).ready(function() {
$("#inputStartDate, #inputEndDate").change(function() {
if ($('#inputStartDate').val() && $('#inputEndDate').val()) {
var startDate = moment($('#inputStartDate').val());
var endDate = moment($('#inputEndDate').val());
var durationMonths = endDate.diff(startDate, 'months');
$('#durationMonths').text(durationMonths);
var durationYears = endDate.diff(startDate, 'years');
$('#durationYears').text(durationYears);
if (duration > 12) {
$('#variablePriceOption').prop("disabled", false);
} else {
$('#variablePriceOption').prop("disabled", true);
}
}
});
$('#variablePriceOption, #fixedPriceOption').change(function() {
if (this.value == 'fixedPrice') {
//Logic needed
} else if (this.value == 'variablePrice') {
//Logic needed
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<div class="container">
<div class="row mt-3">
<div class="col">
<div class="form-group">
<label for="inputStartDate">Start date</label>
<input type="date" class="form-control" id="inputStartDate" name="land_contract_start_date">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="inputEndDate">End date</label>
<input type="date" class="form-control" id="inputEndDate" name="land_contract_end_date">
</div>
</div>
</div>
<div class="text-center">Months between selected dates = <span id="durationMonths"></span>. Years between selected dates = <span id="durationYears"></span>.
</div>
<div class="form-group">
<label for="inputPriceModel">Price model</label>
<div id="inputPriceModel">
<div class="form-check">
<input class="form-check-input" type="radio" name="inputPriceModel" id="fixedPriceOption" value="fixedPrice" required checked="checked">
<label class="form-check-label" for="fixedPriceOption">
Fixed price
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="inputPriceModel" id="variablePriceOption" value="variablePrice" disabled="disabled">
<label class="form-check-label" for="variablePriceOption">
Variable price
</label>
</div>
</div>
</div>
<div class="form-group fixedPriceModelFormGroup">
<label for="fixed_price_input">Fixed price amount</label>
<div class="input-group">
<input type="number" class="form-control" id="fixed_price_input" name="land_contract_fixed_annual_price">
<div class="input-group-append">
<span class="input-group-text">$</span>
</div>
</div>
</div>
</div>
This should help get you started as far as variable pricing inputs showing for each # of year difference of the calendar dates. The code could be broken out into other functions for handling the display/hiding of elements, etc. You need to move your <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> code above your other JS references to get rid of the errors you're seeing for bootstrap.
Also, your duration variable should be durationMonths for comparing > 12, as duration is undefined. durationYears should be moved outside the change function of the calendar dates so you can reference it in your other processing functions. I added Math.abs() to the date calculations to ensure you're dealing with a positive integer for comparisons.
Using the disabled attribute on the inputs that are hidden will allow you to serialize the visible form data and ensure you won't get hidden inputs (variable pricing fields, etc) as part of the serialization data.
As #Twisty mentioned in the comments on your post, you will want to use .detach() or some sort of way to store the variable pricing input values if you toggle back and forth between Fixed/Variable options (localStorage, sessionStorage also options for storing data), if you want to maintain any values placed in the variable/fixed inputs. You will need to remove the .empty() usage on the input fields in my example as well, if you intend to store the data values of the inputs.
The loop function handleVariablePricing for determining how many variable pricing inputs should show would need to hook into the stored data functionality to ensure you are creating the same amount of fields with previously entered values, and not adding additional new fields on top of the existing fields/values.
$(document).ready(function() {
var durationYears = 0;
$("#inputStartDate, #inputEndDate").change(function() {
if ($('#inputStartDate').val() && $('#inputEndDate').val()) {
var startDate = moment($('#inputStartDate').val());
var endDate = moment($('#inputEndDate').val());
var durationMonths = Math.abs(endDate.diff(startDate, 'months'));
$('#durationMonths').text(durationMonths);
// maintain value outside of change function
durationYears = Math.abs(endDate.diff(startDate, 'years'));
$('#durationYears').text(durationYears);
if (durationMonths > 12) {
$('#variablePriceOption').prop("disabled", false);
} else {
$('#variablePriceOption').prop("disabled", true);
}
// If dates changed, update variable inputs shown
if ($('#variablePriceOption').is(':checked')) {
if (durationMonths > 12) {
$('#variable_price_input_1').val('');
$('.duration-years-input').remove();
handleVariablePricing();
} else {
$('#fixedPriceOption').click();
}
}
}
});
$('#variablePriceOption, #fixedPriceOption').change(function() {
if (this.value == 'fixedPrice') {
$('.variablePriceModelFormGroup').removeClass('d-block').addClass('d-none');
$('.variablePriceModelFormGroup input').each(function() {
$(this).val('').attr('disabled', true);
});
$('.fixedPriceModelFormGroup input').prop('disabled', false);
$('.fixedPriceModelFormGroup').removeClass('d-none').addClass('d-block');
$('.duration-years-input').remove();
} else if (this.value == 'variablePrice') {
$('.fixedPriceModelFormGroup').removeClass('d-block').addClass('d-none');
$('.fixedPriceModelFormGroup input').val('').attr('disabled', true);
$('#variable_price_input_1').prop('disabled', false);
$('.variablePriceModelFormGroup').removeClass('d-none').addClass('d-block');
handleVariablePricing();
}
});
/**
* Creates inputs for variable pricing..
**/
var handleVariablePricing = function() {
$rowClone = $('.row-main').clone();
for (var i = 2; i <= durationYears + 1; i++) {
$rowClone.prop('class', 'duration-years-input');
$rowClone.find('label').text('Price Year ' + i);
$rowClone.find('input').prop('id', 'variable_price_input_' + i);
$rowClone.find('input').prop('name', 'land_contract_variable_annual_price_' + i);
if ($('.duration-years-input').length === 0) {
$('.row-main').after($rowClone);
} else {
$('.duration-years-input').last().after($rowClone);
}
$rowClone = $('.duration-years-input').last().clone();
}
};
$('button').click(function() {
console.log($('#test-form').serialize());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<div class="container">
<form id="test-form">
<div class="row mt-3">
<div class="col">
<div class="form-group">
<label for="inputStartDate">Start date</label>
<input type="date" class="form-control" id="inputStartDate" name="land_contract_start_date">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="inputEndDate">End date</label>
<input type="date" class="form-control" id="inputEndDate" name="land_contract_end_date">
</div>
</div>
</div>
<div class="text-center">Months between selected dates = <span id="durationMonths"></span>. Years between selected dates = <span id="durationYears"></span>.
</div>
<div class="form-group">
<label for="inputPriceModel">Price model</label>
<div id="inputPriceModel">
<div class="form-check">
<input class="form-check-input" type="radio" name="inputPriceModel" id="fixedPriceOption" value="fixedPrice" required checked="checked">
<label class="form-check-label" for="fixedPriceOption">
Fixed price
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="inputPriceModel" id="variablePriceOption" value="variablePrice" disabled="disabled">
<label class="form-check-label" for="variablePriceOption">
Variable price
</label>
</div>
</div>
</div>
<div class="form-group fixedPriceModelFormGroup">
<label for="fixed_price_input">Fixed price amount</label>
<div class="input-group">
<input type="number" class="form-control" id="fixed_price_input" name="land_contract_fixed_annual_price">
<div class="input-group-append">
<span class="input-group-text">$</span>
</div>
</div>
</div>
<div class="form-group variablePriceModelFormGroup d-none">
<div class="row-main">
<label for="variable_price_input">Price Year 1</label>
<div class="input-group">
<input type="number" class="form-control" id="variable_price_input_1" name="land_contract_variable_annual_price_1" disabled="disabled">
<div class="input-group-append">
<span class="input-group-text">$</span>
</div>
</div>
</div>
</div>
</form>
<button>Serialize</button>
</div>
I'm trying to calculate the %share which is simply an addition of share1+share2 == 100. However, I want it to work only on the two checked checkboxes.
How do I go about detecting the selected checkbox and apply the function accordingly?
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$("#share1").focusout(function() {
var share1 = $("#share1").val();
var answer = 100 - share1;
$("#share2").val(answer);
});
$("#share2").focusout(function() {
var share2 = $("#share2").val();
var answer = 100 - share2;
$("#share1").val(answer);
});
label {
display: block;
}
.block {
background-color: #eee;
padding: 15px;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<h6>You can choose a maximum of 2 users</h6>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share1" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share2" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share3" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share4" class="form-control" placeholder="% share" required>
</div>
</div>
Do you have a specific reason to use focusout?
You could catch the ID's of the two "selected" elements inside your checkbox function. Or to be precise, get id of input that is in the next div inside the clicked checkbox's parent:
var active1, active2;
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
let checked = $('input.addnominee:checked');
active1 = $(checked[0]).parent().next('div').children('input').attr('id');
//Let's assign active2 only if we have multiple selected checkboxes:
if(checked.length > 1) active2 = $(checked[1]).parent().next('div').children('input').attr('id');
});
Here's example with click. To simplify it a bit, I added stepper class into every number input, and we're now detecting click for the class stepper:
$(document).on('click','.stepper',function(){
if($(this).attr('id') == active1){ //Check which one user clicked
if(active2 != undefined){ //Make the math only if we have another active element
var share1 = $('#'+active1).val();
var answer = 100 - share1;
$('#'+active2).val(answer);
}
}else if($(this).attr('id') == active2){
if(active1 != undefined){
var share2 = $('#'+active2).val();
var answer = 100 - share2;
$('#'+active1).val(answer);
}
}
});
Fiddle: https://jsfiddle.net/xpvt214o/677733/
This surely works also with focusout, but you need to remember that clicking stepper wont focus the input, so it wouldn't be very functional.
And with this same idea you could also disable the inputs which are not 'active'.
I hope this helps!
EDIT:
Maybe a bit simplified version with the same idea:
jQuery(document).ready(function($) {
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$(document).on('click','.stepper',function(){
var checked = $('input.addnominee:checked');
if(checked.length > 1){
var active1 = $(checked[0]).parent().next('div').children('input');
var active2 = $(checked[1]).parent().next('div').children('input');
var share = $(this).val();
var answer = 100 - share;
if($(this).attr('id') == $(active1).attr('id')){
$(active2).val(answer);
}else if($(this).attr('id') == $(active2).attr('id')){
$(active1).val(answer);
}
}
});
});
Fiddle: https://jsfiddle.net/128uzmj3/
I tried to make a function by passing an event to a button but it is not working. What I want the function to do is that when the button is clicked show in the DOM that I click and also display with the innerhtml a message on the web page using if/ else depending of the user imput in the imputs of time abd weight
$(document).ready(function() {
$('#calculate').on('click', function() {
$('#calculate ul li input').slideToggle(800);
});
/********************************************************/
var gender = $('#gender');
var age = $('#age');
var time = $('#time');
var weigth = $('#weight');
var result = $('#result');
var calculate = $('#calculate');
if (calculate.lenght) {
/*event listener*/
calculate.on('click', calculateF);
/*para que cuando se haga click se active la funcion calcular
que estoy creando abajo*/
function calculateF(event) {
event.preventDefault();
console.log("click");
var timeVal = parseInt(time.val());
var weightVal = parseInt(weight.val());
if (time > 8 && weight > 25) {
result.html(" text ");
} else {
result.html("text");
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="manejo_cargas" id="manejo_cargas">
<h3>calculate work load</h3>
</div>
<section id="calculate">
<div class="calculate">
<ul>
<li><input type="text" name="text" placeholder="Gender" id="gender"></li>
<li><input type="number" name="number" placeholder="age" id="age"></li>
<li><input type="number" name="number" placeholder="time" id="time"></li>
<li><input type="number" name="number" placeholder="weight" id="weight"></li>
</ul>
</div>
</section>
<div class="calculate">
<input type="button" class="button" value="result" id="calculate">
</div>
<!--here comes the result-->
<div class="result" id="result">
</div>
.
You are missing the # if you have declared the time, weight, result, and calculate as id's of the elements that you are targeting.
From what I can guess is that the weight and time are inputs the result is a div and the calculate is the button to be clicked.
I will assume they are ids so you need to add # before the id when specifying selectors in jquery using $() otherwise use . if they are class names.
Then if you are converting the code to jquery from javascript you need to replace the respective functions like addEventListener .innerHtml , .value etc
You can see the working below but the calculations and the message that you have to add is on your end as you never provided any details so i have made the conversion for the code
$(document).ready(function() {
var time = $('#time');
var weight = $('#weight');
var result = $('#result');
var calculate = $('#calculate');
/*event listener*/
calculate.on('click', calculateF);
function calculateF(event) {
event.preventDefault();
console.log("you hit click");
/*new variables*/
var timeVal = parseInt(time.val());
var weightVal = parseInt(weight.val());
if (time > 8 && weight > 25) {
result.html(" if condition true ").show();
} else {
result.html("message from the else part").show();
}
}
});
.result {
border: 1px solid #c7c7c7;
padding: 5px;
text-align: center;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--here comes the result-->
<div class="result" id="result">
</div>
<div class="manejo_cargas" id="manejo_cargas">
<h3>calculate work load</h3>
</div>
<section>
<div class="calculate">
<ul>
<li><input type="text" name="text" placeholder="Gender" id="gender"></li>
<li><input type="number" name="number" placeholder="age" id="age"></li>
<li><input type="number" name="number" placeholder="time" id="time"></li>
<li><input type="number" name="number" placeholder="weight" id="weight"></li>
</ul>
</div>
</section>
<div class="calculate">
<input type="button" class="button" value="result" id="calculate">
</div>
<!--folder where my jquery code is saved-->
<script src="js/jquery.js"></script>
<!--folder where my jquery code is saved-->
<script src="js/scripts.js"></script>
EDIT
Your HTML has duplicate id calculate for the section and for the input button that's why it isn't working you cannot have multiple elements with the same id I have used your HTML and removed the id from the section tag, see the demo above
I am trying to get all the values of the input fields. The issue is all of the <input type=radio/> are dynamic and can increase or decrease at any time.
So I am starting with the main DI and going from there. The problem I have now is I am not getting the input radio buttons values.
So here are the steps I am intending to accomplish:
If any radio button is selected, pass its value to the checkbox value,
If the radio button is selected and the checkbox is not selected, do not pass to the checkbox value
I am looking for a solution in JavaScript only - do not use jQuery
Here is my jsFiddle code
HTML
<div style="display: block;" id="mymainDiv" class="fullFloat">
<input type="hidden" value="1" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">UPS<a class="fRight" onclick="localG('10',false,0,false,'UPS','1','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_UPS"><div class="loadingcheckout"></div></div>
<div id="Price_UPS">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11098" id="deliveryMethodId_1" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
UPS Ground (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="UPS_11098">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="UPS">
</div>
<input type="hidden" value="2" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">Standard<a class="fRight" onclick="localG('20',false,0,false,'Standard','2','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_Standard"><div class="loadingcheckout"></div></div>
<div id="Price_Standard">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11117" id="deliveryMethodId_2" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
Standard Delivery - 2-3 Day Delivery at Ground Rate (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="Standard_11117">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="Standard">
</div>
<input type="hidden" value="3" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">FedEx<a class="fRight" onclick="localG('190',false,0,false,'FedEx','3','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_FedEx"><div class="loadingcheckout"></div></div>
<div id="Price_FedEx">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11088" id="deliveryMethodId_3" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
FedEx Ground (Order by 8:00 PM EST)
</span>
<div class="wrapRight">
<div id="FedEx_11088">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="FedEx">
</div>
</div>
<input type="checkbox" name="shipmode" id="shipmode" value="" onclick="getpref('mymainDiv');">Get Value
JS Code
This executes when the checkbox is clicked:
function getpref(val) {
var wr = document.getElementById(val);
childElements = wr.childNodes;
//alert(childElements);
for(var i = childElements.length-1; i>=0; i--){
var elem = childElements[i];
console.log(elem.id);
if(elem.id && elem.id.indexOf(val+'_')==0){
elem.style.display = 'block';
}
}
//alert(val);
}
You can directly access input nodes in your DIV with getElementsByTagName
function getpref(val) {
var divNode = document.getElementById(val);
var inputNodes = divNode.getElementsByTagName('INPUT');
for(var i = 0; i < inputNodes.length; ++i){
var inputNode = inputNodes[i];
if(inputNode.type == 'radio') {
//Do whatever you want
if(inputNode.checked) {
//Do whatever you want
}
}
}
}
Example: http://jsfiddle.net/88vp0jLw/1/
You can use getElementsByName to get you all of the radio buttons by name='deliveryMethodId' and then go from there:
function getpref(val) {
var radioButtons = document.getElementById(val).getElementsByName("deliveryMethodId");
for(var i = radioButtons.length-1; i>=0; i--)
{
var radioButton = radioButtons[i];
if(radioButton.checked)
console.log(radioButton.id + " is selected ");
}
}
I have a button Resend , and on click of it , the checkboxes get enable against the following:
id="AlertSent"
id="AlertNotSent"
id="AlertInProgress"
Now the DIV Code for Above mentioned DIVS is as below
<div class="span9">
<div class="row-fluid">
<div id="enableCheckBox" class ="span12">
<input type="checkbox" id="checkbox1" name="checkbox1"/>
</div>
<div id="AlertSent" class="span12">
<label><spring:message code='alert.sent' />:</label>
</div>
</div>
<div class="row-fluid">
<div id="enableCheckBox" class ="span12">
<input type="checkbox" id="checkbox2" name="checkbox2"/>
</div>
<div id="AlertNotSent" class="span12">
<label><spring:message code='alert.not.sent'/>:</label>
</div>
</div>
<div class="row-fluid">
<div id="enableCheckBox" class ="span12">
<input type="checkbox" id="checkbox3" name="checkbox3" class="required" />
</div>
<div id="AlertInProgress" class="span12">
<label> <spring:message code='alert.in.progress' />:</label>
</div>
</div>
</div>
The button Code for Resend and Done is
<input type="button" value="button" id="resend"/>
<input type="button" value="button" id="done"/>
The JQuery Code is
var j$ = jQuery.noConflict();
j$(document).ready(function() {
var resendbtn = j$('#resend');
var allChkBox = j$('input[name="enableCheckBox"]');
var verifyChecked = function() {
if ! $('#resend').click {
allChkBox.attr('disabled', 'disabled');
} else {
allChkBox.removeAttr('disabled');
}
};
verifyChecked();
resendbtn.change(verifyChecked);
});
The requirement is on click of Resend, the checkboxes appear against above DIVS (AlertSent, AlertNotSent and AlertInProgress), and the Resend button Becomes Done, and if a User unchecks all the checkboxes then the Done Button becomes Resend again.
How do I write a JQuery/JavaScript code to achieve above?
Please suggest
It's hard to know exactly what you want here, but perhaps this will get you started:
http://jsfiddle.net/ZqH7B/
to handle showing the checkboxes:
$("#resend").on( 'click', function () {
$('.enableCheckBox').css('visibility', 'inherit');
$(this).hide().next().show();
$('input:checkbox').prop('checked', true);
});
to handle uncheck behavior:
$('input[type=checkbox]').on( 'change', function() {
var num = $('input:checked').length;
if ( num == 0 ) { $('#resend').show().next().hide(); }
});
Try following code:
HTML:
<input type="checkbox" class="chk">
<input type="button" value="Resend" class="toggle">
JS:
$(document).ready(function(){
$(".chk").prop("checked","checked");
$(".chk").css('display','none');
$(".toggle").click(function(){
$(".chk").css('display','block');
$(".chk").prop("checked","checked");
$(this).val("Done");
});
$(".chk").change(function(){
var all = $(".chk").length;
var chked = $(".chk").not(":checked").length;
if(all == chked){
$(".chk").css('display','none');
$(".toggle").val("Resend");
}
})
});
JSFIDDLE DEMO