Radioboxes and JQuery - javascript

Here's my HTML code:
<label><input type="radio" id="fNuttig" /> Nuttig</label>
<label><input type="radio" id="fNietNuttig" /> Niet nuttig</label>
<label><input type="radio" id="fNogUitTeMakenNuttig" />Nog uit te maken</label>
And here's my javascript code:
if ($('#fNuttig').val() == 'on') {
nuttig = 'Nuttig';
} else if ($('#fNietNuttig').val() =='on') {
nuttig = 'Niet nuttig';
} else if ($('#fNogUitTeMakenNuttig').val() =='on') {
nuttig = 'Nog uit te maken';
} else {
nuttig = 'ongeldige invoer';
}
alert($('#fNuttig').val()); // Gives 'on'
alert($('#fNietNuttig').val()); // Gives 'on'
alert($('#fNogUitTeMakenNuttig').val()); // Gives 'on'
alert(nuttig); // Gives 'on'
This code gets called when pressing a button.
Why are all my radiobuttons turned on? If I add the 'name=' tag, and accomplish the same using PHP, it does work, and in javascript, it says that my buttons are always 'on'.
What am I doing wrong?
Yvan

You want to use if ( $('#fNuttig').is(':checked') ) instead of if ( $('#fNuttig').val() == 'on' ).
$('#fNuttig').val() is just retrieving the value of the value attribute, whether it's checked or not. $('#fNuttig').is(':checked') will return true if it's checked and false if it's not.

Your HTML code lack of name attribute. It's mandatory for a input element to have them. Radios with same name will only able to turn on one of it. any particular reason why you write the js code like the above?
It's better to access it by name
<input name="radio" .../>
$('input[name="radio"]').val();

Related

Laravel 8 - how to keep radio "checked" fields visible after `validate()` refresh?

I have a form with "Does this case have IR number?"
If yes, show fields. If no, hide and show others.
I am using
validate() function.
old() to keep data after failed form submission, aka validate() error messages.
JQuery show/hide for the fields.
For the radio input, I used old() like this:
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(!old('checkIR')) checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR')) checked #endif id="noIR">
to keep the checked as it is after failed validate(), but it's buggy, When I check "Yes" and refresh, it checks "No" when it must be as "Yes".
As for the show/hide, here is what I did:
// Show/Hide fields based on radio button option
$(document).ready(function() {
$('input[name="checkIR"]').click(function() {
var inputValue = $(this).attr("value")
var targetField = $("." + inputValue);
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
});
});
With a help of css:
.box {
display: none;
}
How the code works:
If yes/haveIR radio is checked: show all fields containing class="box haveIR"
Issues trying to solve:
How to fix/improve the small bug in the input old()?
If user checked "yes", how to keep the fields of yes visibile even after failed laravel validate()?
Since the radio inputs have the same name, in both cases your session has "checkIR" and when you try to check it with old('checkIR') it will return true regardless of its value. Thats why "No" is checked.
Therefore, in order to find the old selected one, you should check by its value, not whether it exists in the session or not.
Code like this should work for you;
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(old('checkIR') == 'haveIR') checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR') == 'noIR') checked #endif id="noIR">
Or;
You can use 0 and 1 for values. Since old('checkIR') will return '0' or '1' and PHP will interpret '0' as false and '1' as true the behaviour will be like you wanted.
And for keeping the related fields visible;
You can run some script when document ready and set related fields visible by input value.
$(document).ready(function() {
var input = $('input[name="checkIR"]:checked');
if (input) { // if any checked radio when document ready
var targetField = $("." + input.val());
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
}
});
Note: didn't run the script, it may have errors but you get the point.

How to disable anPHP disable and clear textbox when checkbox is unchecked. Check/uncheck checkbox depending on database

