How to select first radio as default with jquery or javascript - javascript

I have a code like this.
My main goal is when I click a radio button I show a content.
However,
I would like the first radio to be selected as default and the div content is shown.
However, now in order to show the first content I have to click the radio button.
How can I achieve that?
BTW I am not dependent on Jquery. the whole think can be even written with native Javascript.
$(':radio').change(function (event) {
var id = $(this).data('id');
$('#' + id).addClass('none').siblings().removeClass('none');
});
.none {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='thing' value='valuable' data-id="bank" />
<input type="radio" name='thing' value='valuable' data-id="school" />
<hr />
<div id="bank" class="none">Bank</div>
<div id="school" class="none">School</div>

The simplest way to achieve this is to set the checked attribute in the HTML then trigger the change event on that element when the page loads, like this:
$(':radio').change(function(e) {
var id = $(this).data('id');
$('#' + id).addClass('none').siblings().removeClass('none');
}).filter(':checked').trigger('change');
.none {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='thing' value='valuable' data-id="bank" checked="true" />
<input type="radio" name='thing' value='valuable' data-id="school" />
<hr />
<div id="bank" class="none">Bank</div>
<div id="school" class="none">School</div>
Alternatively, if you didn't want to amend the HTML you can set the first radio to be checked programmatically, like this:
$(':radio').change(function(e) {
var id = $(this).data('id');
$('#' + id).removeClass('none').siblings('div').addClass('none');
}).first().prop('checked', true).trigger('change');
.none {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='thing' value='valuable' data-id="bank" />
<input type="radio" name='thing' value='valuable' data-id="school" />
<hr />
<div id="bank" class="none">Bank</div>
<div id="school" class="none">School</div>

You can set checked to true and then trigger the change event like
$("input[data-id='bank']").prop("checked", true).trigger("change")
Here is snippet
$(':radio').change(function (event) {
var id = $(this).data('id');
$('#' + id).addClass('none').siblings().removeClass('none');
});
$("input[data-id='bank']").prop("checked", true).trigger("change")
.none {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='thing' value='valuable' data-id="bank" />
<input type="radio" name='thing' value='valuable' data-id="school" />
<hr />
<div id="bank" class="none">Bank</div>
<div id="school" class="none">School</div>

This should do the trick:
// Get all radios, then simply emulate a click on the first one
var radios = document.getElementsByTagName('input');
radios[0].click();

Related

how to correct check checkbox and display if is checked

i use this code to show some text (Checked) when click on 1 or more checkboxes.
I use the on because the checkboxes are dynamically created.
It seems that only IE Edge can not deal with it. I have to click twice on a checkbox to show the Checked text. In all other browsers it works immediately.
Really don't know what is wrong with the code
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons" style="display:none">Checked</div>
<script>
$(document).on('click','.rafcheckbox',function() {
var $checkboxes = $('.rafcheckbox').change(function() {
var anyChecked = $checkboxes.filter(':checked').length != 0;
$(".cb-buttons").toggle(anyChecked);
});
});
</script>
Fiddle: https://jsfiddle.net/g5tp4kjm/
Since you already have the delegate for the elements, just change it to a change event handler.
Inside that logic, toggle the hide class, but force it to have the hide class if no elements are checked.
$(document).on('change','.rafcheckbox',function() {
$('.cb-buttons').toggleClass('hide', $('.rafcheckbox:checked').length < 1);
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons hide">Checked</div>
Lets try it another way.
$(document).on('click','.rafcheckbox',function() {
if($('.rafcheckbox').is(':checked'))
{
//do whatever you want
}
else
{
//do the opposite
}
});

add highlight class to the label of a checked check box via a button

I have checked all over stack overflow, but they're not exactly what I need.
I have checkboxes with associated labels
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p><input type="button" id='bt' value="Record" /></p>
There is also a button, when the button is clicked, if the checkbox is checked, the label associated with it has a highlight class added to the label. I already have the highlight class written I am just having trouble applying it using the addClass method.
I have:
$(':checkbox:checked').addClass('highlight');
but it does nothing
Let's say this is your HTML:
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p>
<button id="btnSubmit">Click Me!</button>
</p>
and this is your CSS class:
.highlight {
background-color: yellow;
}
One thing you could do is loop through each checked checkbox and just apply the class using the label[for=*] property:
$('#btnSubmit').click(function() {
$('input:checked').each(function () {
$("label[for='" + $(this).attr('id') + "']").addClass("highlight");
});
});
However, using the above method, you're not allowing a way to remove the highlight class should you uncheck a box and hit Submit again. I would prefer the below method... which loops through ALL checkboxes, and tests them to determine if they're checked or not:
$('#btnSubmit').click(function() {
$('input[type=checkbox]').each(function () {
if (this.checked) {
$("label[for='" + $(this).attr('id') + "']").addClass("highlight");
} else {
$("label[for='" + $(this).attr('id') + "']").removeClass("highlight");
}
});
});
Try this Fiddle
I'm trying to find a way to just reference the label of all checked checkboxes in one line of code. Because if you could do that, you can just do away with the looping and the if statements. I'll keep researching, and if I find it, I'll edit my post accordingly.
Update: Okay, I think I understand what you need. See updated example.
The trick is knowing how to find the label and checkbox associated with the button. Since the buttons were not included in the question code, I had to guess. If the button is elsewhere, you can experiment using these jQuery traversing methods.
$(document).ready(function(){
$('#mybutt').click(function(){
var chkboxes = $('input[type=checkbox]');
$(chkboxes).each(function(){
if ( $(this).is(':checked') ){
$(this).parent().find('label').addClass('highlight');
}else{
$(this).parent().find('label').removeClass('highlight');
}
});
});
}); //END document.ready
.highlight{background:red;color:yellow;padding:2px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label>
<p>
<button id="mybutt">Go</button>
I guess, what you are trying to do is to change a class, after the value of your checkbox has changed, easiest way to do this is using the onChange event, you can also bind the event with jQuery using $('#your_checkbox').on('change', function(){})
$('[type="checkbox"]').on('change', function() {
if (!$(this).attr('checked')) {
$(this).attr('checked', 'checked');
$(this).parent().addClass('checked');
} else if ($(this).attr('checked') === 'checked') {
$(this).removeAttr('checked', '');
$(this).parent().removeClass('checked');
}
});
$('#btnSubmit').on('click', function() {
var inputs = $(this).parent().parent().find('[type="checkbox"]')
inputs.each(function(){
if ($(this).attr('checked') === 'checked') {
$(this).parent().addClass('iam-checked');
}
else {
$(this).parent().removeClass('iam-checked');
}
});
});
.checked {
border-bottom: 1px solid green;
}
.iam-checked {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p>
<button id="btnSubmit">Click Me!</button>
</p>
This is a little late, but I was surprised that no one mentioned the next method. You are trying to style the label after the checkbox, not the checkbox itself. In other words, the label is the next sibling of the checkbox.
I think this is the most jQuery way to solve this so wanted to add my two cents.
$("#bt").on("click", function() {
$(":checked").each(function() {
$(this).next().addClass("highlight");
});
});
.highlight { background: gold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p><input type="button" id='bt' value="Record" /></p>

Change submit button text based on radio-button value

How to change submit button text based on which radio-button is active?
Here is my code, but it does not work. It changes text only once.
I have two radio-buttons:
<input type="radio" name="build-team" class="choose" value="build" /> Yes
<input type="radio" name="build-team" class="choose" value="show" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>
And I have script:
$(document).on('click', '.choose', function() {
var target = $('.show-result');
if ($(this).attr('checked') == 'checked') {
target.html(target.data('chooseyes'));
}
else {
target.html(target.data('chooseno'));
}
})
JSFiddle example
$(document).on('click', '.choose', function() {
var target = $('.show-result');
target.html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="build-team" class="choose" value="Yes" /> Yes
<input type="radio" name="build-team" class="choose" value="No" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>
$('.opt').click(function(){
$('#button').html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="opt" name="opt" type="radio" value="Yes" checked="checked">Yes
<input class="opt" name="opt" type="radio" value="No">No
<button id="button" type="submit">Yes</button>
This is the easiest answer, no added attributes, only clean HTML + jQuery, it is also important to realize that there must always be a radio selected/checked by default, if not, you would have to validate the field and validating a radio is not cool haha :) have a nice day!

How to toggle div visibility using radio buttons?

I'm working on a project in which I have to toggle the visibility of a <div>.
I've got the following code:
<input type="radio" name="type" value="1"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
I would like to togle the business-fields div. So, if none of the radio buttons, or the 'personal' radio button is selected: The div should be hidden. If the 'business' radio button is selected, I want it to show.
Currently, I am using this code:
$("input[name='type']").click(function() {
var status = $(this).val();
if (status == 2) {
$(".business-fields").show();
} else {
$(".business-fields").hide();
}
});
However, I was wondering if I can do this using the .toggle() function.
I usually tend not to use JS if possible, therefore here comes a HTML+CSS way approach.
.bussines-type .business-fields {
display: none;
}
.bussines-type input[value="2"]:checked ~ .business-fields {
display: block;
}
<div class="bussines-type">
<input id="bt1" type="radio" name="type" value="1">
<label for="bt1"> Personal</label>
<input id="bt2" type="radio" name="type" value="2">
<label for="bt2"> Business</label>
<div class="business-fields">
<input type="text" placeholder="Company name" name="company-name">
<input type="text" placeholder="Vat number" name="vat-number">
</div>
</div>
The ~ stands for any siblings, that are after the element we defined before the ~ sign.
I'd suggest using the change event, and supplying a Boolean switch to the toggle() method, which will show the jQuery collection of elements if the switch evaluates to true, and hide them if it evaluates to false:
// select the relevant <input> elements, and using on() to bind a change event-handler:
$('input[name="type"]').on('change', function() {
// this, in the anonymous function, refers to the changed-<input>:
// select the element(s) you want to show/hide:
$('.business-fields')
// pass a Boolean to the method, if the numeric-value of the changed-<input>
// is exactly equal to 2 and that <input> is checked, the .business-fields
// will be shown:
.toggle(+this.value === 2 && this.checked);
// trigger the change event, to show/hide the .business-fields element(s) on
// page-load:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="1">Personal</label>
<label>
<input type="radio" name="type" value="2">Business</label>
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Incidentally, note I've also wrapped the associated text, to indicate the radio-button's purpose, inside of a <label> element to directly associate that text with the <input>, so clicking the text checks the <input> automatically.
References:
change().
on().
toggle().
JS Fiddle
Try this one
<input type="radio" name="type" value="1" checked ="true"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
.business-fields{
display: none;
}
$("input[name='type']").change(function() {
$(".business-fields").toggle();
});
You may use like this:
$("input[name='type']").change(function() {
var status = $(this).val();
if (status != 2) {
$(".business-fields").hide();
} else {
$(".business-fields").show();
}
});
.show and .hide are pretty slow.
https://twitter.com/paul_irish/status/564443848613847040
It's better to toggle a css class on and off with javascript. Set the css of the class to {visibility: hidden} or {display: none}
use the below code
<script>
$(function(){
$(":radio[value=1]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==true)
$('.business-fields').toggle();
});
$(":radio[value=2]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==false)
$('.business-fields').toggle();
});
});
</script>
AND HTML is-
<input name="type" type="radio" value="1" >Personal
<input type="radio" name="type" value="2" checked="checked"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Possibly a more elegant solution, It's a bit more readable in my opinion, and and as #Ollie_W points out it might be more performant that toggle (show/hide).
$('input[name="type"]').on('change', function(event) {
var radioButton = $(event.currentTarget),
isBusiness = radioButton.val() === 'business' && radioButton.prop('checked');
$('.business-fields').toggleClass('hidden', !isBusiness);
}).change();
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="personal">Personal</label>
<label>
<input type="radio" name="type" value="business">Business</label>
<div class="business-fields hidden">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>

Get Elements of Certain Type within a Div with jQuery

I have an HTML page that is dynamically generated. A rough version of the HTML looks like this:
<div id="brotherDiv">
<input type="radio" name="myOtherGroup" value="A" />
<input type="radio" name="myOtherGroup" value="B" />
</div>
<div id="myDiv">
<input type="radio" name="myGroup" value="1"></input>
<input type="text" id="myText" name="myText"></input><br />
<input type="radio" name="myGroup" value="2"></input>
<input type="text" id="myText2" name="myText2"></input><br />
<input type="radio" name="myGroup" value="3"></input><br />
<input type="radio" name="myGroup" value="4"></input>
</div>
<div id="sisterDiv"></div>
I am trying to
Get all of the radio buttons in myDiv
Get the index of the selected radio button in the result of #1.
Is there a way to do this type of query in jQuery? If so, how? Currently, I have
var rbs = $("input[name='myGroup']");
I feel like I'm close.
I'd suggest:
var rbs = $("#myDiv input[name='myGroup']:checked"),
index = rbs.index(),
// amongst its siblings, or:
inputIndex = rbs.index('input[name="myGroup"]');
// amongst other input elements of the same group
References:
CSS:
Attribute presence and value selectors.
:checked pseudo-class.
jQuery:
index().
var rbs = $('#myDiv input[type="radio"]'); // Get radio buttons
var result = $('#myDiv input[type="radio"]:checked') // Get checked radio buttons
All radio buttons in #myDiv:
var rbs = $('#myDiv :radio');
Checked:
var checkedIndex = rbs.filter(':checked').index(':radio');
Answer to #1:
var radios = $('#myDiv input[type="radio"][name="myGroup"]');
Answer to #2:
var checkedRadios = radios.index( $('#myDiv input[type="radio"][name="myGroup"]:checked') );
Try
var rbs = $("#myDiv [type=radio]") // #1
, rbschecked = null; // #2 , pending change event
rbs.change(function(e) {
rbschecked = rbs.index(e.target) // #2
})
var rbs = $("#myDiv [type=radio]")
, rbschecked = null;
rbs.change(function(e) {
rbschecked = rbs.index(e.target);
e.target.dataset.i = rbschecked;
console.log(rbschecked)
})
#myDiv input:checked:after {
position : relative;
content : attr(data-i);
left : 12px;
top : -2px;
color : blue;
font-family : arial;
font-style : italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="brotherDiv">
<input type="radio" name="myOtherGroup" value="A" />
<input type="radio" name="myOtherGroup" value="B" />
</div>
<div id="myDiv">
<input type="radio" name="myGroup" value="1"></input>
<input type="text" id="myText" name="myText"></input><br />
<input type="radio" name="myGroup" value="2"></input>
<input type="text" id="myText2" name="myText2"></input><br />
<input type="radio" name="myGroup" value="3"></input><br />
<input type="radio" name="myGroup" value="4"></input>
</div>
<div id="sisterDiv"></div>

Categories

Resources