Refresh radio button without jquery ui - javascript

TL;DR; how to properly implement $('#radioBtn').checkboxradio("refresh"); without the jquery ui library?
I'm working on a project and need the radio buttons to be unselectable + clicking on a table row acting like clicking the radio button.
I'm facing the issue that the radio buttons have to be refreshed after setting the checked/not checked attribute. How do I do this without relying on jquery ui?
Interestingly, if you call any function (that does not exist) on the radio button it gets refreshed.
NOTE: I'm asking about updating the radio button view to show the correct check state, not setting the checked state of the radio.
https://jsfiddle.net/8uno2ybf/5/
$(function() {
var inputClickHandler = function() {
var previousValue = $(this).attr('previousValue');
var name = $(this).attr('name');
if (previousValue == 'checked') {
$(this).prop('checked', false);
$(this).attr('previousValue', false);
$(this).checkboxradio("refresh"); //This refreshes it for some reason
} else {
$("input[name=" + name + "]:radio").attr('previousValue', false);
$(this).attr('previousValue', 'checked');
}
};
$("input[type='radio']").click(inputClickHandler);
$('.monitored_table tbody tr').click(function(event) {
if (event.target.type !== 'radio') {
$(':radio', this).trigger("click");
}
});
console.log("OnLoad");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="monitored_table">
<tr>
<td>Text1</td>
<td>
<input type="radio" name="group1" value="1">
</td>
</tr>
<tr>
<td>Text2</td>
<td>
<input type="radio" name="group1" value="2">
</td>
</tr>
<tr>
<td>Text3</td>
<td>
<input type="radio" name="group1" value="3">
</td>
</tr>
</table>

You don't need Jquery UI for this purpose, Jquery is enough. However; you are trying to execute an inexistent function which breaks the flow of your code. You should check whether the function exists or not by using this function. Therefore; once the javascript code fails refresh is possible in your code blocks

Related

Why does my radio button event trigger when a different radio button is pressed?

I am using the following code to show "pers" and hide "bus" and vice versa
JQuery:
$('input[name="perorbus"]').click(function() {
if ($(this).attr('id') == 'bus') {
$('#showbus').show();
$('#showper').hide();
}
if ($(this).attr('id') == 'pers') {
$('#showper').show();
$('#showbus').hide();
}
});
HTML:
<fieldset id="perorbus">
<label style="font-size: large;">Personal Or Business?</label>
<br/>
<input type="radio" class="PerOrBus" value="pers" id="pers" name="perorbus"/>
<label style="font-size: medium;">Personal Customer</label>
<input type="radio" class="PerOrBus" id="bus" value="bus" name="perorbus"/>
<label style="font-size: medium;">Business Customer?</label>
<br/>
</fieldset>
<table id="showper">
<tr>
<td>Show Personal</td>
</table>
<table id="showbus">
<tr>
<td>Show Business</td>
</table>
Any other Radio button that I put on the page triggers this. They are all given a name attribute like the following:
<fieldset id="CACCc">
<input type="radio" id="1b" class="2b" value="4b" name="1b"/> Yes
<br/>
<input type="radio" id="id12" class="4class" value="4c" name="id12"/> No ​
<br/></fieldset>
However, I have to assign the name on doc ready with jquery like the following:
document.getElementById("1b").setAttribute('name', '1b');
document.getElementById("id12").setAttribute('name', 'id12');
This is due to me being limited to not using name attributes in the HTML (long story)
Any help would be great, thanks
Try going by the radio button and then the name of the radio button. Also use the change trigger. By the way, your fieldset has the same name. That could be an issue.
$(document).ready(function() {
// Update names
$('input[type=radio][name=perorbus]').change(function() {
if (this.id == 'bus') {
$('#showbus').show();
$('#showper').hide();
}
if (this.id == 'pers') {
$('#showper').show();
$('#showbus').hide();
}
});
});
The answer to my issue specifically is that is was a Sharepoint caching issue. Because I do not have access to remove cache, I simply renamed and re-id'd everything and got it working.
This will not solve other peoples issues, probably but the other answers should.

function find() with variable as a parameter returns empty object

I'm refactoring a code on a generated web page and there is a div (tab) which can occur multiple times. There is a small section with check-boxes on each and every such div, which lets you choose other divs that will be shown.
Since there is a chance for other divs to be added to the page I wanted to make the code modular. Meaning that every checkbox id is identical to the class of the div, which it should toggle, with added "Div" at the end. So I use checked id, concat it with "." and "Div" and try to find it in closest fieldset.
Here is the almost working fiddle: http://jsfiddle.net/ebwokLpf/5/ (I can't find the way to make the onchange work)
Here is the code:
$(document).ready(function(){
$(".inChecks").each(function(){
changeDivState($(this));
});
});
function changeDivState(element){
var divClassSel = "." + element.attr("id") + "Div";
var cloField = element.closest("fieldset");
if(element.prop("checked")){
cloField.find(divClassSel).toggle(true);
} else {
cloField.find(divClassSel).toggle(false);
}
}
Aside for that not-working onchange, this functionality does what it's intended to do. However only on the jsfiddle. The same code does not work on my page.
When I used log on variables from the code, the result was as this
console.log(divClassSel) => inRedDiv
console.log($(divClassSel)) => Object[div.etc.]
console.log(cloField) => Object[fieldset.etc.]
//but
console.log(cloField.find(divClassSel)) => Object[]
According to firebug the version of the jQuery is 1.7.1
Since I can't find any solution to this is there any other way how to make it in modular manner? Or is there some mistake I'm not aware of? I'm trying to avoid writing a function with x checks for element id, or unique functions for every check-box (the way it was done before).
Remove the inline onchange and also you don't need to iterate on the elements.
Just write one event on class "inCheckes" and pass the current element reference to your function:
HTML:
<fieldset id="field1">
<legend>Fieldset 1</legend>
<table class="gridtable">
<tr>
<td>
<input id="inRed" class="inChecks" type="checkbox" checked="checked" />
</td>
<td>Red</td>
</tr>
<tr>
<td>
<input id="inBlue" class="inChecks" type="checkbox" />
</td>
<td>Blue</td>
</tr>
</table>
<div class="inDivs">
<div class="inRedDiv redDiv"></div>
<div class="inBlueDiv blueDiv" /></div>
</fieldset>
<fieldset id="field2">
<legend>Fieldset 2</legend>
<table class="gridtable">
<tr>
<td>
<input id="inRed" class="inChecks" type="checkbox" />
</td>
<td>Red</td>
</tr>
<tr>
<td>
<input id="inBlue" class="inChecks" type="checkbox" checked="checked" />
</td>
<td>Blue</td>
</tr>
</table>
<div class="inDivs">
<div class="inRedDiv redDiv"></div>
<div class="inBlueDiv blueDiv" /></div>
</fieldset>
JQUERY:
$(document).ready(function () {
$(".inChecks").change(function () {
changeDivState($(this));
})
});
FIDDLE:
http://jsfiddle.net/ebwokLpf/4/
As gillesc said in the comments changing the javascript code to something like this made it work.
$(document).ready(function(){
$(".inChecks").each(function(){
changeDivState($(this));
});
$(".inChecks").on("change", function() {
changeDivState($(this));
});
});
function changeDivState(element){
var divClassSel = "." + element.attr("id") + "Div";
var cloField = element.closest("fieldset");
if(element.prop("checked")){
cloField.find(divClassSel).toggle(true);
} else {
cloField.find(divClassSel).toggle(false);
}
}
You asked for an other way how to make it in modular manner:
You can create a jQuery plugin which handles the logic for one fieldset including changing the color when clicking different checkboxes.
This way all logic is bundled in one place (in the plugin) and you can refine it later on.
For example you can decide later on that the plugin should create the whole html structure of the fieldset (like jQuery UI slider plugin creates the whole structure for the slider element) and therefore change the plugin.
The code for the (first version) of your jQuery plugin could look something like this:
$.fn.colorField = function() {
var $colorDiv = this.find('.colorDiv'),
$inputs = this.find('input'),
$checked = $inputs.filter(':checked');
if($checked.length) {
// set initial color
$colorDiv.css('background', $checked.attr('data-color'));
}
$inputs.change(function() {
var $this = $(this),
background = '#999'; // the default color
if($this.prop('checked')) {
// uncheck the other checkboxes
$inputs.not(this).prop('checked', false);
// read the color for this checkbox
background = $(this).attr('data-color');
}
// change the color of the colorDiv container
$colorDiv.css('background', background);
});
};
The plugin uses the data-color-attributes of the checkboxes to change the color of the colorDiv container. So every checkbox needs an data-color attribute, but multiple divs for different colors are not necessary anymore.
The HTML code (for one fieldset):
<fieldset id="field1">
<legend>Fieldset 1</legend>
<table class="gridtable">
<tr><td><input id="inRed" class="inChecks" type="checkbox" checked="checked" data-color='#ff1005' /></td><td>Red</td></tr>
<tr><td><input id="inBlue" class="inChecks" type="checkbox" data-color='#00adff' /></td><td>Blue</td></tr>
</table>
<div class="colorDiv"></div>
</fieldset>
Now you can create instances with your colorField-plugin like this:
$(document).ready(function(){
$('#field1').colorField();
$('#field2').colorField();
});
Here is a working jsFiddle-demo

How to hide some detail in html form when radio button is selected?

I am creating student registration form as shown in the image:
The code is as follows:
<tr><td><input type="radio" checked="checked" name="rad1"> Pursuing <input type="radio" name="rad1"/> Completed </td></tr>
<tr><td align="right"><label>Avarage CPI * : </label></td>
<td><input type="number" name="cpi" step="0.01" />upto<input type="number" name="semester"/>th semester</td>
</tr>
Now if user selects "Completed" then upto ____ th semester should be disappeared as shown in following image.
How can i do it? Should I use "onchange()" or "onselect()" event? If yes then how?
asku's answer won't behave as expected, check this fiddle
it'll hide the semester upon when selecting pursing.
if the user selects one radio that hides the semester and then select the other one, semester won't be displayed again.
working fiddle
the code should be -
window.onload = function () {
document.getElementsByName('rad1')[0].onchange = function () {
document.getElementById('semester').style.display = 'initial';
}
document.getElementsByName('rad1')[1].onchange = function () {
document.getElementById('semester').style.display = 'none';
}
}

radio button in html

I am trying to get the selected value from the radio button this is the jsfiddle.
HTML :
<table>
<tr>
<td> Is Reference Number Available</td>
<td> <input type="radio" name="group1" value="yes" onchange="isReferenceNumberAvailable()"> Yes</input>
<input type="radio" name="group1" value="no" onchange="isReferenceNumberAvailable()"> No </input>
</td>
</tr>
</table>
javascript :
function isReferenceNumberAvailable()
{
var test = document.getElementsByName("group1");
for(var elem in test)
{
if(test[elem].checked)
{
alert(test[elem].value); // got the element which is checked
if(test[elem].value=="yes")
alert("Need to create Reference select box");
else if(test[elem].value=="no")
alert("don't create ");
}
}
}
But when I select the radio button i get the following :
Uncaught ReferenceError: isReferenceNumberAvailable is not defined
Check out this
http://jsfiddle.net/9JQU6/
function isReferenceNumberAvailable()
{
var test = document.getElementsByName("group1");
for(var elem in test)
{
if(test[elem].checked)
{
alert(test[elem].value); // got the element which is checked
if(test[elem].value=="yes")
alert("Need to create Reference select box");
else if(test[elem].value=="no")
alert("don't create ");
}
}
}
Reason
Your code is working only error is javascript place error see this demo
The problem is only that its not getting linked in fiddle, it works when placed inside script tags within your HTML see Check this
<script> Within this together with html its fine </script>
Use following script using jquery
$(document).ready(function(){
$('input:radio').click(function(){
alert$('input[name=group1]:checked').val()); // get selected radio button value
// do what you need here
});
});
http://jsbin.com/anAyIWUN/1/edit
Try always to put all your JS before the closing </body> tag.
Regarding your HTML and scripts I would go with something nicer and simpler:
<table>
<tr>
<td> Is Reference Number Available</td>
<td>
<input type="radio" name="group1" value="yes"> Yes
<input type="radio" name="group1" value="no"> No
</td>
</tr>
</table>
JS:
var $el = document.getElementsByName("group1"),
msg = {"yes":"Need to create Reference select box", "no":"Don't create"};
function getVal(){
if(this.checked) alert( msg[this.value] );
}
for(var i=0; i<$el.length; i++)
$el[i].onchange = getVal;

adding check all and uncheck all option using value inside checkbox

I am trying to create a select all, unselect all options like we see in email inboxes for a group of checkboxes. I have added an example for this. The working model that I am trying to get is when a I click on checkbox, it should select and unselect that group with a particular value. Also even if we uncheck any single name form the list, it should uncheck the main "select all" checkbox. I've added a jsfiddle, but it doesnt work properly.
$(document).ready(function(){
$("#selectAll").live("click",function(e){
e.preventDefault();
e.stopImmediatePropagation();
var clickedValue=$(this).attr('class');
clickedValue=clickedValue.replace("select", "");
$("#modalEntity").attr("value", "group"+ clickedValue).attr("checked", true);
});
});
http://jsfiddle.net/EBxSu/
UPDATE (changed live to on & some renaming)
First, you should never have elements with the same ID like this:
<input id="modalEntity" class="entity1" type="checkbox" value="group1" name="India">India
<input id="modalEntity" class="entity2" type="checkbox" value="group1" name="UAE">UAE
I rewrote the jQuery code to this:
$(document).ready(function() {
"use strict";
$("input.select").on("click", function() {
$(this).siblings().find("input.entity").prop("checked", $(this).is(":checked"));
});
$("input.entity").on("click", function() {
var $entityGroup = $(this).siblings().andSelf();
$(this).parent().siblings("input.select").prop("checked", $entityGroup.length === $entityGroup.filter(":checked").length);
});
});
.prop() should only be used on jQuery 1.6 and above.
I also rewrote you HTML a bit, look at the updated jsFiddle here: http://jsfiddle.net/sQVe/EBxSu/8/
Just comment if I missed something, but I think this is what you're after.
I updated your code a bit removing multiple IDs and handling the various scenario requested (clearing the select all check box if user selects a child). Also updated your jQuery using .on() rather than .live().
jQuery looks like:
$(function(){
$('.selectAll').on('click', function(evt){
var group = $(this).attr('data-group'),
isChecked = !!($(this).prop('checked'));
$('input[value="' + group + '"]').prop('checked', isChecked);
})
$('.entity').on('click', function(evt){
var group = $(this).attr('value'),
siblings = $('input[value="' + group + '"]'),
isChecked = true;
siblings.each(function(idx, el){
if(!$(el).prop('checked')) {
isChecked = false;
return;
}
})
$('.selectAll[data-group="' + group + '"]').prop('checked', isChecked);
})
})
And the updated HTML:
<ul>
<li>
Country
<ul>
<input type="checkbox" class="selectAll" data-group="group1">Select/Deselect All Country
<li>
<input class="entity" type="checkbox" value="group1" name="India">India
<input class="entity" type="checkbox" value="group1" name="UAE">UAE
...
</ul>
</li>
</ul>
Here's the fiddle:
http://jsfiddle.net/nBh4L/2/
Thanks!
Jack
I have done that for countries only. Html:
<ul>
<li>
Country
<ul>
<input type="checkbox" id="selectAll" class="select1">Select/Deselect All Country
<li>
<input class="entity1 countries" type="checkbox" value="group1" name="India">India
<input class="entity2 countries" type="checkbox" value="group1" name="UAE">UAE
</li>
</ul>
</li>
<li>​
JavaScript:
$(document).ready(function(){
$("#selectAll").click(function(){
if(!$('.countries').attr('checked'))
$('.countries').attr('checked','checked');
else
$('.countries').removeAttr('checked');
});
$('.countries').click(function(){
var allChecked = true;
$('.countries').each(function(index, element){
if(!$(element).attr('checked'))
allChecked = false;
});
if(!allChecked)
$("#selectAll").removeAttr('checked');
else
$("#selectAll").attr('checked','checked');
});
});​
I updated your JS fiddle with a more correct soltuion:
http://jsfiddle.net/EBxSu/2/
There are a few things that I would like you point out that you are doing wrong, and maybe it will help you with this:
You were using HTML "id" and class" attributes wrong. ID should be unique. Class need not be unique - I switched them around for you.
You don't need to prevent default unless you don't want the checkbox to be checked.
You had a with text inside a tag - this is not valid. Only can exist within a tag - so I moved it out side of the
jQuery should not be complicated. It can be very simple. I moved the HTML around a bit (check the link).
Your javascript code is now simply:
$(document).ready(function() {
$(".selectAll").click(function(e) {
$(this).siblings('ul').find('input').attr('checked', $(this).is(":checked"));
});
});​
ID's are meant to be unique per page, but ignoring some of the mark-up problems with your code, I have edited it so it works as you intended. http://jsfiddle.net/xYWWM/5/
$(document).ready(function() {
$("#selectAll").live("click", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var clickedValue = $(this).attr('class');
clickedValue = clickedValue.replace("select", "");
var checkboxes = $("#modalEntity[value=\"group" + clickedValue + "\"]");
checkboxes.attr("checked", !checkboxes.attr("checked"));
});
});
Follow this Tutorial
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/
Also, Check out this Fiddle for Demo
Here is the HTML used in the Demo,
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Cell phone</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
<td>Droid X</td>
<td>4.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
<td>HTC Desire</td>
<td>3/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
<td>Apple iPhone 4</td>
<td>5/5</td>
</tr>
</table>
Here is the jQuery for the Demo
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
I didn't understand you solution, but here's one. First, keep similar groups of buttons with a common attribute, say relation, having a value of child. Then keep the selector/deselector for that group with the same name but the value of relation attribute set to parent. Now you have to
1.Toggle the state of all similar child checkboxes when the mother's state is toggled:
$("[relation=parent]").change(function() {
name = $(this).prop('name');
$("[relation=child][name="+name+"]").attr('checked',$(this).attr('checked'));
});
2.Toggle the mother's state accordingly when a child's state is toggled:
$("[relation=parent]").change(function() {
name = $(this).attr('name');
$("[relation=child][name="+name+"]").attr('checked',$(this).attr('checked'));
});
$("[relation=child]").change(function() {
name = $(this).attr('name');
if ($(this).attr('checked') == false) {
$("[relation=parent][name="+name+"]").attr('checked',false);
}
else {
if ($("[name="+name+"][relation=child]:checked").length == $("[name="+name+"][relation=child]").length) {
$("[name="+name+"][relation=parent]").attr('checked','true');
}
}
});
There are couple of things you should note while write you code.
1. Keep it simple.
2. Do not use id multiple times
3. Write a html code. Nesting <ul><inputl><li> is not a good idea.
This is simplified solution, which hopefully you'll be able to understand and will be able to implement in later at different situation.
HTML:
<input type="checkbox" id="btn-select-all-1">Select/un-select All
<ul>
<li><input type="checkbox" class="select1">item1</li>
<li><input type="checkbox" class="select1">item1</li>
<li><input type="checkbox" class="select1">item1</li>
<li><input type="checkbox" class="select1">item1</li>
</ul>
Jquery:
$(document).ready(function(){
var btnSelectAll = $("#btn-select-all-1");
var toSelect = $('.select1')
//monitor the select_all checkbox for changes
//and take appropriate action
btnSelectAll.on('click', function(){
if(btnSelectAll.is(":checked")){
toSelect.attr("checked", "checked");
}else{
toSelect.removeAttr("checked");
}
});
});
jsFiddle: http://jsfiddle.net/U8aFU/
more help and links:
Check if checkbox is checked with jQuery
Setting "checked" for a checkbox with jQuery?
I've modified your HTML slightly since you used same ID twice ...Below is the working script...
<ul><li>
Country
<ul>
<input type="checkbox" id="selectAll1" class="selectAll">Select/Deselect All Country
<li>
<input id="modalEntity1" class="entity" type="checkbox" value="group1" name="India">India
<input id="modalEntity2" class="entity" type="checkbox" value="group1" name="UAE">UAE
</li>
</ul>
</li>
<li>Company<ul>
<input type="checkbox" id="selectAll2" class='selectAll'>Select/Deselect All Company</a>
<li>
<input id="modalEntity3" class="entity" type="checkbox" value="group2" name="Apple">Apple
<input id="modalEntity4" class="entity" type="checkbox" value="group2" name="Google">Google
</li>
</ul>
</li>
</ul>​
jQuery:
$(document).ready(function(){
$('.selectAll').click(function(){
var thisStatus = $(this).attr('checked');
if(thisStatus=='checked'){
$(this).parent('ul').find('input[type="checkbox"]').attr('checked','checked');
}
else{
$(this).parent('ul').find('input[type="checkbox"]').attr('checked',false);
}
});
$('input.entity').click(function(){
var thisStatus = $(this).attr('checked');
if(thisStatus!=='checked'){
$(this).parent().parent('ul').find('input.selectAll').attr('checked',false);
}
else{
$("input.entity:checked").each(function(){
$(this).parent().parent('ul').find('input.selectAll').attr('checked','checked');
});
}
});
});​

Categories