jQuery multiple id sets multiple patterns - javascript

OK, sure this is really simple, but I'm new to Java / jQuery so all help knowledge is greatly appreciated!
I have three sets of information, but i want each set to behave the same way, when I check a box, I want a certain div to appear, then disappear when the checkbox is unchecked...
Started with this, and it works...
//Set 1 #mod_1 toggles #sec_mod_1..
$('#sec_mod_1').change(function() {
$('#mod_1').toggle(this.checked);
}).change();
//Set 2
$('#sec_mod_2').change(function() {
$('#mod_2').toggle(this.checked);
}).change();
//Set 3
$('#sec_mod_3').change(function() {
$('#mod_3').toggle(this.checked);
}).change();
Now this is a little long winded, and I know there has to be a shorter way... Thinking something like this...
$('[id^="sec_mod_"]').change(function() {
$('[id^="mod_"]').toggle(this.checked);
}).change();
However, I don't know how to make this function for each separate set, was thinking the "this" keyword...?
Like I said all help would be greatly appreciated...

Use a simple class selector:
$('.trigger').change(function() {
var $checkbox = $(this);
var id = $checkbox.attr('id'); // eg. sec_mod_1
var numb = id.substring(id.lastIndexOf('_') + 1); // eg. 1
$('#mod_' + numb).toggle(this.checked); // toggle #mod_1
}).change();
Add trigger as the class to the elements that needs this functionality.
Working jsfiddle

You may use:
$('#mode_' + this.id.replace('sec_mod_', ''), this).toggle(this.checked);

You can use use the same markup with a handler like
$('input[id^="sec_mod_"]').change(function() {
console.log('d')
$('#mode_' + this.id.replace('sec_mod_', '')).toggle(this.checked);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="sec_mod_1" type="checkbox" />
<div id="mode_1">1</div>
<input id="sec_mod_2" type="checkbox" />
<div id="mode_2">2</div>
<input id="sec_mod_3" type="checkbox" />
<div id="mode_3">3</div>
Or if you can change the markup
$('.sec_mod').change(function() {
$($(this).data('target')).toggle(this.checked);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="sec_mod_1" class="sec_mod" type="checkbox" data-target="#mode_1" />
<div id="mode_1">1</div>
<input id="sec_mod_2" class="sec_mod" type="checkbox" data-target="#mode_2" />
<div id="mode_2">2</div>
<input id="sec_mod_3" class="sec_mod" type="checkbox" data-target="#mode_3" />
<div id="mode_3">3</div>

Related

javascript iterating array of objects using checkboxes

I want to show div when checkboxis true and hide div when checkbox is false. For this reason I have created an array of objects, which have property(checkboxes and divs) and value(selectors of checkboxes and divs). But this code doesn't work. Where have I done a mistake?
https://jsfiddle.net/9LzLm9hx/9/
just change .attr("checked") to .is(":checked")
I don't understand why you give this useless piece of code:
<label for="common"></label> <span>Common</span>
Can be made useful this way:
<label for="common"> <span>Common</span></label>
And to solve your issue, rename the id of the checkboxes to match the class of the divs:
<input type="checkbox" id="post-id" />
<input type="checkbox" id="post-activation" />
And the <div>s:
<div class='col-xs-3 post-id'>id</div>
<div class='col-xs-3 post-activation'>active</div>
Then using jQuery:
$(function () {
$("input:checkbox").change(function () {
if (this.checked)
$("." + this.id).show();
else
$("." + this.id).hide();
});
});

Automatically checking / unchecking parent inputs

I'm hoping someone can help me out here.
I'm trying to automatically check parent items in an input list, but also uncheck children if the parent is unchecked.
The great thing is I found some code that replicates the desired functionality perfectly: http://jsfiddle.net/3y3Pb/14/
EDIT: To clarify - the functionality required is this: Check mark a child input & all of the parent items get checked. Uncheck a Parent - all child inputs get unchecked. See the above example.
However, this doesn't seem to be working with my particular code (it's output from a WordPress plugin - Advanced Custom Fields) so I don't want to modify it).
I've narrowed it down to what I BELIEVE is the problem. ACF wraps each input with a <label></label>. I don't know why, but this breaks the functionality:
http://jsfiddle.net/3y3Pb/223/
When I remove the <label></label> it works fine:
http://jsfiddle.net/3y3Pb/225/
Changing the markup isn't really an option here, I would REALLY appreciate it if someone could assist me in making this work!
This should work, its simple and only uses divs and a few lines of jquery:
$('[type="checkbox"]').change(function () {
var kids = $(this).next().next();
if (kids.is('div') && !$(this).prop('checked'))
{
kids.children().each(function(){$(this).prop('checked',false)});
}
var thisChecked = $(this).prop('checked');
var master = $(this).parent().prevAll('[type="checkbox"]:first');
master.prop('checked', thisChecked ? true : master.prop('checked'));
});
div {
margin-left: 25px;
}
div div {
margin-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />Master Check
<br />
<div>
<input type="checkbox" />Slave Check 1
<br />
<input type="checkbox" />Slave Check 2
<br />
<input type="checkbox" />Slave Check 3
<br />
<div>
<input type="checkbox" />Slave 2 Check 1
<br />
<input type="checkbox" />Slave 2 Check 2
<br />
<input type="checkbox" />Slave 2 Check 3</div>
</div>
I have improved the javascript code.
$(document).ready(function() {
$('input[type=checkbox]').click(function(){
// if is checked
if($(this).is(':checked')){
$(this).parents('ul').children('li').children('label').find('input').prop('checked', true);
} else {
// uncheck all children
$(this).closest('li').find('input').prop('checked', false);
}
});
});
Children travels a single level down the DOM tree, whereas find goes for multiple levels down looking into descendants.
It was the label - here is the solution:
$('input[type=checkbox]').click(function(){
// if is checked
if($(this).is(':checked')){
$(this).parents('li').children('label').find('input[type=checkbox]').prop('checked', true);
} else {
// uncheck all children
$(this).closest('li').find('input[type=checkbox]').prop('checked', false);
}
});

Show element with attribute

<input type="radio" name="group2" test="one" value="Water"> Water
<input type="radio" name="group2" test="two" value="Beer"> Beer<br>
<div style="display: none" test="one">aaaaaaa</div>
<div style="display: none" test="two">bbbbbbb</div>
<div style="display: none" test="one">ccccccc</div>
I would like: if i click on radio Water with attribute test="one" then should show me all div with attribute test="one". How can i make it with jQuery?
LIVE: http://jsfiddle.net/hRCXV/
Try this:
$("input[type='radio']").click(function() {
var test = $(this).attr("test");
$("div[test]").hide();
$("div[test='" + test + "']").show();
});
Updated fiddle
Please bear in mind that creating your own attributes as you have here is not valid. If you're using HTML5 you should consider using the data attribute to store whatever information you need associated with each element.
Attach a label to the Water text, and a click handler using the attribute selector:
<label for="option1">
<input type="radio" name="group2" id="option1" test="one" value="Water"> Water
</label>
<script>
$('label').click(function() {
// Logic tells me that you want to only show the test elements whose
// attribute matches the selected radio element; Hide the previous ones:
$('div[test]').hide();
// Get test value:
var test = $('#' + $(this).attr('for') ).attr('test');
$('div[test="' + test + '"]').show();
});
</script>
$('input [value="Water"]').click(function() {
$('[test="one"]').show();
});
jsFiddle: http://jsfiddle.net/hRCXV/1/
$("input[type=radio][value=Water]").click(function()
{
$("[test=one]").show();
});​
I belive this is something that you are looking for?
​$(':radio[name="group2"]')​.click(function(e){
var test = $(this).attr('test');
$('div[test]').hide();
$('div[test='+test+']').show();
});​
try this
jQuery(document).ready(function(){
var yourAttributeName = 'test';
var allDivs = jQuery('div['+yourAttributeName+']');
jQuery('input['+yourAttributeName+']').click(function(){
allDivs.hide().filter('[' + yourAttributeName + '=' + jQuery(this).attr(yourAttributeName) + ']').show();
})
//check the init checked
.filter(':checked')
//and fire click event to filter
.click();
});

How to check a radio button with jQuery?

I try to check a radio button with jQuery. Here's my code:
<form>
<div id='type'>
<input type='radio' id='radio_1' name='type' value='1' />
<input type='radio' id='radio_2' name='type' value='2' />
<input type='radio' id='radio_3' name='type' value='3' />
</div>
</form>
And the JavaScript:
jQuery("#radio_1").attr('checked', true);
Doesn't work:
jQuery("input[value='1']").attr('checked', true);
Doesn't work:
jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
Doesn't work:
Do you have another idea? What am I missing?
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
Tip: You may also want to call click() or change() on the radio button afterwards. See comments for more info.
Try this.
In this example, I'm targeting it with its input name and value
$("input[name=background][value='some value']").prop("checked",true);
Good to know: in case of multi-word value, it will work because of apostrophes, too.
Short and easy to read option:
$("#radio_1").is(":checked")
It returns true or false, so you can use it in "if" statement.
One more function prop() that is added in jQuery 1.6, that serves the same purpose.
$("#radio_1").prop("checked", true);
Try this.
To check Radio button using Value use this.
$('input[name=type][value=2]').attr('checked', true);
Or
$('input[name=type][value=2]').attr('checked', 'checked');
Or
$('input[name=type][value=2]').prop('checked', 'checked');
To check Radio button using ID use this.
$('#radio_1').attr('checked','checked');
Or
$('#radio_1').prop('checked','checked');
Use prop() mehtod
Source Link
<p>
<h5>Radio Selection</h5>
<label>
<input type="radio" name="myRadio" value="1"> Option 1
</label>
<label>
<input type="radio" name="myRadio" value="2"> Option 2
</label>
<label>
<input type="radio" name="myRadio" value="3"> Option 3
</label>
</p>
<p>
<button>Check Radio Option 2</button>
</p>
<script>
$(function () {
$("button").click(function () {
$("input:radio[value='2']").prop('checked',true);
});
});
</script>
The $.prop way is better:
$(document).ready(function () {
$("#radio_1").prop('checked', true);
});
and you can test it like the following:
$(document).ready(function () {
$("#radio_1, #radio_2", "#radio_3").change(function () {
if ($("#radio_1").is(":checked")) {
$('#div1').show();
}
else if ($("#radio_2").is(":checked")) {
$('#div2').show();
}
else
$('#div3').show();
});
});
Try This:
$("input[name=type]").val(['1']);
http://jsfiddle.net/nwo706xw/
Surprisingly, the most popular and accepted answer ignores triggering appropriate event despite of the comments. Make sure you invoke .change(), otherwise all the "on change" bindings will ignore this event.
$("#radio_1").prop("checked", true).change();
You have to do
jQuery("#radio_1").attr('checked', 'checked');
That's the HTML attribute
Try this
$(document).ready(function(){
$("input[name='type']:radio").change(function(){
if($(this).val() == '1')
{
// do something
}
else if($(this).val() == '2')
{
// do something
}
else if($(this).val() == '3')
{
// do something
}
});
});
If property name does not work don't forget that id still exists. This answer is for people who wants to target the id here how you do.
$('input[id=element_id][value=element_value]').prop("checked",true);
Because property name does not work for me. Make sure you don't surround id and name with double/single quotations.
Cheers!
We should want to tell it is a radio button.So please try with following code.
$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);
Yes, it worked for me like a way:
$("#radio_1").attr('checked', 'checked');
This answer is thanks to Paul LeBeau in a comment. I thought I'd write it up as a proper answer since there surprisingly wasn't one.
The only thing that worked for me (jQuery 1.12.4, Chrome 86) was:
$(".js-my-radio-button").trigger("click");
This does everything I want – changes which radio button looks selected (both visually and programmatically) and triggers events such as change on the radio button.
Just setting the "checked" attribute as other answers suggest would not change which radio button was selected for me.
Try this with example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>
<script>
$(document).ready(function () {
$('#myForm').on('click', function () {
var value = $("[name=radio]:checked").val();
alert(value);
})
});
</script>
$("input[name=inputname]:radio").click(function() {
if($(this).attr("value")=="yes") {
$(".inputclassname").show();
}
if($(this).attr("value")=="no") {
$(".inputclassname").hide();
}
});
Get value:
$("[name='type'][checked]").attr("value");
Set value:
$(this).attr({"checked":true}).prop({"checked":true});
Radio Button click add attr checked:
$("[name='type']").click(function(){
$("[name='type']").removeAttr("checked");
$(this).attr({"checked":true}).prop({"checked":true});
});
Just in case anyone is trying to achieve this while using jQuery UI, you will also need to refresh the UI checkbox object to reflect the updated value:
$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set
I use this code:
I'm sorry for English.
var $j = jQuery.noConflict();
$j(function() {
// add handler
$j('#radio-1, #radio-2').click(function(){
// find all checked and cancel checked
$j('input:radio:checked').prop('checked', false);
// this radio add cheked
$j(this).prop('checked', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="section">
<legend>Radio buttons</legend>
<label>
<input type="radio" id="radio-1" checked>
Option one is this and that—be sure to include why it's great
</label>
<br>
<label>
<input type="radio" id="radio-2">
Option two can be something else
</label>
</fieldset>
Try this
var isChecked = $("#radio_1")[0].checked;
I've just have a similar problem, a simple solution is to just use:
.click()
Any other solution will work if you refresh radio after calling function.
function rbcitiSelction(e) {
debugger
$('#trpersonalemail').hide();
$('#trcitiemail').show();
}
function rbpersSelction(e) {
var personalEmail = $(e).val();
$('#trpersonalemail').show();
$('#trcitiemail').hide();
}
$(function() {
$("#citiEmail").prop("checked", true)
});
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');
I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.
Example is in here:
$(function () {
$('#CostAnalysis input[type=radio]').click(function () {
var value = $(this).val();
if (value == "Supply & Lay") {
$('#ul-suplay').empty();
$('#ul-suplay').append('<fieldset data-role="controlgroup"> \
http://jsfiddle.net/m7hg2p94/4/
attr accepts two strings.
The correct way is:
jQuery("#radio_1").attr('checked', 'true');
In addition, you can check if the element is checked or not:
if ($('.myCheckbox').attr('checked'))
{
//do others stuff
}
else
{
//do others stuff
}
You can checked for unchecked element:
$('.myCheckbox').attr('checked',true) //Standards way
You can also uncheck this way:
$('.myCheckbox').removeAttr('checked')
You can checked for radio button:
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
I used jquery-1.11.3.js
Basic Enable & disable
Tips 1: (Radio button type common Disable & Enable)
$("input[type=radio]").attr('disabled', false);
$("input[type=radio]").attr('disabled', true);
Tips 2: ( ID selector Using prop() or attr())
$("#paytmradio").prop("checked", true);
$("#sbiradio").prop("checked", false);
jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
jQuery("#sbiradio").attr('checked', false);
Tips 3: ( Class selector Using prop() or arrt())
$(".paytm").prop("checked", true);
$(".sbi").prop("checked", false);
jQuery(".paytm").attr('checked', 'checked'); // or true
jQuery(".sbi").attr('checked', false);
OTHER TIPS
$("#paytmradio").is(":checked") // Checking is checked or not
$(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled
$('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
$("input:checked", "#paytmradio").val() // get the checked value
index.html
<div class="col-md-6">
<label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
<div id="paymenttype" class="form-group" style="padding-top: inherit;">
<label class="radio-inline" class="form-control"><input type="radio" id="paytmradio" class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
<label class="radio-inline" class="form-control"><input type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
</div>
</div>
try this
$("input:checked", "#radioButton").val()
if checked returns True
if not checked returns False
jQuery v1.10.1
Some times above solutions do not work, then you can try below:
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));
Another way you can try is:
jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

jQuery .change() not firing

Just working on some small pages to be elements of a much larger project and am completely confused at my current problem here is my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<STYLE TYPE="text/css">
.questionBlock { font-size: x-large; color: red }
</STYLE>
<script type="text/javascript">
$(document).ready(function() {
alert("sdsd")
$("input[#name='questionType']").change(function(){
alert("dfdfdf");
var selected = $("form input:radio:checked").val();
alert(selected);
})
});
</script>
<form action="">
<input type="radio" name="questionType" value="closed" /> Closed Endeded<br />
<input type="radio" name="questionType" value="matrix" /> Matrix Question<br />
<input type="radio" name="questionType" value="open" /> Open Ended
</form>
<div class="questionBlock" id="closed">lol</div>
<div class="questionBlock" id="open">rol</div>
<div class="questionBlock" id="matrix">bol</div>
But the change event never fires, regardless of browser, I've tried using bind as well but it's driving me up the wall!
jQuery attribute selectors don't need # prefix (like XPath). Change your code like this:
$("input[name='questionType']").change(function(){
Here is a working version.
you need to remove the # fiddle
$(document).ready(function() {
$('input[name="questionType"]').change(function(){
alert("dfdfdf");
var selected = $("form input:radio:checked").val();
alert(selected);
})
});
jQuery does not use "#" in Xpath-style attr selectors anymore. This being the case, your selector does not match anything.

Categories

Resources