I got a problem with my Feedback Form. I'd like to validate with either JQuery or Javascript, that every group of radio-buttons has always one button selected before you the user can submit the form.
Here's my code from my form.html.
<form id='form' method='POST' action='validate.php'>
<table>
<!-- Table header -->
<tr>
<th> </th>
<th>Always</th>
<th>Often</th>
<th>Rarely</th>
<th>Never</th>
</tr>
<!-- Group One -->
<tr>
<th>Dummy Text 1</th>
<th><input class='radio' type='radio' name='item[0]' value='always'></th>
<th><input class='radio' type='radio' name='item[0]' value='often'></th>
<th><input class='radio' type='radio' name='item[0]' value='rarely'></th>
<th><input class='radio' type='radio' name='item[0]' value='never'></th>
</tr>
<!-- Group two -->
<tr>
<th>Dummy Text 2</th>
<th><input class='radio' type='radio' name='item[1]' value='always'></th>
<th><input class='radio' type='radio' name='item[1]' value='often'></th>
<th><input class='radio' type='radio' name='item[1]' value='rarely'></th>
<th><input class='radio' type='radio' name='item[1]' value='never'></th>
</tr>
<!-- End of table -->
</table>
</form>
<button class='buttons' onclick='subForm()' name='submit'>Send Feedback</button>
<script>
function subForm() {
//Code
}
</script>
But I dont know what I should use for checking if the radio-buttons are checked.
I tried to use document.getElementsByName but this gave me back undefined values
You could add a class to each group of radio buttons, and then use getelementsbyclass, or queryselectorall(compatible with older browsers). Depending on what you're trying to support, you could also consider using the HTML5 "required" attribute on your radio buttons. This will work on most browsers newer than IE8 and will require minimal coding on your part.
I can't comment so I'll clarify that the other solution posted here at the moment will not work because it checks to make sure that at least one radio button on the page has been checked, which means a user can submit an incomplete form if there are multiple groups of radio buttons. His code looks like it's functional otherwise, just create a class for each group of radio buttons.
I think this is your best bet:
var selectedCount = 0;
$('.radio').each(function(){
if($(this).attr("checked", "checked")){
selectedCount++;
}
})
This returns the number of checked radio buttons:
$('input:radio:checked').length
Check if it's equal to the number of groups of radio buttons. (In your example, two.)
Fiddle
Try this solution:
function subForm() {
var valid = true;
//for every row
jQuery("tr").each(function(idx, elem) {
//checks only rows with radio inputs inside
if ($(this).find('input[type=radio]').length) {
//if there are no radios checked then form is not valid
if (!$(this).find('input[type=radio]:checked').length) {
valid = false;
}
}
});
console.log(valid);
if (valid) {
//submit form
}
}
Variable 'valid' refers to whole form being valid (at least one radiobutton is selected in each group).
Here's a jsfiddle.
Related
i have a loop in my laravel project which contain checkbox and input
#foreach($s as $sh)
<tr>
<td><input type="checkbox" name="service_id[]" class="checkser" value="{{$sh->id}}"></td>
<td class="checkservice">{{$sh->name}}</td>
<td> <input type="text" class="form-control checkser inputservice" placeholder="{{trans('home.quantity')}}" name="ser_quantity[]" ></td>
<td>{{$sh->price}}</td>
</tr>
#endforeach
i need to fill text input with (1) when checkbox checked
and empty this when checkbox unchecked
i tried many method but failed to work this with next input only
You can do this using jquery and bind a change event handler to your checkbox.
Also, use closest method.See reference here.
$('.checkser').change(function() {
if($(this).is(":checked")) {
$(this).closest('tr').find('.inputservice').val(1);
}
else
$(this).closest('tr').find('.inputservice').val('');
});
Try jQuery is() method
if($(".checkser").is(':checked'))
$(".inputservice").val(1); // checked
else
$(".inputservice").val(''); // unchecked
Just use $(selector).is(':checked')
It returns a boolean value.
I have a row in a table that gets duplicated when a button is pressed. See below:
<tr>
<td valign="top"><input type="text" name="session[]" size="15"></td>
<td valign="top"><textarea name="descr[]" cols="40" rows="5" required></textarea></td>
<td valign="top"><input id='datepick' name='sessDate[]' style='padding:5px;' size='15' required /></td>
</tr>
This all works fine. You will see that in column 3 there is a datepicker. This is controlled by:
<script type="text/javascript" src="js/datepickr.min.js"></script>
<script type="text/javascript">
new datepickr('datepick', {
'dateFormat': 'd/m/Y'
})
</script>
The first row works fine and a calendar pops up. However when I click on the button to add a new row then obviously the datepicker doesn't work as 'datepicker2' is already being used. How to I get the datepicker to work on newly generated rows? Is there anyway to do it so it picks up the array for example datepicker[] then some how in the js code it automatically add another new datepickr to the script?
I can show the code to add the new row if required, it basically just duplicates the table row.
Thanks in advance
Give class to your field.After append new row call datepicker using class.
//code for inserting newRow
$('.Yourclass').datepicker();
Insted of class you may use Id selector. Id must be unique in your form so be careful about ID.
$('input[id^=datepick]').datepicker();
So, using jQuery, one way to do it is to use a custom event that would trigger as and when a new input is added. The custom event would then, go thru all the inputs, filter out the ones that do not already have a datepickr instance, and bind the datepickr to only those inputs.
Use classes as opposed to IDs as IDs need to be unique!
$("button").on("click", function() {
$("#demo").append('<input type="text" class="datepickr" />').trigger("inputAdded");
});
$("#demo").on("inputAdded", function() {
$(this).find("input.datepickr").filter(function() {
return $(this).closest(".datepickr-wrapper").length === 0;
}).each(function() {
new datepickr(this.tagName, {
dateFormat: 'd-m-Y'
});
});
}).trigger("inputAdded");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://joshsalverda.github.io/datepickr/src/datepickr.min.css" rel="stylesheet" type="text/css"/>
<script src="http://joshsalverda.github.io/datepickr/src/datepickr.min.js"></script>
<div id="demo">
<input type="text" class="datepickr" />
<input type="text" class="datepickr" />
</div>
<button>Add more</button>
I have a list of items that need to be selected and take an action based on user's request.
User selects the items and click on one of the btns to do something on the items.
My code is as following but I am not sure how to complete it. I believe, need to put them in a form to be submitted or pass the but not sure how to have a form with two submit btns, (if I need to have ).
<body>
<p><b>Shopping cart</b></p>
<table>
<tbody>
<c:forEach items="${mycart.items}" var="item">
<tr>
<td>
<input type="checkbox" name="Items"
value="${item.ID}"/>
</td>
<td>
Name : ${item.name}
</td>
</tr>
</c:forEach>
</tbody>
</table>
checkout
Delete
you can easily have two <input type="submit" name="something" /> in one <form>
if you want to differentiate the actions, just use different name for each submit button
EDIT:
<form ...>
...
...
<input id="b1" type="submit" name="edit" value="Edit"/>
<input id="b2" type="submit" name="delete" value="Delete"/>
</form>
If the form above is submitted by clicking #b1, then your request will contain a parameter named "edit". If the submit is triggered by #b2, then it will contain "delete".
I think following script might let you obtain what items are checked.
With jQuery, you need implement your checkout() like this
function checkout() {
$('input[name="Items"]:checkbox').each(function() {
if ($(this).attr("checked")) {
alert($(this).val() + 'is checked');
} else {
alert($(this).val() + 'is not checked');
}
}
);
}
I have two separate radio button arrays that should behave as if they are one. Currently, I have it only working one way. I have a YouTube video showing my problem.
I have two mutually exclusive arrays that I want them working together as one array to the user. E.g., If one radio button is checked" in one array, I do not want the other array's radio button checked, but unchecked. JavaScript should deselect the radio button in the other array, making the functionality to look like the user is working with one set of radio buttons. The two separate radio arrays have different name=pair values.
YouTube Video Showing Problem
https://www.youtube.com/watch?v=nlvzgu3pJ8A
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
body{font-family:sans-serif, arial;}
th{text-align:left;}
h3,h4{margin-top:.15em; padding:0;}
</style>
<script>
function monthlyPlan(){
for(var i=0; i<document.deliveryForm.monthly.length;++i)
{
if(document.deliveryForm.monthly[i].checked== true )
document.deliveryForm.weekly.checked = false;
}
}
function weeklyPlan(){
for(var i=0; i<document.deliveryForm.weekly.length;++i)
{
if(document.deliveryForm.weekly[i].checked == true)
document.deliveryForm.monthly.checked = false;
}
}
</script>
</head>
<body>
<form name="deliveryForm" action="FormProcessor.html" method="get">
<h3>Delivery Rates</h3>
<h4>Allow users to select their desired delivery option.</h4>
<ul>
<li>Bill weekly or monthly</li>
<li>Devlivered Mon-Sat or Everyday</li>
</ul>
<p>
<strong>Billed continuously $3.50 by the Month?</strong>
<input type="radio" name="monthly" value="yes" onclick="monthlyPlan();" /> Yes
</p>
<strong>Billed by a Weekly Plan?</strong>
<table border=1 cellpadding=6>
<tr>
<th></th>
<th>4 weeks</th>
<th>13 weeks</th>
<th>26 weeks</th>
<th>52 weeks</th>
</tr>
<tr>
<th>Devlivered Mon-Sat</th>
<td><input type="radio" name="weekly" value="12.60" onclick="weeklyPlan();" />12.60</td>
<td><input type="radio" name="weekly" value="40.95" onclick="weeklyPlan();" />40.95</td>
<td><input type="radio" name="weekly" value="81.90" onclick="weeklyPlan();" />81.90</td>
<td><input type="radio" name="weekly" value="156.00" onclick="weeklyPlan();" />156.00</td>
</tr>
<th>Devlivered Everyday</th>
<td><input type="radio" name="weekly" value="13.56" onclick="weeklyPlan();" />13.56</td>
<td><input type="radio" name="weekly" value="44.07" onclick="weeklyPlan();" />44.07</td>
<td><input type="radio" name="weekly" value="88.14" onclick="weeklyPlan();" />88.14</td>
<td><input type="radio" name="weekly" value="159.74" onclick="weeklyPlan();" />159.74</td>
</tr>
</table>
</form>
</body>
</html>
Try this:
function monthlyPlan() {
for (var i = 0; i < document.deliveryForm.weekly.length; ++i) {
document.deliveryForm.weekly[i].checked = false;
}
}
function weeklyPlan() {
document.deliveryForm.monthly.checked = false;
}
Demo: http://jsfiddle.net/DpbMB/
You don't need to test whether the radio that was just clicked is checked, because for radio buttons you know they will be checked when the click event occurs (there's no way to uncheck them by clicking except by clicking on another in the group, and then it is the other that gets the event).
When the monthly radio button is clicked, loop over all of the weekly radio buttons and set them to not be checked. When any weekly radio is clicked simply uncheck the monthly one.
The array-style access is only applicable when there is more than one element with the same name, so to access the monthly button don't use [i].
It seems to me though that it would be easier to just make the monthly button part of the same group, and give it an appropriate value that you can test server-side.
Try the following for your monthlyPlan() function:
function monthlyPlan(){
/*for(var i=0; i<document.deliveryForm.monthly.length;++i)
{
if(document.deliveryForm.monthly.checked== true )
document.deliveryForm.weekly.checked = false;
}
*/
alert(document.deliveryForm.monthly.length); // will say undefined
if (document.deliveryForm.monthly.checked)
{
for (var k = 0; k < document.deliveryForm.weekly.length; ++k)
{
document.deliveryForm.weekly[k].checked = false;
}
}
}
It appears that when you only have one radio button in the group, the DOM doesn't treat it as an array.
EDIT: Actually, nnnnnn's answer is better. No point keeping the redundant if statements.
I have this table containing 3 radio buttons, I want to find out whether a particular radio button is check or not at given point of time.
<table align="center" width="100%" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="compareRadio" value="all" checked="checked"/>
<label>View All Records</label>
</td>
<td>
<input type="radio" name="compareRadio" value="diff" />
<label>View Differences</label>
</td>
<td>
<input type="radio" name="compareRadio" id="patch" value="patches" />
<label>Compare Patches</label>
</td>
<td>
<input type="button" class="btn" value="Export Into Excel"/>
</td>
</tr>
</tbody>
</table>
I send a request to the server, when the result comes back I want to identify whether patches radio button is selected or not.
So I did something like this.. but it returns all radio button
$.post("/csm/compare.action",
{
sessiontoken: sessiontoken,
compareCategory: "system",
compareSubCategory:"patch",
xml1:absP[0],
xml2:absP[1]},
function(resdata)
{
comparePatchData=resdata;
comparePatchLoading=false;
if($("input:radio[name=compareRadio]").val()=="patches")
{
//Trigger click on radio button for "same" campare
$('input[name=compareRadio]:eq(2)').click(); //so that it refreshes the content
$("input[name=compareRadio]:eq(2)").attr("checked", true);
$('input[type="radio"]').removeAttr('disabled');
}
}
);
If you just want to know if it is checked or not, then you could do this:
if($('#patch:checked').length)
// It is checked.
Or:
if($('input[value=patches]:checked').length)
// It is checked.
The $() function returns an array of matched elements so you can check its length property to see how many things (if any) were matched.
References:
:checked selector
Attribute equals selector
To find out if particular checkbox is checked you can use jQuery's is():
if($('input[value=all]').is(':checked'))
{
//Yep, it's checked
}