Toggle checked status on input inconstant in jQuery function - javascript

I fear I'm missing something painfully obvious, but this jquery function appears to be working inconsistently.
HTML:
<label id="income_this_tax_year">
<div class="left">
<p>Have you had Self-Employment, Sole Trade or CIS income during the tax year?</p>
</div>
<div class="right">
<input type="radio" name="income_this_tax_year" value="yes" />
<input type="radio" name="income_this_tax_year" value="no" />
<button type="button" data-value="yes" class="button">Yes</button>
<button type="button" data-value="no" class="button">No</button>
</div>
<div class="float-clear"></div>
</label>
jQuery:
$(document).ready(function(){
$('button').on('click', function(e) {
e.preventDefault();
var option = $(this).parent('.right').parent('label').attr('id');
var value = $(this).data('value');
$('#'+option).find('input[type=radio]').prop('checked', false);
$('#'+option+' input[value='+value+']').prop('checked', true);
var income_this_tax_year = $('input[name=income_this_tax_year]:checked').val();
console.log(income_this_tax_year);
})
});
jsfiddle
The buttons are to replace the interaction of the radio inputs. On the first initial clicks of each button it works as intended, but any consequent click returns undefined (and removes the checked status from the inputs entirely).
What makes this particularly tricky to debug is that when I inspect the DOM everything happens as expected. The radios checked status/attr does change, but jquery still reports it as undefined and visually the radio button isn't checked (you can see this if you inspect the result on jsfiddle and watch the inputs as you click the buttons).
Any thoughts?

You can use prop instead:
$(document).ready(function() {
$('button').on('click', function(e) {
e.preventDefault();
var option = $(this).parent('.right').parent('label').attr('id');
var value = $(this).data('value');
//$('#' + option).find('input[type=radio]').removeAttr('checked');
//replace here attr with prop
$('#' + option + ' input[value=' + value + ']').prop('checked', true);
var income_this_tax_year = $('input[name=income_this_tax_year]:checked').val();
console.log(income_this_tax_year);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="income_this_tax_year">
<div class="left">
<p>Have you had Self-Employment, Sole Trade or CIS income during the tax year?</p>
</div>
<div class="right">
<input type="radio" name="income_this_tax_year" value="yes" />
<input type="radio" name="income_this_tax_year" value="no" />
<button type="button" data-value="yes" class="button">Yes</button>
<button type="button" data-value="no" class="button">No</button>
</div>
<div class="float-clear"></div>
</label>

Use prop() instead of attr() and removeAttr() to change the checked status of radio buttons.
Check .prop('checked',false) or .removeAttr('checked')? for more info.
Demo
$(document).ready(function() {
$('button').on('click', function(e) {
e.preventDefault();
var option = $(this).parent('.right').parent('label').attr('id');
var value = $(this).data('value');
$('#' + option + ' input[value=' + value + ']').prop('checked', true);
var income_this_tax_year = $('input[name=income_this_tax_year]:checked').val();
console.log(income_this_tax_year);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<label id="income_this_tax_year">
<div class="left">
<p>Have you had Self-Employment, Sole Trade or CIS income during the tax year?</p>
</div>
<div class="right">
<input type="radio" name="income_this_tax_year" value="yes" />
<input type="radio" name="income_this_tax_year" value="no" />
<button type="button" data-value="yes" class="button">Yes</button>
<button type="button" data-value="no" class="button">No</button>
</div>
<div class="float-clear"></div>
</label>

Related

JS/jQuery for assigning values

I am trying to achieve this:
Currently value has been set on 2 radio buttons.
Once one of the button is selected, the value(attribute) of that button should be assigned to the value of the div with an id.
I am not sure where I am going wrong. Below is the code snippet.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
if (init_font_one == 'checked') {
init_id_value.val(init_font_one.val());
}
if (init_font_two == 'checked') {
init_id_value.val(init_font_two.val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" value="abc"> Testing
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
You have to use on('change' to update the value of div when radio button is click. And use attr of jQuery to update the value of particular element.
Try this.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
init_font_one.change(function() {
init_id_value.attr("value",init_font_one.val());
console.log(init_id_value.attr("value"));
});
init_font_two.on('change',function() {
init_id_value.attr("value",init_font_two.val());
console.log(init_id_value.attr("value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
There is few problems with your code:
<div> can't have value property.
Your code executes on page load and not when some event was triggered.
init_font_one == 'checked' compares jQuery object with string.
input[id="init-one-name"] can be replaced with #init-one-name
Your labels are not linked with inputs.
$('.radios').change(function() {
$("#test").val($('.radios:checked').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<!-- uncomment below -->
<!--<input type="hidden" id="test" value="abc"/>-->
<input type="text" id="test" value="abc" /> Testing
</div>
<input class="radios" id="init-one-name" type="radio" name="init-one-name" value="abcd"><label for="init-one-name">Test1</label>
<input class="radios" id="init-two-name" type="radio" name="init-one-name" value="xyz"><label for="init-two-name">Test2</label>
You should use jQuery change event to detect the change in the radio buttons and assign the value of checked radio button to the div with id="test"
var init_id_value = $("#test");
$('input[id="init-one-name"]').on('change', function() {
init_id_value.text($(this).val());
});
$('input[id="init-two-name"]').on('change', function() {
init_id_value.text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
try this
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue =
$("input[name='init-one-name']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});
I do not understand what you are trying to do, but try this:
$( "input[name='init-one-name']" ).change(function(){
$('#test').val('New Value: ' + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test">Testing
</textarea><BR>
<input type="radio" name="init-one-name" value="abcd"><label>Op 1</label>
<input type="radio" name="init-one-name" value="xyz"><label>OP 2</label>
There is no value on a div, but you can change the text content or you can assing a "virtual value" to the div using .data()
Check the snippet
$(function(){ // On jquery initialize
var idtest = $('#test'); // the target Div
$('input[type="radio"]').on('change',function(){ // change event for the two radio buttons
/*** Method 1 : Using data attribute to assing a value ***/
idtest.data('value',$(this).val()); // Value of the selected radio
/*** Method 2 : Add the value of the selected radio to the text inside the div ***/
idtest.text( $(this).val() ) // Value of the selected radio
//retrieve the setted data value
console.log( idtest.data('value') );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
Refer to the fixed code below.
Added a listener to detect action performed over the radio buttons and changed method to check if radio is checked or not.
let ele = document.getElementById('init-one-div');
ele.addEventListener('click', function(e) {
if ("INPUT" === e.target.nodeName)
checkAndAssign();
});
function checkAndAssign() {
var init_font_one = $('#init-one-name'),
init_font_two = $('#init-two-name'),
init_id_value = $("#test");
if (init_font_one.is(':checked')) {
init_id_value.val(init_font_one.val());
}
if (init_font_two.is(':checked')) {
init_id_value.val(init_font_two.val());
}
//REMOVE below line if you want to remove the line printing the result
init_id_value.html(' Testing [ ' + init_id_value.val() + ' ] ');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<div id="init-one-div">
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"> <label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"> <label>Test2</label>
</div>

How to find which radio Button is selected after a div

How can I find which radio button is selected after a precise div?
This is an Example:
<div class="largelines">
<p class="line">OPTION 1</p>
<div class="delete">
</div>
<fieldset>
<input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
<input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
</fieldset>
</div>
Here, when I click on the class .delete I would like to check (with jQuery) if one of the radio button below (inside the fieldset) has been selected. Do you have any hints?
Thanks in advance.
If there is just bunch of radio button you would like to check are checked or not you can do something like this
$(document).ready(function(){
$('.delete').on('click', function(){
$(document).find('input[type=radio]').each(function(){
if($(this).get(0).checked){
//do something
}
});
});
});
Ofc in line 3 you can specify more about the radio button location. For exp $(document).find('.largelines input[type=radio]') "OR" if you need to find radio butons based on delete button you can modify the code like this:
$(document).ready(function(){
$('.delete').on('click', function(){
var $parent = $(this).parents('.largelines');
$parent.find('input[type=radio]').each(function(){
if($(this).get(0).checked){
//do something
}
});
});
});
There is bunch of other ways to do that, another one is using next() or siblings() function:
$(document).ready(function(){
$('.delete').on('click', function(){
var $fieldset= $(this).next('fieldset');
//var $fieldset= $(this).siblings('fieldset');// i comment this out [its alternative way]
$fieldset.find('input[type=radio]').each(function(){
if($(this).get(0).checked){
//do something
}
});
});
});
This find only checked radio under .largelines scope of clicked .delete element.
$(function () {
$(document).on('click', '.delete', function () {
var isChecked = $('input:radio:checked', $(this).parent()).length > 0
alert(isChecked)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="largelines">
<p class="line">OPTION 1</p>
<div class="delete">
Check 1
</div>
<fieldset>
<input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
<input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
</fieldset>
</div>
<hr>
<div class="largelines">
<p class="line">OPTION 2</p>
<div class="delete">
Check 2
</div>
<fieldset>
<input type="radio" id="option21" name="option1" value="option1"><label for="option1">option1 </label><br>
<input type="radio" id="option22" name="option2" value="option2"><label for="option2">option2 </label>
</fieldset>
</div>

Why Checkbox is not unchecking in jquery

I need to uncheck a checkbox. It is doing everything like alert or removing div, but not unchecking the checkbox. I have used both attr and prop methods. The checkbox id is ok. Even it doesn't show any error in firebug console.
$('html').on('click', '#inScopeDiv .remButton', function () {
var currId = $(this).attr('id');
var chkBoxId = "#chk"+currId;
alert(currId);
alert('#chk'+currId);
$(chkBoxId).prop("checked", false);
$(chkBoxId).attr("checked", false);
$('#div'+ currId).remove();
$('#inScopeActionDiv' + currId).remove();
});
HTML provided ::
<c:forEach items="${data.inScope}" var="inScopeValues">
<div class="col-md-12" style="background-color: snow;">
<input class="inScope" type="checkbox" id="chk${inScopeValues.key}" name="chk + ${inScopeValues.key}" value="${inScopeValues.value}">
${inScopeValues.value}
</div>
</c:forEach>
Button & Checkbox is below ::>
<input class="inScope" type="checkbox" id="chkisc_2" name="chkisc_2" value="In Scope 2">
<button id="chkisc_1" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>
The button you show in the updated question has id="chkisc_1", then in your function you take that and add #chk to the beginning of it which would mean you're looking for an element with the selector "#chkchkisc_1". Meanwhile, apparently the checkbox has id="chkisc_2", although it does seem to be created in a loop so perhaps there is also a _1 (though that would mean you have more than one element with the same id, which is invalid html).
Change the button to have id="isc_1", then when your JS adds #chk it will be looking for #chkisc_1:
$('html').on('click', '#inScopeDiv .remButton', function () {
var currId = $(this).attr('id');
var chkBoxId = "#chk"+currId;
$(chkBoxId).prop("checked", false);
$('#div'+ currId).remove();
$('#inScopeActionDiv' + currId).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="inScopeDiv">
<input class="inScope" type="checkbox" id="chkisc_1" name="chkisc_1" value="In Scope 1" checked>
<button id="isc_1" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>
<input class="inScope" type="checkbox" id="chkisc_2" name="chkisc_2" value="In Scope 2" checked>
<button id="isc_2" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>
</div>
You should use prop() and removeAttr() to achieve this.. Hope it helps!
var cb = $("#checkbox")
$('#button1').click(function() {
cb.prop("checked", true)
})
$('#button2').click(function() {
cb.removeAttr('checked')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox" />This is a checkbox
<br />
<br />
<button id="button1">Check checkbox</button>
<br />
<br />
<button id="button2">Uncheck checkbox</button>
let checkbox = document.querySelector("input");
checkbox.addEventListener("click",function(){
console.log("Sorry ( ͡° ͜ʖ ͡°)");
this.checked = false;
});
<input type="checkbox" />

Cannot update radio input

I have two radio buttons
<div class="radio">
<input class="i-radio" type="radio" name="rbtnRoundTrip" checked="checked" value="OneWayTrip" />
</div>
<div class="radio">
<input class="i-radio" type="radio" name="rbtnRoundTrip" value="RoundTrip" />
</div>
I have a value on my variable
Var Tripway;
That is "OneWayTrip" or "RoundTrip" so now i am trying to select the coresponding radio button.
$('#FormSearch input[type="radio"][name="rbtnRoundTrip"][value="' + Tripway + '"]').trigger('click');
But this code never selects the radio button with the values "RoundTrip". Even if the value of the variable is "RoundTrip" the radio button is always checked on OneWayTrip
do it like
$('#FormSearch input[type="radio"][name="rbtnRoundTrip"][value="' + Tripway + '"]').prop("checked", true).trigger('click');
Considering you want to trigger click event too.
If you are using old jquery then user .attr("checked", "checked") instead of .prop("checked", true)
You should use prop() method instead of trigger('click') like following.
var Tripway = "RoundTrip";
$('#FormSearch input[type="radio"][name="rbtnRoundTrip"][value="' + Tripway + '"]').prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="FormSearch">
<div class="radio">
<input class="i-radio" type="radio" name="rbtnRoundTrip" checked="checked" value="OneWayTrip" />
</div>
<div class="radio">
<input class="i-radio" type="radio" name="rbtnRoundTrip" value="RoundTrip" />
</div>
</form>

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!

Categories

Resources