easier way to toggle a radio button with JavaScript/Ajax? - javascript

I've set up radio buttons like this:
<hr />
<h2>PhoneyTV Cabana</h2>
<p>
<input type="radio" id="phoneyRadio1" value="0" onclick="toggleParticlePower(phoneyID, phoneyPowerFunction, this.value)" name="led" />Off
<input type="radio" id="phoneyRadio2" value="1" onclick="toggleParticlePower(phoneyID, phoneyPowerFunction, this.value)" name="led" />On
</p>
there must be a simpler way of updating their stat than this:
$.getJSON(myURL, function(data) {
state = (parseInt(data.result) == 1)
if (state) {
$('#phoneyRadio1').attr('checked', false);
$('#phoneyRadio2').attr('checked', true);
} else {
$('#phoneyRadio2').attr('checked', false);
$('#phoneyRadio1').attr('checked', true);
}
});
I tried just making the 'active' button highlighted, but I'm having trouble with that...
What obvious shortcut am I missing?

if (state) {
$('#phoneyRadio1').attr('checked', false);
$('#phoneyRadio2').attr('checked', true);
} else {
$('#phoneyRadio1').attr('checked', true);
$('#phoneyRadio2').attr('checked', false);
}
In the above code, if you observe closely, a simple pattern that value for phoneyRadio1 is always opposite of condition and phoneyRadio2 is same as condition. So it can be reduced to:
$('#phoneyRadio1').attr('checked', !state);
$('#phoneyRadio2').attr('checked', state);
Now, state = (parseInt(data.result) == 1) will make state a global variable(missing var). Secondly, you are converting data.result to int, so since you are matching same type values, you should use === instead of ==.
So it would look like var state = (parseInt(data.result) === 1) or var state = (+(data.result) === 1).
Sample Fiddle

You can try this.
$.getJSON(myURL, function(data) {
state = (parseInt(data.result) == 1)
$('#phoneyRadio1').attr('checked', !state);
$('#phoneyRadio2').attr('checked', state);
});

Related

How can i change the value of checkbox upon change

I would like to change the value of the checkbox, but failed with the following code.
$("input:checkbox").on("change", function () {
if (this.checked == true) {
this.val("1");
}
else {
this.val("0");
}
});
I not sure why it is no responds without the code, which it should've the "checked" when I'm calling this element, but no. So i will need to add a value field manually.
<input class="c-switch-input" type="checkbox" name="pk_{{$d['id']}}" value="{{$d['status']}}">
You are mixing jQuery and DOM incorrectly
EITHER
this.value = "1";
OR
$(this).val("1")
But use a ternary:
$("input:checkbox").on("change", function () {
this.value = this.checked ? "1" : "0";
console.log(this.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" />

Read a field value, remember it, change the field, and then return to the previous state

I have some number fields set based on a large number of factors in an eCommerce site. I want an option that will clear out those numbers if a radio option is clicked, but then return to their previous numbers if a different radio option is clicked. I have the following code to set the values to 0, but I dont know how to continue for setting them back. My values are defined in several different places, so I can't easily refer to them, but is there a way to read the fields before they're set to 0, and then set them back to their previous state?
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$('#option1').val('0');
$('#option2').val('0');
$('#option3').val('0');
$('#option4').val('0');
}
else if($(this).attr('id') == 'no-option') {
???
}
You can use data-attributes to store the previously entered/selected value:
$('input[type="radio"]').click(function() {
var $optionOne = $('#option1');
var $optionTwo = $('#option2');
var $optionThree = $('#option3');
var $optionFour = $('#option4');
if($(this).attr('id') == 'yes-option') {
$optionOne.data('previous-value', $optionOne.val());
$optionOne.val('0');
$optionTwo.data('previous-value', $optionTwo.val());
$optionTwo.val('0');
$optionThree.data('previous-value', $optionThree.val());
$optionThree.val('0');
$optionFour.data('previous-value', $optionFour.val());
$optionFour.val('0');
} else if($(this).attr('id') == 'no-option') {
$optionOne.val($optionOne.data('previous-value'));
$optionTwo.val($optionTwo.data('previous-value'));
$optionThree.val($optionThree.data('previous-value'));
$optionFour.val($optionFour.data('previous-value'));
}
});
A possible approach would be to always keep your options' previous state in an array.
var previousStates = [];
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$.saveState(); //Save the current state before changing values
$( "option" ).each(function( index ) {
$(this).val('0');
});
}
else if($(this).attr('id') == 'no-option') {
$.restoreState();
}
});
$.saveState = function() {
previousStates = []; //Empty the array
$( "option" ).each(function( index ) {
previousStates[index] = $(this).val();
});
}
$.restoreState = function() {
$( "option" ).each(function( index ) {
$(this).val(previousStates[index]);
});
}
Note: as this method uses indexes to identify options, be careful if you need to dynamically add or remove an option!
Use data-attributes to store the old values, so you can read them later on.
It's better to use a loop to go trough each element, so you don't need to modify it every time a new input field was added.
You can also change the selector to $('input') or anything that suit your needs.
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$('[id^="option"]').each(function(){
$(this).data('oldval', $(this).val());
$(this).val(0);
});
}
else if($(this).attr('id') == 'no-option') {
$('[id^="option"]').each(function(){
$(this).val($(this).data('oldval'));
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input name="clr" type="radio" id="yes-option">
<span>YES</span>
</label>
<label>
<input name="clr" type="radio" id="no-option">
<span>NO</span>
</label>
<div>
<input type="number" id="option1" value="15">
</div>
<div>
<input type="number" id="option2" value="23">
</div>
<div>
<input type="number" id="option3" value="100">
</div>
<div>
<input type="number" id="option4" value="86">
</div>

Change radio button value with javascript

I have two radio buttons:
<input type="radio" name="editList" id="prov" value="Admin">Admin
<input type="radio" name="editList" id="user" value="User">User
I want to change values with javascript, and I try as:
var typeu= $('input[type=radio][name=editList]').val();
if (typeu=== "Admin") {
typeu= typeu.val() === "A";
} else if (typeu === 'User') {
typeu= typeu.val() === "U";
But I get issue:
Uncaught TypeError: typeu.val is not a function
Can someone help me please?
Try this
var typeu = $('input[type=radio][name=editList]');
$.each(typeu, function(i, v) {
if ($(v).val() === "Admin") {
$(v).val("A");
} else if ($(v).val() === 'User') {
$(v).val("U");
}
});
https://jsfiddle.net/za61z3vx/
First line, you get all the inputs that match type=radio and name=editList. Since there's more than one it'll be an array, so you need iterate through it.
To check radio button by javascript you should use "prop" function
$('#prov').prop('checked', true );
// or $('#prov').prop('checked', false );
To GET checked prop u should use:
$('#prov').prop('checked');
From your code:
var typeu= $('input[type=radio][name=editList]');
typeu.each( radio => {
const $rb = $(radio);
console.log( $rb.val(), $rb.prop('checked') )
});
Use val(function)
var radioValues = {
'Admin':'A',
'User':'U'
};
$('#prov, #user').val(function(_, existingValue){
// if current value matches keys in object, will return new value
// if not a match will return existing value
return radioValues[this.value] || existingValue;
})
// log updated values for this demo
.each(function(){
console.log(this.id, 'value is', this.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="editList" id="prov" value="Admin">Admin
<input type="radio" name="editList" id="user" value="User">User
Note that your attempt will only return value of the first element. You need to loop over them and deal with each instance

I got a annoying bug in storing input value using localStorage

I want to do is to store the current inputs even if the user refresh or close the browser.
My problem is if i click Yes in the radio button and refresh the page or close the browser and reopen it the No button is checked and the Yes button is unchecked.
testing link: http://jsfiddle.net/5kcsn/124/
current script:
$(document).ready(function () {
$('#employed_v1, #employed_v0, #test').on("change", function () {
debugger;
localStorage.setItem($(this).attr("id"), $(this).val())
});
$('#employed_v1, #employed_v0, #test').each(function (ind, val) {
debugger;
if ($(val).attr("id") != "employed_v1") {
$(val).val(localStorage.getItem($(val).attr("id")))
}
if ($(val).attr("id") != "employed_v0") {
$(val).val(localStorage.getItem($(val).attr("id")))
}
else {
if (localStorage.getItem($(val).attr("id")) == "Yes"){
$("#employed_v1[value=Yes]").prop("checked", true);}
if (localStorage.getItem($(val).attr("id")) == "No"){
$("#employed_v0[value=No]").prop("checked", true);}
}
});
$('[id="employed_v0"]').on('click', function(){
$('#test').val('');
$('#test').prop('disabled', true);
});
$('[id="employed_v1"]').on('click', function(){
$('#test').prop('disabled', false);
});
});
To store the check state you should use the checked attribute.
However, here is a modified version :
$(document).ready(function () {
$('#employed_v1, #employed_v0').on("change", function () {
localStorage.setItem('employed', $(this).attr("id"))
});
$('#' + localStorage.getItem('employed')).attr('checked', true);
});
There are many things to consider here. First, the change-event is only fired on the one radiobutton that is clicked, and you are storing the value of the radiobutton to localstorage. But that information is the same that is already present in the HTML, so it really doesn't serve the purpose. The radiobuttons are grouped by the name-attribute, so you could store only one variable that tells which value of the radiobuttons is the selected one, here is an example:
Html:
<input type="radio" name="employed" id="employed_v1" value="Yes" required="required" class="js-store" />Yes
<br />
<input type="radio" name="employed" id="employed_v0" value="No" required="required" class="js-store" />No
<br>
<input type="text" name="test" id="test" class="js-store" />
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$('.js-store').on("change", function () {
if ($(this).is(":radio")) {
localStorage.setItem($(this).attr("name"), $(this).val());
}
else {
localStorage.setItem($(this).attr("id"), $(this).val());
}
});
$(".js-store").each(function() {
if ($(this).is(":radio")) {
var value = localStorage.getItem($(this).attr("name"));
if (value) { $(this).prop("checked", value === $(this).val()); };
}
else {
var value = localStorage.getItem($(this).attr("id"));
if (value) {$(this).val(value);}
}
});
});
</script>

JQuery submitted values for checkboxes are undefined

I just received some really great help today with a prior jQuery problem and figured since my luck was running that maybe I could also get some help with some checkboxes. Can someone please tell me what I am doing wrong?
Thanks!
The checkboxes are correctly echoing the database bool values but when I submit the changed values, an alert() telles me that they are undefined.
else if (item.field == "admCustRptDly" && item.value == "1")
{
$('#admCustRptDly').attr('checked', true);
}
else if (item.field == "admCustRptSumm" && item.value == "1")
{
$('#admCustRptSumm').attr('checked', true);
}
else if (item.field == "admCustRptDtl" && item.value == "1")
{
$('#admCustRptDtl').attr('checked', true);
}
<tr>
<td class="admMarker">Daily<input type="checkbox" id="admCustRptDly" name="admCustRptDly" class="admChkbx"></td>
<td class="admMarker">Summary<input type="checkbox" id="admCustRptSumm" name="admCustRptSumm" class="admChkbx"></td>
<td class="admMarker">Detail<input type="checkbox" id="admCustRptDtl" name="admCustRptDtl" class="admChkbx"></td>
</tr>
$(function() { $('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admCustBtn").click(function()
{ // validate and process form
// first hide any error messages
$('.error').hide();
var admCustRPSecPhone =
$("input#admCustRPSecPhone").val();
var admCustRptDly =
$("checkbox#admCustRptDly").val();
var admCustRptSumm =
$("checkbox#admCustRptSumm").val();
var admCustRptDtl =
$("checkbox#admCustRptDtl").val();
var dataString =
'admCustID='+ admCustID +
'&admCustRptDly='+ admCustRptDly +
'&admCustRptSumm='+ admCustRptSumm +
'&admCustRptDtl='+ admCustRptDtl;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
alert( "Success! Data Saved");
}
});
return false; }); });
Actually both..
the checkboxes don't have value, so if you try to alert() their values it will lead to "undefined", but if you are facing this on alerting the checkbox itself you are probably doing something wrong.
Setting their values to true, won't lead to anything, as #Soviut said, most properties repeat their names on setting. So your input will get like:
<input type="checkbox" checked="checked" value="1" name="myCheck" />
So, try the above and give us some feedback =´p
Sorry in my case it was the .attr() - works fine for me, even in adobe air.
jQuery('#mycheckbox').attr( "checked" )
Your selectors for the checkboxes are not correct.
var admCustRPSecPhone = $("input#admCustRPSecPhone:checked").val() == 'on';
var admCustRptDly = $("input#admCustRptDly:checked").val() == 'on';
var admCustRptSumm = $("input#admCustRptSumm:checked").val() == 'on';
var admCustRptDtl = $("input#admCustRptDtl:checked").val() == 'on';
You could also use something like:
var admCustRptDly = $("#admCustRptDly:checkbox:checked").val() == 'on';
This will set the values to true/false depending on whether the checkbox is checked or not.
You have no value attribute set on your HTML input element
<input type="checkbox" value="1" id="admCustRptDly" name="admCustRptDly">

Categories