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.
Related
I have more than fifteen checkbox inputs all with the same class, looking something like below:
I want to have only the first input be checked and stay checked when any other input with the same class is checked. If only the first input is checked you should be able to check and uncheck it freely. Only the first one has the ID, #SR01201. The rest only have the class check-12.
Right now, I can freely uncheck and check the first input, and it will get checked if any other inputs with the class check-12 are checked. But once any other input (besides the first one) is checked, it can't be unchecked.
$('.check-12:not(#SR01201)').on('change', function() {
var $this = $(this);
var SRTwelveOne = $("#SR01201");
if ($this.prop('checked', true)) {
SRTwelveOne.prop('checked', true)
} else if ($this.prop('checked', false) && $this.siblings().prop('checked', false)) {
SRTwelveOne.prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">
The $this.prop('checked', true) in if ($this.prop('checked', true)) is setting the checkbox to true, not checking if it's true. For that you want to use if ($this.prop('checked')). But I think your issue can be reduced to the following:
$('.check-12:not(#SR01201)').on('change', function() {
$("#SR01201").prop('checked', $('.check-12:not(#SR01201):checked').length > 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">
The first line selects your checkboxes with the class you specified, but not the first one. Upon changing any of them, the checkbox with the ID SR01201 changes its checked property depending on how many of the other checkboxes are checked. 1 or more? check it, otherwise uncheck it. The result of $('.check-12:not(#SR01201):checked').length > 0 will be true or false.
The problem is that you're not checking if a checkbox is checked with $this.prop('checked', true) in your if statement. You're actually checking the box. To see if it's a box is checked, use is(":checked")
The function created to send an alert based on a radio box's value returning as null is firing and sending alert while radio box has a value that should not be null. Somewhere else on the page is a function that hides the tables these radios appear on, and is what initially made this task out of my reach. If this div didn't hide, and these tables weren't generated dynamically then it could have been solved by adding a required attribute to the radio. This actually works as long as the div is showing, however breaks when hidden. I've essentially been tasked to take the long way around making this radio required.
Here is the javascript
<script type="text/javascript">
$(function validate() {
$(document).submit(function() {
<%For z = 0 to TotalUnits - 1%>
if ($("input[name='checkradio<%=z%>']:checked").length == 0)
alert("Select Yes or No for Needs Repair checkbox <%=z%>");
return false;
}
<%Next%>
$("submitbutton").click(function() {
$("#formID").submit();
document.getElementsByName("checkradio").addEventListener('click',
validate);
});
});
});
</script>
Here is the HTML
<label id="checklabel" name="checklabel">The Vehicle Requires Repair</label>"
<label id="yesradio">
<input type="radio" ((name="checkradio" & z)) value="1" id="Radio1"> Yes</label>
<label id="noradio">
<input type="radio" ((name="checkradio" & z)) value="0" id="Radio0"> No</label>
Here is the script that hides the div (I cleaned the concat. but left the meat in its own tags)
<script>
<%for z = 0 to TotalUnits - 1%>
$( document ).ready(function() {
$("div.section<%=z%>").hide();
});
<%next%>
</script>
<%response.write(TmpString)%>
Here is my submit button (stripped off the label)
<input value="Submit" type="submit" id="submitbutton" name="submitbutton"
onsubmit="validate()">
The alert should only fire when the submit button is pressed and the value of the radio is null.
Because each radio button is a control it is own right, you need to check if any of the controls that are linked together (via the name attribute) are checked.
Firstly, getElementsByName() returns an array (notice the s on Elements), so there is no .value for you to check.
(Oh, and be aware that having multiple <label id="yesno"> is invalid, as elements need to have a unique id attribute. In this case you're probably best just removing the id="yesno" completely.)
But it's a lot, lot easier to do this via jQuery...
<script type="text/javascript">
$(function() {
$(document).submit(function() {
<%For z = 0 to TotalUnits - 1%>
if ($("input[name='checkradio<%=z%>']:checked").length == 0)
alert("Select Yes or No for Needs Repair checkbox <%=z%>");
return false;
}
<%Next%>
$("submitbutton").click(function() {
$("#formDVIR").submit();
});
});
});
</script>
By using the selector of input[name='checkradio<%=z%>']:checked you're asking jQuery to find all input controls with a name of checkradio1 (or whatever z is) and only those which are checked. If the length of the resultant jQuery object is more than 1 you know at least one is selected
push me or so
const myId=document.getElementById(“myId”);
myId.addEventListener(“click”, function () { alert(“message and stuff”)});
Using Web2Py I constructed some checkboxes, they all look similar to this one:
<input type="checkbox" value="some_value" onchange="ajax('/app/controller/function/args', ['the_name'])" name="the_name" id="some_id" class="boolean">
They are supposed to submit their value on change, which they do. When I print request.vars:
<Storage {'the_name': some_value}>
but only when they are being checked or activated.
The other way, when they are unchecked or deactivated the ajax call is done, but no data submitted. Again print request.vars:
<Storage {}>
Why is this only working 'one-way'?
Edit:
The behaviour stays the same when using the default-value value="on". To specify what I am doing: I have a number of hidden checkoxes that get checked / unchecked on button-clicks. When the checkboxes are not hidden and clicked directly the behaviour does not change - submitting data on activation, not submitting any data on deactivation.
Here is the JS I use.
$(function() {
return $('.btn-trigger').click(function() {
var btn, checkbox;
btn = $(this);
checkbox = btn.next();
if (checkbox.attr('checked')) {
checkbox.val('false');
checkbox.removeAttr('checked').prop('checked', false);
checkbox.trigger('change');
return btn.removeClass('btn-success').addClass('btn-danger');
} else {
checkbox.val('true');
checkbox.attr('checked', 'checked').prop('checked', true);
checkbox.trigger('change');
return btn.removeClass('btn-danger').addClass('btn-success');
}
});
});
The solution to this problem is to pass a hidden input field along the checkbox. Both, the checkbox and the hidden field must share the same name:
<input type="checkbox" value="some_value" onchange="ajax('/app/controller/function/args', ['the_name'])" name="the_name" id="some_id" class="boolean">
<input type="hidden" name="the_name value="some_value">
Now, if the checkbox is deactivated (is unchecked) the value from the hidden field is passed:
<Storage {'the_name': some_value}>
on activating the values from both fields are passed:
<Storage {'the_name': [some_value, some_value]}>
This post pointed to the solution.
How can I check if a field is a radio button?
I tried if(document.FORMNAME.FIELDNAME.type =='radio') but document.FORMNAME.FIELDNAME.type is returning undefined.
The html on the page is
<input name="FIELDNAME" type="radio" value="1" >
<input name="FIELDNAME" type="radio" value="0" >
Unless I am taking the whole approach wrong. My goal is to get the value of an input field, but sometimes that field is a radio button and sometimes its a hidden or text field.
Thanks.
Your example does not work because document.FORMNAME.FIELDNAME is actually an array with 2 elements (since you have 2 inputs with that name on the form). Writing if(document.FORMNAME.FIELDNAME[0].type =='radio') would work.
EDIT: Note that if you don't know if document.FORMNAME.FIELDNAME is a radio (ie you might have a text/textarea/other) it is a good idea to test if document.FORMNAME.FIELDNAME is an array first, then if the type of it's first element is 'radio'. Something like if((document.FORMNAME.FIELDNAME.length && document.FORMNAME.FIELDNAME[0].type =='radio') || document.FORMNAME.FIELDNAME.type =='radio')
In case you don't have a form then maybe go by attribute is an option.
var elements = document.getElementsByName('nameOfMyRadiobuttons');
elements.forEach(function (item, index) {
if (item.getAttribute("type") == 'radio') {
var message = "Found radiobutton with value " + item.value;
if(item.checked) {
message += " and it is checked!"
}
alert(message);
}
});
Your code should work, but you could try the following:
document.getElementById('idofinput').type == 'radio'
Edit: Your code doesn't work for the reason mihaimm mentions above
I need to use javascript so that when the one radio button is selected nothing happens but if the other one is (for example, other address) it will then validate the following fields;
street
suberb
postcode
Whilst I post this, it's probably a similar method, but when I have a checkbox and a textbox how could I make it so that the textbox must not be left empty only if the checkbox is checked...
Thanks everyone!!!! Ask for more details if needed, I'm terrible at explaining things!
/* To check radio validation in Employee Details page */
function editPage()
{
var select=document.frmEmployeeDetails.radSelect;
if (radioValidate(select,"Select an Employee"))
{
window.open("EditEmployee`enter code here`.html","_self");
}
return false;
}
Hope this example helps you friend.
Since they will be checking the radio button when they click on it, you can add an onClick event to one of the radio buttons and not the other.
<input type='radio' id='test' name='test-1' />
<input type='radio' id='test' name='test-2'onClick='Validate();'/>
For the checkbox, when a user checks the box you should set the focus to the text input field. That way if a user moves away from that field (onBlur) you can give them an error/alert to fill in the text.
<input type='checkbox' id='testChkbx' name='testChkbx' onClick=' /*Set the focus to the text box*/'/>
<input type='text' id='testText' name='testText' onBlur='/* Check to make sure the value of the checkbox is not empty. */'/>
I'll assume you might be using jQuery, since you didn't say. If not, then you can still take the concepts and port them to plain old javascript or whatever you're using.
Example markup
<form id="address-form">
<input type="radio" name="validate" id="validate_address" value="yes"> Validate<br>
<input type="radio" name="validate" value="no"> Don't Validate<br>
Street <input name="street"><br>
Suberb <input name="suberb"><br>
Postcode <input name="postcode"><br>
<input type="submit">
</form>
Conditional validation
Either somewhere on your page in a <script> tag or in a javascript file you include, create a submit event that will check the value of the radio input before doing the validation.
$('#address-form').submit(function(event) {
if ($('input[name=validate]:checked').val() === 'yes') {
if (!formValid()) {
event.preventDefault(); // Don't submit the form
}
}
});
// Perform validations
function formValid() {
if ($('input[name=street]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=suberb]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=postcode]').val().length == 0) {
// tell them ...
return false;
}
return true;
}
That should do the trick!
I created a jsfiddle you can mess with further if you want - http://jsfiddle.net/nilbus/JNnuX/2/
Using a checkbox instead
It's pretty similar to use a checkbox. Instead of this
if ($('input[name=validate]:checked').val() === 'yes') {
just check to see if your checkbox is checked.
if ($('input[name=validate]').attr('checked')) {
http://jsfiddle.net/nilbus/JNnuX/3/