How to clear old value from checkbox before next try? - javascript

I wrote my JavaScript code to get a value with JSON function to show in a checkbox, but every time I try with new options the old values still exist in the check box. I want to clear the checkbox before the next try. I marked the problem area in the code below:
HTML:
<div class="panel-body">
<div class="form-group">
<label for="field-1" class="col-sm-3 control-label" >Select Group</label>
<div class="col-md-2">
<select class="form-control" name="perms" onchange="OnSelectionChange(this)">
<option>Choice your group</option>
{foreach $perms as $perm}
<option value="{$perm.pID}">{$perm.title}</option>
{/foreach}
</select>
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<strong>Edite Permisions:</strong>
<br />
<br />
</div>
<div class="col-sm-6" style="width:100%;">
<ul class="icheck-list">
{foreach $rps as $rp}
<li>
<input type="checkbox" name="updatePERM[]" id="{$rp.id}" value="{$rp.id}">
<label style="padding-left: 5px;vertical-align: middle;" >{$rp.rname}</label> <pre>{$rp.rdes}</pre>
</li>
{/foreach}
</ul>
</div>
</div>
</div>
</div>
JS:
function OnSelectionChange (select) {
var selectedOption = select.options[select.selectedIndex];
var url = "./include/getPerms.php?key="+selectedOption.value+"";
$.getJSON(url, function(data) {
$.each(data.rules, function(i, rule) {
// MY PROBLEM LINE: HOW I CAN DO THIS ?
if input:checkbox.val() != rule.id => set attr('checked', false)
else if input:checkbox.val() == rule.id => set attr('checked', true)
// HOW I CAN DO THIS ?
});
});
}

function OnSelectionChange(select) {
var selectedOption = select.options[select.selectedIndex];
var url = "./include/getPerms.php?key=" + selectedOption.value + "";
$.getJSON(url, function (data) {
// Default make all checkbox un-checked.
$("input:checkbox").prop("checked", false)
$.each(data.rules, function (i, rule) {
// If rule.id matches with the checkbox values then make those checkbox checked
$(":checkbox[value="+rule.id+"]").prop("checked",true);
});
});

Related

Only checked specific checkbox inside a loop with jQuery

In my project, my issue is when I click Select All I want just want this row's checkbox to be checked. The 1st image below is the initial state that I want when the event click on .give-all-permissions fires. I want to be the 2nd image but my it gives me the 3rd image output how to achieve like 2nd image. Please see all the images that I tried to get this to work.
1st img
2nd img
3rd img
my HTML markup
<div class="row permission-group">
<div class="col-lg-4">
<fieldset class="mt-1 {{ $loop->last ? null : 'mb-1' }}">
<div class="checkbox checkbox-shadow">
<input type="checkbox" class="give-all-permissions" id="module_{{ md5($module->id) }}">
<label class="cursor-pointer" for="module_{{ md5($module->id) }}">Select All</label>
</div>
</fieldset>
</div>
<div class="col-lg-8">
#foreach ($module->permissions as $permission)
<fieldset class="mt-1 {{ $loop->last ? null : 'mb-1' }}">
<div class="checkbox checkbox-shadow">
<input class="checked-input" type="checkbox" id="permission_{{ md5($permission->id) }}">
<label class="cursor-pointer" for="permission_{{ $permission->id }}">{{ $permission->name }}</label>
</div>
</fieldset>
#endforeach
</div>
</div>
my code
$(document).ready(function () {
$('.give-all-permissions').click( (e) => {
// e.preventDefault();
if (e.target.checked === true) {
$('.checked-input').each(function (i, el) {
el.setAttribute("checked", "checked");
this.checked = true;
});
} else if (e.target.checked === false) {
$('.checked-input').each(function (i, el) {
el.removeAttribute("checked");
this.checked = false;
});
}
})
})

Change variables on click after AJAX call

I can't find an answer or solution to this issue that I'm facing. So I have made a script (php & jquery) that allows users to promote their "listings" on my website. So when they land on a page they can select which listing they want to promote, then when they select it the jquery calls AJAX (on select change) which then calls the php page and get the plans for the selected listing. Since I'm using PayPal Standard I can only pass variables with one input (I'm storing all variables in one custom input and then read them on the php page as array). Everything works fine, my listing ID gets changed when the listing is changed, the days duration gets changed when they change it in input but the thing that doesn't work is checkboxes.
So in the datebase I have three columns under listing table (featured, topsearch, sidebar) and by default their value is 0. So on the page I disable all plans that are already promoted with getting the value out of the datebase and then if the value is 0 the plan is available for promoting, and if its 1 its already promoted and its disabled for promoting. Now when the checkbox is selected for the certain plan it changes the checkbox value to 1, and then the plan is to update the listing and for example if user selected sidebar it will update the column from 0 to 1. But whatever I do the var featured, var topsearch and var sidebar won't change in my AJAX call after clicking them. It updates the checkbox input value but it won't reflect in my AJAX call.
jQuery:
$('.select-placement').hide();
$('.s-b').hide();
$('#count-duration').text('0');
$("#pick_listing, #no-text, #customCheck1, #customCheck2, #customCheck3").change(function() {
var selectedValue = $('#pick_listing').val();
$.ajax({
url: '../paypal/promote/promote.php',
type: 'POST',
data: {selectedValue: selectedValue},
success: function(data) {
$('.select-placement').show();
$(".select-results").html(data);
$('.s-b').show();
let ajax_duration = parseFloat($('#no-text').val() || '0');
if (ajax_duration == 1) {
$('#count-duration').text(ajax_duration + " day");
} else {
$('#count-duration').text(ajax_duration + " days");
}
// Changes checkbox value if its checked -- NOT WORKING
if ($('#customCheck1').is(':checked')) {
$("#customCheck1").val("1");
} else {
$("#customCheck1").val("0");
}
if ($('#customCheck2').is(':checked')) {
$("#customCheck2").val("1");
} else {
$("#customCheck2").val("0");
}
if ($('#customCheck3').is(':checked')) {
$("#customCheck3").val("1");
} else {
$("#customCheck3").val("0");
}
var duration_value = $('#no-text').val();
var listing = $('#pick_listing').val();
var featured = $('#customCheck1').val(); // It should update when the checkbox is checked
var topsearch = $('#customCheck2').val(); // It should update when the checkbox is checked
var sidebar = $('#customCheck3').val(); // It should update when the checkbox is checked
// This is the custom PayPal input in which I store all the collected variables
// All variables changes on change function instead of checkbox
$('input[name=custom]').val("<?php echo $current_token; ?>," + listing + "," + duration_value + "," + featured + "," + topsearch + "," + sidebar);
$('#tots').text("0");
$('#tots2').text("0");
$('#icon1').css('color','#ccc');
$('#icon2').css('color','#ccc');
$('#icon3').css('color','#ccc');
}
});
});
promote.php file:
$placement_token = $_POST['selectedValue']; // Getting the value from AJAX
// Call the promote options
$listing_placement = mysqli_query($conn, "SELECT featured, topsearch, sidebar FROM listing WHERE listing_token='$placement_token'"); ?>
<form id="custom-form" class="row row-placement">
<?php while($place_row = mysqli_fetch_row($listing_placement)) {
if ($place_row[0] == 1) { ?>
<div class="col-sm-4 listing-disabled">
<div class="select-ad disabled-ad">
<div class="already-promoted">Already Promoted</div>
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck1" data-price="10" value="1">
<label class="custom-control-label" for="customCheck1"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/spotlight.png">
</div>
<div class="price-content">
<h5>Featured</h5>
<label for="customCheck1">$10 / day</label>
</div>
</div>
</div>
<?php } else { ?>
<div class="col-sm-4">
<div class="select-ad active-ad">
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck1" data-price="10" value="0">
<label class="custom-control-label" for="customCheck1"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/spotlight.png">
</div>
<div class="price-content">
<h5>Featured</h5>
<label for="customCheck1">$10 / day</label>
</div>
</div>
</div>
<?php } if ($place_row[1] == 1) { ?>
<div class="col-sm-4 listing-disabled">
<div class="select-ad disabled-ad">
<div class="already-promoted">Already Promoted</div>
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck2" data-price="50" value="1">
<label class="custom-control-label" for="customCheck2"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/topofsearch.png">
</div>
<div class="price-content">
<h5>Top of Search</h5>
<label for="customCheck2">$50 / day</label>
</div>
</div>
</div>
<?php } else { ?>
<div class="col-sm-4">
<div class="select-ad active-ad">
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck2" data-price="50" value="0">
<label class="custom-control-label" for="customCheck2"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/topofsearch.png">
</div>
<div class="price-content">
<h5>Top of Search</h5>
<label for="customCheck2">$50 / day</label>
</div>
</div>
</div>
<?php } if ($place_row[2] == 1) { ?>
<div class="col-sm-4 listing-disabled">
<div class="select-ad disabled-ad">
<div class="already-promoted">Already Promoted</div>
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck3" data-price="20" value="1">
<label class="custom-control-label" for="customCheck3"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/listingsidebar.png">
</div>
<div class="price-content">
<h5>Sidebar</h5>
<label for="customCheck3">$20 / day</label>
</div>
</div>
</div>
<?php } else { ?>
<div class="col-sm-4">
<div class="select-ad active-ad">
<div class="ad-image">
<div class="lp-select-top input-group margin-right-0 clearfix">
<div class="custom-control custom-checkbox cst-check">
<input type="checkbox" class="custom-control-input checks" id="customCheck3" data-price="20" value="0">
<label class="custom-control-label" for="customCheck3"></label>
</div>
</div>
<img src="https://classic.listingprowp.com/wp-content/themes/listingpro/assets/images/listingsidebar.png">
</div>
<div class="price-content">
<h5>Sidebar</h5>
<label for="customCheck3">$20 / day</label>
</div>
</div>
</div>
<?php } } ?>
</form>
And I really got confused because the var duration_value and var selectedValue gets updated on every change, but checkboxese won't. I have read that I should be using document on change instead of just change function but I tried and it didn't helped. I know that the posted question is messy but I couldn't replicate it in jsfiddle, sorry. I just need solutions on what could it be that is holding checkboxes to change its value on CHANGE.
Regards
Checkboxes are handled differently in html and in Javascript/JQuery. Value is not what you want to change here. You want to set your variable's value based on a checkbox property.
Based on your feedback I have updated the code where the select change makes the ajax call to initiate the form based on selected value. And then on change of any input in the form the values are read back to format the string for hidden field.
$('.select-placement').hide();
$('.s-b').hide();
$('#count-duration').text('0');
$("#pick_listing").change(function() {
var selectedValue = $('#pick_listing').val();
$.ajax({
url: '../paypal/promote/promote.php',
type: 'POST',
data: {selectedValue: selectedValue},
success: function(data) {
$('.select-placement').show();
$(".select-results").html(data);
$('.s-b').show();
$('#tots').text("0");
$('#tots2').text("0");
$('#icon1').css('color','#ccc');
$('#icon2').css('color','#ccc');
$('#icon3').css('color','#ccc');
}
});
});
$("#no-text, #customCheck1, #customCheck2, #customCheck3").change(function() {
let ajax_duration = parseFloat($('#no-text').val() || '0');
if (ajax_duration == 1) {
$('#count-duration').text(ajax_duration + " day");
} else {
$('#count-duration').text(ajax_duration + " days");
}
var duration_value = $('#no-text').val();
var listing = $('#pick_listing').val();
var featured = ($('#customCheck1').prop('checked')) ? "1" : "0";
var topsearch = ($('#customCheck2').prop('checked')) ? "1" : "0";
var sidebar = ($('#customCheck3').prop('checked')) ? "1" : "0";
// This is the custom PayPal input in which I store all the collected variables
// All variables changes on change function instead of checkbox
$('input[name=custom]').val("<?php echo $current_token; ?>," + listing + "," + duration_value + "," + featured + "," + topsearch + "," + sidebar);
});

Show / Hide Elements within the same parent div

I'm having trouble getting a div ('.option-other') within a parent group ('.other-row') to show/hide when the corresponding option of the select element ('.select-toggle') is selected. Right now if "other" is selected from either question set 1 or 2 it will show both of the '.option-other' divs. I tried using .parent() and .closest() as described in this solution, but can't seem to figure out the proper way to utilize it for this use case.
$(".select-toggle").change(function() {
var oth = false;
$(".select-toggle option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
if (oth) $('.option-other').show();
else $('.option-other').hide();
// tried this method as well but still doesnt work
// if (oth) $(this).closest('.other-row').children('.option-other').show();
// else $(this).closest('.other-row').children('.option-other').hide();
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
// you wrote:
// tried this method as well but still doesnt work
// if (oth) $(this).closest('.other-row').children('.option-other').show();
// else $(this).closest('.other-row').children('.option-other').hide();
You're close, but $.children only selects direct children of each .other-row. Since .option-other is inside .col inside .other-row, $.children can't see it. Use $.find instead.
// your original code:
var oth = false;
$(".select-toggle option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
This sets one visibility value for the entire page: if at least one "other" option is selected, anywhere, show all the text inputs. The change event is fired for the <select> that actually changed, so focus your efforts there:
var oth = false;
$(this).children("option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
if (oth) $(this).closest('.other-row').find('.option-other').show();
else $(this).closest('.other-row').find('.option-other').hide();
This works, but it could be cleaner. Showing or hiding an element based on a boolean is a common enough requirement that jQuery has a function for it: $.toggle. You can replace the if/else lines with
$(this).closest('.other-row').find('.option-other').toggle(oth);
Your $.each loop does one thing: set oth if there exists at least one selected <option> with a value of "other". You can get the same logic as a one-liner by using an attribute selector:
var oth = ($(this).find('option:checked[value="other"]').length !== 0);
(I changed :selected to :checked because you're already filtering on option elements, and :selected has a performance penalty.)
The final version:
$(".select-toggle").change(function() {
var oth = ($(this).find('option:checked[value="other"]').length !== 0);
$(this).closest('.other-row').find('.option-other').toggle(oth);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
Vanilla JS version:
document.querySelectorAll('.select-toggle').forEach(el => {
el.addEventListener('change', evt => {
const oth = evt.target.querySelector('option:checked[value="other"]');
evt.target
.closest('.other-row')
.querySelector('.option-other')
.style.display = (oth ? '' : 'none');
});
// trigger change event programmatically
const event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);
});
Here is a solution that is a little clunky but I did it relatively quick. It's kind of a work around for having to know which of your two selectors with the same class had been selected.
Here is a working example using your code.
$(".select-toggle").change(function () {
var oth = false;
$(".select-toggle option:selected").each(function () {
if ($(this).val() == "otherFood") {
oth = true;
$('.option-other-food').show();
} else {
$('.option-other-food').hide();
};
if ($(this).val() == "otherDrink") {
oth = true;
$('.option-other-drink').show();
} else {
$('.option-other-drink').hide();
};
});
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="otherFood">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other-food">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like"/>
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="otherDrink">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other-drink">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like"/>
</div>
</div>
</div>
Cheers!

Get and set value on another div

I am working in ASP.Net MVC4. My div elements contents are generated in a loop as below:
#foreach (var product in Model.Products)
{
<div class="col-md-2 vcenter">
<span class="product-price">Preço: #Model.Price.ToString("C")</span>
</div>
#if (Model.IsValid != null && Model.IsValid != "")
{
<div class="col-md-2" style="text-align: end;">
<span>Enter number.</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
#Html.TextBoxFor(m => m.CouponTemp, new {
#class = "product-discount-coupon",
chart_price = Model.Price.ToString(),
dicsount_price = Model.SpecialPrice.ToString(),
product_coupon = Model.Coupon,
style = "width:50px;"
})
<button type="button" class="apply-discount">Recalculate</button>
</div>
}
}
JavaScript portion
$(".apply-discount").on("click", function () {
var applyCoupon = $(this).parent().find(".product-discount-coupon").val();
var price = $(this).parent().find(".product-price").val();
var cost = 0;
if (applyCoupon === NaN) {
applyCoupon = 0;
}
if (price === NaN) {
price = 0;
}
$(this).parent().find(".product-price").val(applyCoupon);
});
Browser generated html is below
<div>
<div class="col-md-1">
<img src="/Astrology/Product/GetImage/51da66b7-3cb9-418b-ae9a-bc9fe8073b26" style="width: 50px; height: 50px;" alt="Mapa Natal Cármico" />
</div>
<div class="col-md-6 vcenter">
<span style="font-size: large">Mapa Natal Cármico. Escrito por Marcelo Dalla</span>
</div>
<div class="col-md-2 vcenter">
<span class="product-price">Preço: R$ 44,00</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
<button type="button" class="dec-count">-</button>
<input chart-price="44,0000" class="product-count" data-val="true" data-val-number="The field Quantity must be a number." data-val-required="The Quantity field is required." dicsount-price="10,0000" id="products_7819060a-0f29-4637-83de-9262beb1a13f__Quantity" name="products[7819060a-0f29-4637-83de-9262beb1a13f].Quantity" product-coupon="10" readonly="readonly" style="width:50px;" type="text" value="1" />
<button type="button" class="inc-count">+</button>
</div>
<span>If you have a discount coupon for the purchase please enter it here and press the recalculate button.</span>
<div class="col-md-2 vcenter" style="text-align: end;">
<input chart-price="44,0000" class="product-discount-coupon" dicsount-price="10,0000" id="products_7819060a-0f29-4637-83de-9262beb1a13f__CouponTemp" name="products[7819060a-0f29-4637-83de-9262beb1a13f].CouponTemp" product-coupon="10" style="width:50px;" type="text" value="" />
<button type="button" class="apply-discount">Recalculate</button>
<input id="apply-product-coupon" type="hidden" name="apply-product-coupon">
</div>
<div class="col-md-1 vcenter">
<a href="/Astrology/Shop/DeleteFromCard?productId=41f7e40b-62ad-4202-964a-cbed7381b06c">
<i class="fa fa-remove"></i>
</a>
</div>
</div>
When the user clicks on the Recalculate button I want to put CouponTemp textbox value in another span. Note that clicking on block-1 does not impact on block-2 or rest, in the same way click on block-2 not impact on another block content.
<span>Preço: #Model.Price.ToString("C")</span>
Here is your script:
$(document).ready(function(){
$("button.apply-discount").click(function(){
//get your input value
var discount = $(this).prev('input.product-discount-coupon').first().val();
//Get your span
var resultSpan = $(this).parent().prev().prev().prev().find('span');
//Update your span with input value
resultSpan.html("Preço: R$ " + discount);
});
});
I create JSFiddle to show how it works.
Following code snippet may help you.
$(".apply-discount").on("click", function () {
var applyCoupon = $(this).parent().find(".product-discount-coupon");
var price = applyCoupon.val();
//to get others info
var chart_price= applyCoupon.attr('chart_price');
var dicsount_price= applyCoupon.attr('dicsount_price');
var product_coupon= applyCoupon.attr('product_coupon');
$(this).parent().prev().prev().find(".product-price").html('Preço: '+price*1);
});
N.B: price*1 will convert it to a number.
Well, pretty easy if you just assign ids to the elements. Use something like id from your product to ensure they are unique and match.
#foreach (var product in Model.Products)
{
<div class="col-md-2 vcenter">
<span>Preço: #Model.Price.ToString("C")</span>
</div>
#if (Model.IsValid != null && Model.IsValid != "")
{
<div class="col-md-2" style="text-align: end;">
<span id="#product.Id">Enter number.</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
#Html.TextBoxFor(m => m.CouponTemp, new {
#class = "product-discount-coupon",
chart_price = Model.Price.ToString(),
dicsount_price = Model.SpecialPrice.ToString(),
product_coupon = Model.Coupon,
style = "width:50px;",
id = "txt_" + #product.Id
})
<button type="button" class="apply-discount" onclick="adjustPrice(#product.Id);">Recalculate</button>
</div>
}
}
Then have a function that handles it:
<script type="text/javascript">
var adjustPrice = function (id) {
var txt = $('#txt_' + id).val();
$('#' + id).val(txt);
};
</script>

How can i check radio button by default?

On page load i want to show below radio button selected by default i used html attribute but its not working. So on page load I want to show all process radio button checked by default. Is there any other way to achieve this task?
radio.html
<div class="panel panel-default">
<div class="panel-heading">View/Search Inventory</div>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterOptions"
k-ng-model="kfilter" ng-model="filter" ng-change="onChange()"></select>
</div>
<div ng-show="filter=='PROCESS'" ng-init="search.showCriteria='allProcess';onChange()">
<div class="col-md-7">
<label class="radio-inline" for="allProcess"> <input
type="radio" name="optionsRadios1" ng-value="'allProcess'"
id="allProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show All Processes
</label> <label class="radio-inline" for="ratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'ratedProcess'"
id="ratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Rated Processes
</label> <label class="radio-inline" for="unratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'unratedProcess'"
id="unratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unrated Processes
</label>
</div>
</div>
<div ng-show="filter=='RISK'">
<div class="col-md-7">
<label class="radio-inline" for="allRisk"> <input
type="radio" name="optionsRadios1" ng-value="'allRisk'"
id="allRisk" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Risks
</label> <label class="radio-inline"> <input type="radio"
name="optionsRadios1" ng-value="'unalignedRisk'"
ng-model="search.showCriteria" ng-change="selectSearchType()">
Show Unaligned Risks
</label>
</div>
</div>
<div ng-show="filter=='CONTROL'">
<div class="col-md-7">
<label class="radio-inline" for="allControl"> <input
type="radio" name="optionsRadios1" ng-value="'allControl'"
id="allControl" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Controls
</label> <label class="radio-inline" for="unalignedControl"> <input
type="radio" name="optionsRadios1" ng-value="'unalignedControl'"
id="unalignedControl" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unaligned Controls
</label>
</div>
</div>
<div class="col-md-2">
<button class="btn btn-default" type="button" ng-click="search(0)">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
<div class="row">
<!--<label for="filterBy" class="col-md-1">Filter by: </label>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'" k-option-label="'Select'"
k-data-value-field="'value'" k-data-source="filterByOptions"
k-ng-model="kfilterBy" ng-model="filterBy" style="width: 100%"></select>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterByValues" k-option-label="'Select'"
k-ng-model="kfilterByValue" ng-model="filterByValue" style="width: 100%"></select>
</div> -->
<div class="col-md-3">
<a href="" ng-show="!showAdvance" ng-click="advanceFilter()">Advanced
Search</a> <a href="" ng-show="showAdvance" ng-click="advanceFilter()">Basic
Search</a>
<!-- <button ng-show="!showAdvance" class="btn btn-default" type="button" ng-click="search()">Go</button> -->
</div>
</div>
<form role="form" name="formTimeLine" kendo-validator="validator"
k-options="myValidatorOptions">
<div ng-show="showAdvance">
<div class="clone" ng-repeat="input in inputs">
<br />
<div class="row">
<div class="col-md-1">
<a ng-if="inputs.length < searchOptions.length"
class="add col-md-1" name="addnumadd" ng-click="add($index)"> </a>
<a ng-if="inputs.length >1" class="delete col-md-1"
name="deletenumadd" ng-click="remove($index)"> </a>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-option-label="'Select'" k-data-value-field="'value'"
k-data-source="searchOptions" name="searchBy-{{$index}}"
ng-model="input.searchBy"
data-required-msg="Please select the value"
ng-change="clearPreviousValue({{$index}})" data-duplicate=""
style="width: 100%" required></select>
</div>
<div class="col-md-3">
<input type="text" class="form-control"
ng-model="input.searchValue" placeholder="Enter search item"
ng-maxlength="256" name={{$index}}>
</div>
<div class="col-md-4">
<input type="radio" name={{$index}} value="exactMatch"
ng-model="input.exactMatch" data-requiredCheckbox=""> Exact
Match <input type="radio" name={{$index}} value="contains"
ng-model="input.exactMatch" data-requiredCheckbox=""> Contains
<span class="k-invalid-msg" data-for={{$index}}></span>
</div>
</div>
</div>
</div>
</form>
</div>
<div id="outergrid" class="row">
<ng-include src="gridInclude"></ng-include>
</div>
</div>
radio.js
$scope.processSearchOptions = processSearchOptions;
$scope.riskSearchOptions = riskSearchOptions;
$scope.controlSearchOptions = controlSearchOptions;
$scope.filterByOptions = filterByOptions;
$scope.filterByValues = filterByValues;
$scope.searchOptions = processSearchOptions;
$scope.onChange = function () {
var value = $scope.filter;
$scope.postArgs.page = 1;
if (value === 'PROCESS') {
$scope.search.showCriteria = 'allProcess';
$scope.searchOptions = processSearchOptions;
$scope.gridInclude = 'views/viewAll/processGrid.html';
}
if (value === 'RISK') {
$scope.search.showCriteria = 'allRisk';
$scope.searchOptions = riskSearchOptions;
$scope.gridInclude = 'views/viewAll/riskGrid.html';
}
if (value === 'CONTROL') {
$scope.search.showCriteria = 'allControl';
$scope.searchOptions = controlSearchOptions;
$scope.gridInclude = 'views/viewAll/controlGrid.html';
}
$scope.showAdvance = false;
$scope.clearAdvFilter();
$scope.postArgs = {
page: 1
};
};
//initialize process grid
initializeGrid('process');
$scope.processGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.processGridColumns);
$scope.processInnerGridOptions = viewSearchInvService.getInnerProcessGrid;
//initialize risk grid
initializeGrid('risk');
$scope.riskGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.riskGridColumns);
$scope.riskInnerGridOptions = viewSearchInvService.getInnerRiskGrid;
//initialize control grid
initializeGrid('control');
$scope.controlGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.controlGridColumns);
$scope.controlInnerGridOptions = viewSearchInvService.getInnerControlGrid;
$scope.ProcessEditHandler = function (id) {
ViewEditPrcsService.saveProcessId(id);
};
$scope.RiskEditHandler = function (id) {
ViewEditRiskService.saveRiskId(id);
};
$scope.advanceFilter = function () {
if ($scope.showAdvance) {
$scope.clearAdvFilter();
$scope.showAdvance = false;
} else {
$scope.showAdvance = true;
}
};
$scope.clearAdvFilter = function () {
$scope.inputs = [];
$scope.inputs.push(getNewObject());
};
$scope.search = function () {
if ($scope.validator.validate() || !$scope.showAdvance) {
searchCriteria(1);
searchFlag = true;
if ($scope.filter === 'PROCESS') {
$scope.search.process.dataSource.read();
}
if ($scope.filter === 'RISK') {
$scope.search.risk.dataSource.read();
}
if ($scope.filter === 'CONTROL') {
$scope.search.control.dataSource.read();
}
}
};
$scope.selectSearchType = function () {
$scope.clearAdvFilter();
$scope.showAdvance = false;
$scope.search();
};
$scope.add = function () {
$scope.inputs.push(getNewObject());
};
$scope.remove = function (index) {
$scope.inputs.splice(index, 1);
};
$scope.myValidatorOptions = {
rules: {
duplicate: function (input) {
return checkDuplicates(input.val(), input[0].name);
},
requiredCheckbox: function (input) {
return !(input[0].type === 'radio' && !$scope.inputs[input[0].name].exactMatch && !$scope.inputs[input[0].name].contains);
}
},
messages: {
duplicate: 'Option already selected. please select another option',
requiredCheckbox: 'Operator is required'
}
};
$scope.clearPreviousValue = function (index) {
$scope.inputs[index].searchValue = '';
};
});
Without knowing more about the specifics of when you want this checked, apply the following using ngChecked. In this case, checked if true, but this can be any expression
ng-checked="true"
JSFiddle Link
In response to your updated code, you could leverage ngInit on your parent <div> for defaulting one radio button in a group. Note for isolating the direct issue I have slimmed down most of this markup
<div ng-init="search.showCriteria='allProcess'">
Updated JSFiddle Link
You need to make sure your model is set to the value of the radio box.
$scope.search.showCriteria = 'allProcess'
As a side node, you don't need to be using ng-value here. You could use just use value="allProcess" because ng-value is only needed for Angular expressions, not plain strings.

Categories