Keep checkbox checked AND only check 1 checkbox per group - forms

I'm looking to combine two things:
a) ensure that when a checkbox is checked, it remains checked after submit, AND
b) only allow one checkbox per group (e.g. the one below) be allowed to be checked at once. I can't use radio buttons unfortunately!
I can do a) & b) in isolation but unfortunately can't seem to combine them! Please help?
<form>
<input type="checkbox" name="a" value="low" <?php if(isset($_POST['a'])) echo "checked='checked'"; ?>/>
<input type="checkbox" name="b" value="mid" <?php if(isset($_POST['b'])) echo "checked='checked'"; ?>/>
<input type="checkbox" name="c" value="hi" <?php if(isset($_POST['c'])) echo "checked='checked'"; ?>/>
</form>

Using jQuery, I was able to create a function that will allow only one checkbox to be clicked at a time.
$('.check').click(function(){
if($('.check:checked').length == 1){
$('.check:not(:checked)').attr('disabled',true);
}
else if($('.check:checked').length == 0){
$('.check:not(:checked)').removeAttr('disabled');
}
});
<p>Check a box</p>
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
DEMO

Related

Passing Text into URL from a Form

I'm trying to insert a variable collected from a form into a URL, but I don't want the "?variable=value" part of the URL.
<form action="http://www.example.com/<?php echo htmlspecialchars($_GET['entry']);?>/" method="GET">
<input type="text" value="" name="entry" id="entry">
<input type='submit'>
</form>
Is there any easy way to do this? I want the browser to go to the following URL when the user types "whatever"
http://www.example.com/whatever/
Edit:
I've changed the code to the following, which seems to work, but have I now introduced a script vulnerability?
<form onSubmit=" location.href = 'https://www.example.com/' + document.getElementById('entry').value + '/' ; return false; ">
<input type="text" value="" name="entry" id="entry" placeholder="Your Promo Code">
<input name="promoSubmit" type="submit" value="Buy Now">
</form>
you could use javascript for this kind of tasks, i don't see why would you involve server side for such thing
but the easiest answer will be like:
<script>
function go(){
window.location='http://www.example.com/'+document.getElementById('url').value;
}
</script>
<input type='text' id='url'>
<button id='btn_go' onclick='javascript:go();'>Go</button>

Parsley checkbox validate: can't get working

Here's what I have, below, trying to use bits from similar answers here, plus items from the parsley site.. Nothing happens..User is not alerted that at least 1 box must be checked. Do I have this all wrong? Thank you in advance for any clues!
<form action="success.html" id="contact-form" data-parsley-validate>
<label for="language">Please Choose your Language:<br>
<input type="checkbox" class="checkbox" name="language" value="english" parsley-group="language" parsley-mincheck="1">English<br>
<input type="checkbox" class="checkbox" name="language" value="spanish" parsley-group="language" >Spanish<br>
<input type="checkbox" class="checkbox" name="language" value="french" parsley-group="language" >French
</label>
You have some problems with your code:
parsley-group doesn't exist. There is a data-parsley-group and is applicable if you want to validate a portion of your form.
parsley-mincheck="1" doesn't exist. There is a data-parsley-mincheck="1".
Assuming that you require at least one language, but can accept more, this code should do the trick:
<form action="success.html" id="contact-form" data-parsley-validate>
<label for="language">Please Choose your Language:<br>
<input type="checkbox" class="checkbox" name="language[]"
value="english" required>English<br>
<input type="checkbox" class="checkbox" name="language[]"
value="spanish" required>Spanish<br>
<input type="checkbox" class="checkbox" name="language[]"
value="french" required >French</label>
<button type="submit" id="submit-button">Submit form</button>
</form>
$(document).ready(function() {
// bind parsley to the form
$("#contact-form").parsley();
// on form submit, validate form and, if valid, show valid in the console
$("#contact-form").submit(function() {
$(this).parsley("validate");
if ($(this).parsley("isValid")) {
console.log('valid');
}
event.preventDefault();
});
});
If you want the user to select one and only one option, I advice you to use radio buttons.

How do i merge 2 web forms into 1?

I need to merge these 2 forms into 1 so it passes the email address to all 3 sources.
Is it possible?
Form 1:
<form method="post" id="transparent_redirect_form" name="transparent_redirect_form" action="https://joinalpha.com/launch/signup.php/taster">
<input type="text" id="signup_email_address" name="signup_email_address" placeholder="you#business.com" />
<input type="submit" value="Subscribe" />
</form>
Form 2:
<form method="post" action="http://joinalpha.com/blog/signup/"><input type="hidden" name="ip" value="213.106.180.209" />
<input type="text" name="email" id="s2email" value="you#business.com" onfocus="if (this.value == 'you#business.com') {this.value = '';}" onblur="if (this.value == '') {this.value = 'you#business.com';}" />
<input type="submit" name="subscribe" value="Subscribe" />
</form>
Each form has only one field and one action - to send the email address somewhere...
Any clues how i do this?
I would suggest to use javascript.
Create a button or something outside of the form, then invoke the submit of the form, then use the DOM to change the action in the form, and call submit again.

JSP - check form submission

Let say I have a simple form with no required fields:
<form action="index.jsp" method="post">
<input type="text" name="firstName" />
<input type="text" name="lastName" />
<input type="text" name="email" />
<input type="submit" value="submit" />
</form>
I want to check if the form was submitted by checking the submit parameter (because it's always present). In PHP I can do a simple
if ( $_POST['submit'] )
but the request.getParameter("submit") doesn't seem to work.
So what's the best way to check if a form was submitted?
You need to give the input element a name. It's the element's name which get sent as request parameter name.
<input type="submit" name="submit" value="submit" />
Then you can check it as follows:
if (request.getParameter("submit") != null) {
// ...
}
You perhaps also want to check if "POST".equalsIgnoreCase(request.getMethod()) is also true.
if ("POST".equalsIgnoreCase(request.getMethod()) && request.getParameter("submit") != null) {
// ...
}
Better, however, would be to use a servlet and do the job in doPost() method.
You can try this way:-
if ("POST".equalsIgnoreCase(request.getMethod())) {
// Form was submitted.
} else {
// It may be a GET request.
}

Required attribute on multiple checkboxes with the same name? [duplicate]

This question already has answers here:
Using the HTML5 "required" attribute for a group of checkboxes?
(16 answers)
Closed 6 years ago.
I have a list of checkboxes with the same name attribute, and I need to validate that at least one of them has been selected.
But when I use the html5 attribute "required" on all of them, the browser (chrome & ff) doesn't allow me to submit the form unless all of them are checked.
sample code:
<label for="a-0">a-0</label>
<input type="checkbox" name="q-8" id="a-0" required />
<label for="a-1">a-1</label>
<input type="checkbox" name="q-8" id="a-1" required />
<label for="a-2">a-2</label>
<input type="checkbox" name="q-8" id="a-2" required />
When using the same with radio inputs, the form works as expected (if one of the options is selected the form validates)
According to Joe Hopfgartner (who claims to quote the html5 specs), the supposed behaviour is:
For checkboxes, the required attribute shall only be satisfied when one or more of the checkboxes with that name in that form are checked.
For radio buttons, the required attribute shall only be satisfied when exactly one of the radio buttons in that radio group is checked.
am i doing something wrong, or is this a browser bug (on both chrome & ff) ??
You can make it with jQuery a less lines:
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
With $(':checkbox[required]') you select all checkboxes with the attribute required, then, with the .change method applied to this group of checkboxes, you can execute the function you want when any item of this group changes. In this case, if any of the checkboxes is checked, I remove the required attribute for all of the checkboxes that are part of the selected group.
I hope this helps.
Farewell.
Sorry, now I've read what you expected better, so I'm updating the answer.
Based on the HTML5 Specs from W3C, nothing is wrong. I created this JSFiddle test and it's behaving correctly based on the specs (for those browsers based on the specs, like Chrome 11 and Firefox 4):
<form>
<input type="checkbox" name="q" id="a-0" required autofocus>
<label for="a-0">a-1</label>
<br>
<input type="checkbox" name="q" id="a-1" required>
<label for="a-1">a-2</label>
<br>
<input type="checkbox" name="q" id="a-2" required>
<label for="a-2">a-3</label>
<br>
<input type="submit">
</form>
I agree that it isn't very usable (in fact many people have complained about it in the W3C's mailing lists).
But browsers are just following the standard's recommendations, which is correct. The standard is a little misleading, but we can't do anything about it in practice. You can always use JavaScript for form validation, though, like some great jQuery validation plugin.
Another approach would be choosing a polyfill that can make (almost) all browsers interpret form validation rightly.
To provide another approach similar to the answer by #IvanCollantes.
It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked checkbox.
jQuery(function($) {
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.on('change', function(e) {
var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');
var isChecked = checkboxGroup.is(':checked');
checkboxGroup.prop('required', !isChecked);
});
requiredCheckboxes.trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form target="_blank">
<p>
At least one checkbox from each group is required...
</p>
<fieldset>
<legend>Checkboxes Group test</legend>
<label>
<input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1
</label>
<label>
<input type="checkbox" name="test[]" value="2" required="required">test-2
</label>
<label>
<input type="checkbox" name="test[]" value="3" required="required">test-3
</label>
</fieldset>
<br>
<fieldset>
<legend>Checkboxes Group test2</legend>
<label>
<input type="checkbox" name="test2[]" value="1" required="required">test2-1
</label>
<label>
<input type="checkbox" name="test2[]" value="2" required="required">test2-2
</label>
<label>
<input type="checkbox" name="test2[]" value="3" required="required">test2-3
</label>
</fieldset>
<hr>
<button type="submit" value="submit">Submit</button>
</form>
i had the same problem, my solution was apply the required attribute to all elements
<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>
when the user check one of the elements i remove the required attribute from all elements:
var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
$checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');
$checkboxes.click(function() {
if($checkedCheckboxes.length) {
$checkboxes.removeAttr('required');
} else {
$checkboxes.attr('required', 'required');
}
});
Here is improvement for icova's answer. It also groups inputs by name.
$(function(){
var allRequiredCheckboxes = $(':checkbox[required]');
var checkboxNames = [];
for (var i = 0; i < allRequiredCheckboxes.length; ++i){
var name = allRequiredCheckboxes[i].name;
checkboxNames.push(name);
}
checkboxNames = checkboxNames.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
for (var i in checkboxNames){
!function(){
var name = checkboxNames[i];
var checkboxes = $('input[name="' + name + '"]');
checkboxes.change(function(){
if(checkboxes.is(':checked')) {
checkboxes.removeAttr('required');
} else {
checkboxes.attr('required', 'required');
}
});
}();
}
});
A little jQuery fix:
$(function(){
var chbxs = $(':checkbox[required]');
var namedChbxs = {};
chbxs.each(function(){
var name = $(this).attr('name');
namedChbxs[name] = (namedChbxs[name] || $()).add(this);
});
chbxs.change(function(){
var name = $(this).attr('name');
var cbx = namedChbxs[name];
if(cbx.filter(':checked').length>0){
cbx.removeAttr('required');
}else{
cbx.attr('required','required');
}
});
});
Building on icova's answer, here's the code so you can use a custom HTML5 validation message:
$(function() {
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function() {
if (requiredCheckboxes.is(':checked')) {requiredCheckboxes.removeAttr('required');}
else {requiredCheckboxes.attr('required', 'required');}
});
$("input").each(function() {
$(this).on('invalid', function(e) {
e.target.setCustomValidity('');
if (!e.target.validity.valid) {
e.target.setCustomValidity('Please, select at least one of these options');
}
}).on('input, click', function(e) {e.target.setCustomValidity('');});
});
});
var verifyPaymentType = function () {
//coloque os checkbox dentro de uma div com a class checkbox
var inputs = window.jQuery('.checkbox').find('input');
var first = inputs.first()[0];
inputs.on('change', function () {
this.setCustomValidity('');
});
first.setCustomValidity( window.jQuery('.checkbox').find('input:checked').length === 0 ? 'Choose one' : '');
}
window.jQuery('#submit').click(verifyPaymentType);
}