I want to disable and clear a textbox if a checkbox is uncheck and enable it when checked. At the same time, the checkbox should be dependent on the value on the database.
If deductstatus == 1, checkbox should be checked when loaded
If deductstatus == 2, checkbox should be unchecked when loaded
The code below is not working. Any help?
$(".dedstat").click(function() {
if ($(".dedstat").is(":checked")) {
$(".deductto").removeAttr("disabled")
} else {
$(".deductto").attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
deductto.value = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat" value="<?php if ($dedstat == 1) echo 'checked'; ?>">
<input type="text" name="deductto" id="deductto" value="<?php echo $deductto;?>">
Checked is not a value, it is an attribute, it should be:
<input type="checkbox" name="dedstat" id="dedstat" value="" <?php if ($dedstat == 1) echo 'checked'; ?>>
When manipulating boolean attributes such as checked, disabled, multiple, you should be using .prop() instead of .attr() or .removeAttr(). Some other suggested improvements:
Use this.checked instead of $(".dedstat").is(":checked"), so that it is context specific
Use the ID selector instead of class
You can chain your jQuery methods, so you can both disable the input and empty its value at the same time
Listen to the change event instead of click for <input> elements
$("#dedstat").change(function() {
if (this.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
If you want the state of the input to be evaluated on pageload, you will also have to perform the same logic without binding it to the onChange event. The best way is to create a function that is called by both the onChange event and DOMready/window.load event. In the example below, the method we create will accept a DOM node as an argument, so that it is contextually aware of which checkbox element you are referring to:
// Method to conditionally enable/disable input
var updateTextInput = function(el) {
if (el.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
}
// Call method when change event is fired from checkbox
$("#dedstat").change(function() {
updateTextInput(this);
});
// Call method on DOMready, pass DOM node (not the jQuery object)
updateTextInput($('#dedstat')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
And with regards to your PHP, you can simply use tenary operators to conditionally write the checked prop to your input element, i.e.:
<input type="checkbox" name="dedstat" id="dedstat" <?php echo $dedstat == 1 ? 'checked' : ''; ?>>
value attribute can not be used to keep it checked or unchecked based on database value. And bind checked or unchecked attribute separately.
So change that tag like this:
<input type="checkbox" name="dedstat" id="dedstat" onclick="isChecked()" value="1" <?php echo (isset($dedstat) && $dedstat == 1)? "checked" : "" ; ?>
More on this,
If you want to store 1 and 2 values to save checked and unchecked condition of the checkbox respectively, then what you should do is, if the checkbox is checked, you will get its value in php $_POST but if it was not checked, you will not get it in $_POST. So in that case, you should store its default value 2 into the DB column. So then only you can get 2 when you fetch its value next time from DB.
Just a little suggestion :
Is your JS at the bottom of the page ?
Plus I just noticed something :
$(".dedstat") <= you're calling a class with the dot. Your imputs have ID's.
$("#dedstat").click(function () {
if ($("#dedstat").is(":checked")) {
$("#deductto")
.removeAttr("disabled")
}
else {
$("#deductto")
.attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
.deductto.value = "";
}
});
It should work a little better.

Need help validating radio buttons with JavaScript

I need help validating radio buttons with JavaScript. Here's the section of HTML:
<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" /> Yes, both!<br/>
<input type="radio" name="receptionattend" value="yesc" /> Yes, but only the ceremony! <br/>
<input type="radio" name="receptionattend" value="yesr" /> Yes, but only the reception!<br/>
<input type="radio" name="receptionattend" value="no" /> No, you guys are lame!
And here's the simplest validation code I have:
function validateForm()
var y=document.forms["rsvpform"]["receptionattend"].checked;
if (y==null || y=="")
{
alert("Please indicate whether or not you will attend.");
return false;
}
}
My issue mostly seems to be that, no matter how I code the validation, it returns an error message even when I have a radio button selected.
The first issue you have is that in general, you should force a default in your radio buttons, make one of the buttons be already "checked" and you will never have a null value passed to your form checker. Most people expect their radio buttons to have a default already checked and this is standard practice in web development.
However, should you need to check for null or undefined, you should use typeof and strict comparison with ===
(typeof y === "undefined" || y === null);
After reading your comment - I noticed one other thing. Are you trying get get the value directly from Javascript by reading the DOM with like an onclick function? You won't be able to do this because you aren't ever actually getting your checked value with this line.
var y=document.forms["rsvpform"]["receptionattend"].checked;
Instead, try something like this.
var y = document.getElementsByName('receptionattend');
var y_value;
for(var i = 0; i < y.length; i++){
if(y[i].checked){
y_value = y[i].value;
}
}
y_value should now return the result of the checked radio button. If nothing was checked y_value will be null.
this line:
var y=document.forms["rsvpform"]["receptionattend"].checked;
returns either true or false based on checked attribute of your element, so you should be doing:
if ( !y ) { //if not checked i.e false
alert("Please indicate whether or not you will attend.");
return false;
}
do like:
function validateForm() {
var is_checked = false;
var eles = document.forms["rsvpform"]["receptionattend"];
for(var i = 0; i < eles.length; i++ ) {
if( eles[i].checked ) {
is_checked = true;
break;
}
}
if (!is_checked)
{
alert("Please indicate whether or not you will attend.");
return false;
}
else {
alert("valid");
}
}
Demo:: jsFiddle
I'm not going to suggest using jquery just for this. But should you end up using jquery, it makes this kind of validation very easy.
HTML Note the use of Labels, this is just a good practice, it means your uses can click on the text and a whole raft of other accesibililty bonuses.
<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" id="rcBoth" /><label for="rcBoth">Yes, both!</label><br/>
<input type="radio" name="receptionattend" value="yesc" id="rcCOnly" /><label for="rcCOnly"> Yes, but only the ceremony! </label><br/>
<input type="radio" name="receptionattend" value="yesr" id="rcROnly" /><label for="rcROnly">Yes, but only the reception!</label><br/>
<input type="radio" name="receptionattend" value="no" id="rcNo" /><label for="rcNo"> No, you guys are lame!</label><br />
<input type="button" value="Validate Me" id="btnValidate"/>
Javascript/Jquery Wire this up in the jquery $(document).ready event.
$("#btnValidate").click(function(){
//The following selector is not very efficient, classes
//or a bounding element (eg div or fieldset) would be better
if($("input[name='receptionattend']:checked").length == 0)
{
alert("Please tell us if you're attending or not!");
}
});
http://jsfiddle.net/wpMvp/
To break down the script
$("#btnValidate").click(function(){}); adds an onlclick event handler to the button with ID btnValidate
$("input[name='receptionattend']:checked").length returns how many input elements with a name of receptionattend are checked
the rest should be fairy self explanatory

Hide and show another element onclick of a radio button, based on value

I have 4 jquery radio buttons in my form something like this
<form:radiobutton path="lcmoption" name ="lcmoptions" id ="lock" value="lock" checked="checked"/>
<fmt:message key="lcm.form.options.lock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="unlock" value= "unlock"/>
<fmt:message key="lcm.form.options.unlock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="terminate" value="terminate" />
<fmt:message key="lcm.form.options.terminate" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="wipe" value="wipe" />
<fmt:message key="lcm.form.options.wipe" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="other" value="other" />
<fmt:message key="lcm.form.options.other" />
onclick of the first four radio buttons I am dynamically loading the select box using an AJAX call. When the user clicks the last option, i.e, other, I need to hide the textbox and show a text area.
I tried using:
$("input:radio[name=lcmoption]").click(function() {
if(type=="other")
{
$([name="reasonsList"]).css("display",none");
$([name="otherreasonsList"]).css("display", "block");
}
else
{
// AJAX CALL to load dropdown (for other options)
}
}
But this did not work. I also tried:
$([name="reasonsList"]).hide();
$([name="otherreasonsList"]).show();
This shows both the dropdown and text area. Can anyone help me on hiding reasonsList div and show otherreasonsList div onclick of a radio button with other value?
There's all kinds of syntax errors in the code you posted.
For instance, you need to quote your selector strings as text, and an attribute value in an attribute selector ([name=something]) can be either an unquoted single word or a quoted string.
In this case, just leave it out:
$('[name=reasonsList]').show();
Also, instead of $.click(), I would use $.change(), which will detect when the radio value has changed.
$("input:radio[name=lcmoptions]").change(function(){...});
See notes in comments:
// First line looks ok, but I would use a .change() handler
// Also, I just noticed you're:
// "input:radio[name=lcmoption]"
//
// But shouldn't it be:
// "input:radio[name=lcmoptions]"
//
// See lcmoptions vs lcmoption (no s on second); it's lcmoptions
// in your template code. I don't know what path="lcmoption" means,
// but I think name="lcmoptions" is what you need to use to select.
$("input:radio[name=lcmoption]").click(function() {
// What is type? I think you mean this.value or $(this).val()
// Don't forget to lowercase the comparison, so other matches
// Other.
if (this.value.toLowerCase() == "other")
{
// The selector needs to be quoted as a string, ie:
// '[name="reasonsList"]'
//
// Also, jQuery has a shortcut method, $(sel).hide();
$([name="reasonsList"]).hide();
// The same thing here, you need to quote that string or
// alternatively, since it's a single word, leave the quotes
// out of the selector, ie:
// $('[name=otherreasonsList]')
//
// Again, jQuery has a shortcut method, $(sel).show();
$('[name=otherreasonsList]').show();
}
// Don't know if you missed this in the example, but you need });
// to close the $.click() function.
});
And your second attempt:
// Same problem as above, you need to quote the string for the
// selector, ie:
// $('[name=reasonsList]')
//
// With inner quotes, but here they're unnecessary.
$('[name="reasonsList"]').hide();
//
// Without inner quotes on name value
$('[name=otherreasonsList]').show();
For what you're wanting to do, you can:
$(document).ready(function(){
// This is called caching, which is a good practice to get
// get into, as unless you need to requery due to dynamic
// changes, selecting them only once and reusing will give
// you better performance.
var $lcmoptions = $('input:radio[name=lcmoptions]'),
$textbox = $('[name=textbox]'),
$textarea = $('[name=textarea]');
$lcmoptions.change(function(){
// Note I this.value.toLowerCase() the comparison value
if (this.value.toLowerCase() === 'other') {
$textbox.hide();
$textarea.val($textbox.val()).show();
} else {
$textarea.hide();
$textbox.val($textarea.val()).show();
}
});
});
For more information on caching, see:
Does using $this instead of $(this) provide a performance enhancement?
This is assuming your client-side markup looks something like:
<input type="radio" name="lcmoptions" id="unlock" value= "lock"/> Lock
<input type="radio" name="lcmoptions" id="unlock" value= "unlock"/> Unlock
<input type="radio" name="lcmoptions" id="terminate" value="terminate" /> Terminate
<input type="radio" name="lcmoptions" id="wipe" value="wipe" /> Wipe
<input type="radio" name="lcmoptions" id="other" value="other" /> Other
<div>
Enter text:
<input type="text" name="textbox" value="test text stuff"/>
<textarea name="textarea"></textarea>
</div>
http://jsfiddle.net/LthAs/
Have tried this mine working fine
if(document.getElementById('other').checked==true)
{
$("#txtboxID").hide(350);
$("#txtareaid").show(350);
}
try this, u can put this on change event or click event.
if ($("radio[#name='lcmoptions']:checked").val() == 'other')
$("#otherreasonsList").show();

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources