jquery radio button click and change function not working - javascript

I want to hide and show div according to radio buttons value.
HTML code is,
<div id="share_to_others">
<input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type">
<input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type">
<input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type">
</div>
And jquery code that i tried is,
$("#share_to_others input[name='fx_sharepl_type']").click(function () {
alert("test");
});
$("#share_to_others input[name='fx_sharepl_type']").change(function () {
alert("test");
});
$("#fx_sharepl_type").change(function () {
alert("asdas");
});
$("input[name=fx_sharepl_type]:radio").change(function () {
alert("click fired");
});
$(document).on('change', 'input:radio[name=fx_sharepl_type"]', function (event) {
alert("click fired");
});
Many of them from jsfiddle working demo, But not working for me, i dont know why.
Am i doing anything wrong?

You have to give unique id to each radio button then after do like this way.
$("#r1, #r2, #r3").change(function () {

$(function() { // DOM loaded event handler
var show_duration = 0;
var content_33 = $("#content_33");
var content_22 = $("#content_22");
var content_11 = $("#content_11");
var bloc_radio_share = $("#share_to_others");
// Take an html element in parameter and show it
function show_content(content_id) {
content_id.show(show_duration);
}
// Take an html element in parameter and hide it
function hide_content(content_id) {
content_id.hide(0);
}
hide_content(content_22);
hide_content(content_11);
bloc_radio_share.change(function() {
var radio_checked_val = $('input[name=fx_sharepl_type]:checked', '#share_to_others').val();
if (radio_checked_val == 33) {
hide_content(content_22);
hide_content(content_11);
show_content(content_33);
}
else if (radio_checked_val == 22) {
hide_content(content_33);
hide_content(content_11);
show_content(content_22);
}
else { // case content == 11
hide_content(content_33);
hide_content(content_22);
show_content(content_11);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="share_to_others">
<label>
<input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type" checked />
33
</label>
<label>
<input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type" />
22
</label>
<label>
<input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type" />
11
</label>
</div>
<div id="content_33">
This div is displayed because of click on radio button 33
</div>
<div id="content_22">
Radio button 22 has been clicked so I appear
</div>
<div id="content_11">
If you click on radio button 11 you'll see me, like now
</div>
Here is an example of algorithm that fits your need. Logic may be not the best or the fastest but that is a begin.

Your code wors but you forgot to include a JQuery source version located to the left side of the JSFiddle window.
Selecting any version of JQuery will make your code work.

Related

Radio button is showing div on selection but not hiding after selecting a different radio button

I have three divs I want to show based on a radio selection. I've written the below script, but the problem I've run into is the div doesn't hide after a different radio button is selected. I'm using ucalc so I can't change the class names or ids of the divs or the radio buttons so have to work with that.
Note, the radio button is automatically selected when the form loads so the first div needs to be showing initially.
Code below:
$(document).ready(function(){
// First Div/Radio Button
$('#input_radio-30-0-des').on('change', function(){
var a = $(this).prop('checked');
if(a) {
$("#grid-40-42").show();
} else {
$("#grid-40-42").hide();
}
});
// Second Div/Radio Button
$("#grid-44-46").hide();
$('#input_radio-30-1-des').on('change', function(){
var a = $(this).prop('checked');
if(a) {
$("#grid-44-46").show();
} else {
$("#grid-44-46").hide();
}
});
// Third Div/Radio Button
$("#grid-46-48").hide();
$('#input_radio-30-2-des').on('change', function(){
var a = $(this).prop('checked');
if(a) {
$("#grid-46-48").show();
} else {
$("#grid-46-48").hide();
}
});
});
I'm not very familiar with writing javascript (you can probably tell!) so an explanation for 'dummies' would be appreciated!
Thank you for your help!
You need to hide 2nd & 3rd div by CSS and when user change other button then find ID so according to ID show that div and rest div will hide as below snippet.
$(document).ready(function(){
$('#input_radio-30-0-des, #input_radio-30-1-des, #input_radio-30-2-des').on('change', function(){
var getid = $(this).attr('id');
if (getid=='input_radio-30-0-des') {
$('#grid-44-46, #grid-46-48').hide()//2nd and 3rd div hide
$("#grid-40-42").show();
}
if (getid=='input_radio-30-1-des') {
$('#grid-40-42, #grid-46-48').hide()//1st and 3rd div hide
$("#grid-44-46").show();
}
if (getid=='input_radio-30-2-des') {
$('#grid-40-42, #grid-44-46').hide()//1st and 2rd div hide
$("#grid-46-48").show();
}
})
});
#grid-44-46, #grid-46-48{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" name="div-show-hide" id="input_radio-30-0-des" checked> Button One</label>
<label><input type="radio" name="div-show-hide" id="input_radio-30-1-des"> Button Two</label>
<label><input type="radio" name="div-show-hide" id="input_radio-30-2-des"> Button Three</label>
<div id="grid-40-42"><h2>Show - Div One</h2></div>
<div id="grid-44-46"><h2>Show - Div Two</h2></div>
<div id="grid-46-48"><h2>Show - Div Three</h2></div>
Use wild card to hide all <div> which id start with grid- on radio change.
$("[id^=grid-]").hide();
$('#input_radio-30-0-des').on('change', function() {
$("[id^=grid-]").hide();
var a = $(this).prop('checked');
if (a) {
$("#grid-40-42").show();
} else {
$("#grid-40-42").hide();
}
});
$('#input_radio-30-1-des').on('change', function() {
$("[id^=grid-]").hide();
var a = $(this).prop('checked');
if (a) {
$("#grid-44-46").show();
} else {
$("#grid-44-46").hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='radio' id='input_radio-30-0-des' name="group1" />
<div id='grid-40-42'>grid-40-42</div>
<input type='radio' id='input_radio-30-1-des' name="group1" />
<div id='grid-44-46'>grid-40-46</div>
Note
No need multi-pal $(document).ready(function(){ .
Id must be unique.
I'm using a Javascript object to match each Radio button with it's targeted div.
I assume they are hidden by default. Just having fun and giving an alternative to multiple checks! A cleaner code also where you could easily setup all those confusing names...
$( document ).ready(function() {
let matches = {
"input_radio-30-0-des": 'grid-40-42',
"input_radio-30-1-des": 'grid-44-46',
"input_radio-30-2-des": 'grid-46-48'
};
$(":input[name='FM']").on("change", function () {
var target= matches[$(this).attr('id')];
$('#' +target).toggle($(this).checked);
$("[id^=grid-]").not('#' +target).hide();
})
});
div[id*='grid-'] { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="FM" id="input_radio-30-0-des" value="0"/>
<label for="input_radio-30-0-des">0</label>
<input type="radio" name="FM" id="input_radio-30-1-des" value="1"/>
<label for="input_radio-30-1-des">1</label>
<input type="radio" name="FM" id="input_radio-30-2-des" value="2"/>
<label for="input_radio-30-2-des">2</label>
<div id="grid-40-42">40-42</div>
<div id="grid-44-46">44-46</div>
<div id="grid-46-48">46-48</div>

Checkbox Hidden Div Unchecked

I have a checkbox hidden div with text field. If checkbox is checked this text field will showed, but if checkbox unchecked text field not show. This Code :
<script type="text/javascript">
$(function () {
$("input[name='checkbox1']").click(function () {
if ($("#checkyes1").is(":checked")) {
$("#dvcheckbox1").show('lainnya');
} else {
$("#dvcheckbox1").hide('lainnya');
}
});
});
</script>
<div style="margin-left: 29%; margin-top: -2%;">
<label for="checkyes1">
<input type="checkbox" id="checkyes1" name="checkbox1" value="lainnya" />
Lainnya
</label>
<div id="dvcheckbox1" style="display: none;">
<?php echo $form->textField($model,'lainnya'); ?>
</div>
</div>
But, How this checkbox is checked if there something value on textfield? and text field shown. Because in form Update, value was show but checkbox is checked. I want checkbox is checked
For example Like this:
Click to show example
Instead use with change event with .toggle(boolean) method:
// on page load check of the div contains any text
$("#dvcheckbox1").toggle(function(){
var $v = $(this).find('input').val();
$("input[name='checkbox1']").prop('checked', $v.trim().length !== 0)
return $v.trim().length !== 0;
});
$("input[name='checkbox1']").change(function () {
$("#dvcheckbox1").toggle(this.checked);
});
There are a few things here:
1 - Better if you use document ready, because it waits until all the elements are loaded.
2 - You should hide the element$("#dvcheckbox1").hide('lainnya') when the page is loaded.
3 - A listener in the input:text is a good idea. It enables the checkbox if the textbox is empty.
Please, have a look at the next piece of code:
<div>
<label for="checkyes1">
<input type="checkbox" id="checkyes1" name="checkbox1" value="lainnya" />
Lainnya
</label>
<div id="dvcheckbox1">
<label for="myValuye"/>
<input type="text" id="myValue" name="myValue" value=""/>
</div>
</div>
<script>
$(document).ready(function() {
$("input[name='checkbox1']").click(function () {
// Always use some logs to check what line are you reaching.
console.log("Clicked checkbox!!!");
if ($("#checkyes1").is(":checked")) {
$("#dvcheckbox1").show('lainnya');
} else {
console.log("Value: " + $("#myValue").val());
$("#dvcheckbox1").hide("lainnya");
}
});
$("#myValue").bind("change paste keyup", function() {
if ($(this).val() == "") {
$("#checkyes1").removeAttr("disabled");
} else {
$("#checkyes1").attr("disabled", true);
}
});
// First of all we hide the #dvcheckbox1
$("#dvcheckbox1").hide('lainnya');
})

Jquery add and remove disable attribute

I'm having some checkboxes and text inputs. The Text inputs are disabled when the pages loads. If a checkbox is checked, the corresponding input should be fillable. Here's my current code
For some reason I can't seem to get it right, I'm pretty new to JS and Jquery.
When I click the checkboxes, nothing happens, and when I load the page I get 6 times the text "false"
var c1 = $('#check1');
var c2 = $('#check2');
var c3 = $('#check3');
var f1 = $('#field1');
var f2 = $('#field2');
var f3 = $('#field3');
$(function() {
enable_cb(c1, f1);
enable_cb(c2, f2);
enable_cb(c3, f3);
c1.click(enable_cb(c1, f1));
c2.click(enable_cb(c2, f2));
c3.click(enable_cb(c3, f3));
});
function enable_cb(checkbox, field) {
if (checkbox.checked) {
console.log('if');
field.removeAttr("disabled");
} else {
console.log('else');
field.attr("disabled", true);
}
}
Here's a piece of html, the other parts look the same as this one:
<div class="form-group" >
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect customcheckbox" for="check1">
{{ Form::checkbox('check', 1, null, ['class' => 'mdl-checkbox__input', 'id' => 'check1']) }}
<span class="mdl-checkbox__label">test</span>
</label>
</div>
<div class="form-group" >
<label for="field1">test<br></label>
<select id="field1" name="field1" disabled class="searchselect searchselectstyle">
</select>
#if ($errors->has('field1'))
<span class="help-block">
<strong>{{ $errors->first('field1') }}</strong>
</span>
#endif
</div>
You have several issues.
You should use the change event when dealing with checkboxes so that people who navigate with the keyboard can use them.
You should provide an anonymous function to the event handler. You current code is immediately executing the enable_cb() function and then ignoring any further events.
The checkbox parameter passed to the function is a jQuery object which has no checked property. You should use is(':checked') instead.
You should use prop() over attr() and removeAttr() where possible.
Try this:
$(function() {
enable_cb(c1, f1);
enable_cb(c2, f2);
enable_cb(c3, f3);
c1.change(function() {
enable_cb(c1, f1)
});
c2.change(function() {
enable_cb(c2, f2)
});
c3.change(function() {
enable_cb(c3, f3)
});
});
function enable_cb(checkbox, field) {
if (checkbox.is(':checked')) {
console.log('if');
field.prop("disabled", false);
} else {
console.log('else');
field.prop("disabled", true);
}
}
Working example
That said, you should really look to DRY up your code to reduce repetition. Exactly how you do this depends on your HTML structure, but here's an example.
<div class="checkbox-group">
<input type="checkbox" id="check" />
<input type="text" id="subcomplex"/>
</div>
<div class="checkbox-group">
<input type="checkbox" id="yearlymanagermaintainancedayscheck" />
<input type="text" id="yearlymanagermaintainancedays" />
</div>
<div class="checkbox-group">
<input type="checkbox" id="yearlysuppliermaintainancedayscheck" />
<input type="text" id="yearlysuppliermaintainancedays" />
</div>
$('.checkbox-group :checkbox').change(function() {
$(this).siblings('input').prop('disabled', !this.checked);
}).change();
Working example
Note how much simpler the code is for the latter version, and how the JS will require no updates or maintenance no matter how many input elements you add to the HTML.
If you need to toggle a property using jQuery, you can use the prop() function, which you could use to toggle the disabled property :
$(yourElement).prop('disabled',!checkbox.checked);
which in your case might look something like :
function enable_cb(checkbox, field) {
$(field).prop('disabled',!checkbox.checked);
}

Show hide text box from a dynamic element jQuery c#

Below is my code, I am trying to hide and show dynamic elements. The problem I am having is, I only want my hidden div to only show one at a time if only I check "Other". However, the code below will show the hidden div for all number of #dynamicRows I have. so it works for initial 1st #dynamicRow added, the problem is when I have two or more #dynamicRows
$('#dynamicRow').on('click', 'input[id^=race]', function () {
if ($(this).is(":checked")) {
if ($(this).val() == "Other") {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
}
else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
}
});
Below are dynamic rows, for help purposes i am showing the html code, however, it doesn't exist on the screen, a user will click "ADD" to generate the code below. I have no problem in generating dynamic row and it is not why I am posting. note the name in my radio button is generated by c# and everything works. Again the problem is not how to create a dynamic row, it is nicely taken care of in C#.
Dynamic row one works with the above jQuery:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Dynamic row two doesn't work with the above jquery and it takes the above form events as its own, so if i check the radio button in row 2, the 1st dynamic row responds to that event and vice versa:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Working Example
id should be unique in same document, replace the duplicate ones by a class :
<input type="radio" value="No" class="race" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" class="race" name="Person[hhhhhh].race"> Other:
Also add class and not id to the dynamic rows generated by your C# code :
<div class="dynamicRow">
Then in your js use this class :
$(".cssclass").hide();
$('.dynamicRow').on('click', '.race', function () {
if ($(this).val() == "Other") {
$(this).next(".cssclass").show();
} else {
$(this).nextAll(".cssclass").hide();
}
});
Hope this helps.
Try this:
$('body').on('click', '#dynamicRow', function () {
if ($(this).find('[value=Other]').is(":checked")) {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
} else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
});
He is a working example of what you wanted. I am generating the required with js only.
Few Points to mention
you add the event listener to the parent of the dynamic generated content.
Avoid use of IDs if they are not going to be unique and prefer classes and pseudo selectors if required
var counter = 0;
function addNewEntry(){
++counter;
var str = '<div class="dynamicRow"><input type="radio" value="No" id="race[]" name="Person[hh'+counter+'].race"> No:<input type="radio" value="Other" id="race[]" name="Person[hh'+counter+'].race"> Other:<div id="iamhidden" class="cssclass"> I appear one at a time, when other radio button is checked</div> </div>';
$('#dynamicRowContainer').append(str);
$("#dynamicRowContainer .dynamicRow:last-child .cssclass").hide()
}
$('#dynamicRowContainer').on('change', '.dynamicRow > input', function () {
if(this.value=="Other"){
$(this).siblings('.cssclass').show();
}else{
$(this).siblings('.cssclass').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="addNewEntry()">Add New Entry</button>
<div id="dynamicRowContainer">
</div>

Get output of .change() function in .click() function

I have two radio buttons which both have values. When one is selected, and a button/link is clicked, the value of the selected radio button needs to be outputted to a text box.
Here is my HTML:
<form class="discount-choice" method="post" action="#">
<ul>
<li>
<input type="radio" value="1" name="discount" id="1-month" class="discount-checkbox" />
<label for="1-month">1 Month - no discount</label>
</li>
<li>
<input type="radio" value="0.95" name="discount" id="4-months" class="discount-checkbox" />
<label for="4-months">4 months - 5% discount</label>
</li>
</ul>
Get Result
<input type="text" class="result" />
</form>
and my JavaScript (jQuery):
var discount = $(".discount-checkbox").on("click", function () {
return this.value;
});
$(".get-result").on("click", function() {
$(".result").attr("value", discount);
});
When I click the button (after having selected a radio button), I just get [object Object] in the text box.
I'm not sure of the syntax for setting a variable to be a jQuery function so this is likely where I am going wrong. If anyone could give me some guidance that would be awesome.
Thank you for any help :)
discount is set to the jQuery object returned by $(".discount-checkbox"). You need to bind a click handler that updates a variable:
var discount = 0;
$(".discount-checkbox").on("click", function () {
discount = this.value;
});
Use this:
$(".get-result").on("click", function(e) {
e.preventDefault();
$(".result").val( $('.discount-checkbox:checked').val() );
});
You do not need the click handler on the checkbox as #billyonecan has mentioned in the comments.
And ... if you really need to attach an event handler to the checkboxes, that would be a change event handler instead of click.
Try This Code:
var discount;
$(".discount-checkbox").on("click", function () {
discount= this.value;
});
$(".get-result").on("click", function() {
$(".result").attr("value", discount);
});
no need of discount-checkbox click event
$(".get-result").on("click", function() {
var discount = $(".discount-checkbox:checked").val();
$(".result").val(discount);
});

Categories

Resources