JQuery - radio button CSS not refreshing after submit - html

I have a form with twitter bootstrap buttons as below
<label class="control-label span3">Status of the Dispute? </label>
<div class="controls span7">
<label class="inline radio">
<input type="radio" id="status" name="status" value="Continue"/> Continue</label>
<label class="inline radio">
<input type="radio" id="status" name="status" value="Resolved"/>Resolved</label>
<label class="inline radio">
<input type="radio" id="status" name="status" value="Referred"/> Referred</label>
<label for="status" class="error">Please tell us the dispute status</label>
</div>
</div>
Upon submission, the form submits the data successfully and refreshes well all other elements except the radio buttons.
I've searched for various options, and came along prop function. It helped me to somepoint as it unchecks the selector on the inside. CSS stylsheet on the user page still remain as if it is selected.
$('input[name="status"]').prop('checked', false);
I also tried this idea
$('input:not(:checked)').parent().removeClass("inline radio");
but its still not successfull.
My full submit code is as follows:
$.validator.setDefaults({
submitHandler: function(form) {
$.post('registermyform.php',
$("#registermyform").serialize(),
function(data)
{
$('#results').html(data);
if (data="yes"){
alert("The new Dispute has been successfully submitted!");
$('#registerDispute')[0].reset();
$('input[name="status"]').prop('checked', false);
$('input:checked').parent().removeClass("inline radio");
}
else {
alert("not submitted!");
}
});
}
});
Please assist. I want to remove the CSS of radio buttons such that it doesn't appear as if it is checked while it is not.

You need to iterate through the elements to reset them all:
var $items = $('input[name="status"]');
for (var i = 0; i < $items.length; i++) {
$($items[i]).prop('checked', false);
}

Related

Select a random element from a dynamic array in HTML

I'd like to add HTML to a Google Site that allows a user to press a button that displays a random letter of the alphabet. However, it should randomize only the letters that the user selects through checkboxes. Below is an image of what I'd like to achieve, and I'd like the result to display to the right of the checkbox array.
As to what I have tried so far, I have the following code that I modified from an open source online. I hope it is ok for my purpose.
<!DOCTYPE html>
<html>
<body>
<h1>Pick Letters To Randomize</h1>
<form action="/action_page.php">
<input type="checkbox" id="letter1" name="letter1" >
<label for="letter1"> A</label><br>
<input type="checkbox" id="letter2" name="letter2" >
<label for="letter2"> B</label><br>
<input type="checkbox" id="letter3" name="letter3" >
<label for="letter3"> C</label><br><br>
<input type="submit" value="Randomize">
</form>
</body>
</html>
But I am really at a loss for how to solve the rest of my problem.
Here is a working example for you. I have a few suggestions that I've implemented that will make this easier for you:
Add a value to the checkbox input. That way, you don't have to grab a child/sibling label.
I've added comments to show what I'm doing. Hope that helps!
document.addEventListener("DOMContentLoaded", function() {
const form = document.getElementById("randomLetterForm");
const submitBtn = document.getElementById("randomSubmit");
const textResult = document.getElementById("result");
// We check the values on the submit click
submitBtn.addEventListener("click", function(e) {
// Prevent it from *actually* submitting (e.g. refresh)
e.preventDefault();
// Grab *all* selected checkboxed into an array
const items = document.querySelectorAll("#randomLetterForm input:checked");
// Checking if it's not empty
if (items.length > 0) {
// Setting a random index from items[0] to items[items.length]
textResult.innerHTML = items[Math.floor(Math.random() * items.length)].value;
} else {
// If not, we alert
alert("Please choose at least 1 number");
}
});
});
<h1>Pick Letters To Randomize</h1>
<form id="randomLetterForm" action="/action_page.php">
<input type="checkbox" value="A" id="letter1" name="letter1" >
<label for="letter1"> A</label><br>
<input type="checkbox" value="B" id="letter2" name="letter2" >
<label for="letter2"> B</label><br>
<input type="checkbox" value= "C" id="letter3" name="letter3" >
<label for="letter3"> C</label><br><br>
<input id="randomSubmit" type="submit" value="Randomize">
</form>
<div>
<p id="result"></p>
</div>

AngularJS validation message and showing no results and results div issue on submit

The following form shows a list of data on submit. I am trying to show no results found when there is no data on submit. I tried like shown below,it shows and hides the div. But when there is no options selected on form and click submit button it shows the no result div.How to show the no results div only when form validation succeeds and there is no data to display.
HTML
<div class="form-group" >
<label class="radio-inline">
<input name="sampleinlineradio" value="3" type="radio" ng-model="radioption"
ng-required="!radioption"> MAIN 1</label>
<label class="radio-inline">
<input name="sampleinlineradio" value="1" type="radio" ng-model="radioption" >
Main 2</label>
<div ng-show="!radioption && buttonClicked">Please select one.</div>
</div>
<div class="form-group">
<label ng-repeat="branch in branches">
<input type="checkbox" name="selectedBranches[]" value="{{branch.value}}"
ng-model="branch.selected" ng-required="isOptionsRequired()" >
{{branch.name}}</label>
<div ng-show="isOptionsRequired() && buttonClicked">Please select one.</div>
</div>
<input type="button" ng-click="fetchresults()" value="submit" >
<div ng-show="buttonClicked">
<table> <thead>.....</thead>
<tbody>
<tr ng-show="results.length!=0" ng-repeat="r in results">
<td></td></tbody></table>
</div>
<div ng-show="buttonClicked">
<span ng-show="results.length==0 ">No results.</span>
</div>
Minimal Controller Code
$scope.fetchresults = function(){
$scope.results = Result.query({main: $scope.radioption, branch: $scope.selection[0], });
$scope.buttonClicked = true;
}
EDIT:
I used model to validate and $valid is also working, as suggested below.But Got a couple of glitches. If i click the button it does not show div. but after validation is over it shows automatically "no results" from the click before. How to stop this.And while it lists data when its available it shows "no results" for a second or so
Give your form a name
<form name="formName">
Then you can do
ng-show="results.length==0 && formName.$valid"
Some more information on angularJS form validation
You can check the below snippet, I have changed most of them in angular way with $invalid, $pristine, $submitted and $valid.
You can check the angular documentation to read about them.
Link 1, Link 2
Note: You can use a submit button and get rid of ng-click event and use ng-submit instead which can't be used in this snippet as form submit is not allowed. Comment the line form.$submitted = true; when you use a submit button.
var app = angular.module('app', []);
app.controller('TestController', function($scope){
$scope.isFieldInvalid = function(field) {
var form = $scope.testForm;
return form[field].$invalid && (!form[field].$pristine || form.$submitted);
};
$scope.fetchResults = function(){
var form = $scope.testForm;
form.$submitted = true; // comment this line if button type="submit"
if(form.$valid){
$scope.searching = true;
$scope.results = [];
var rnd = Math.random();
if(rnd >= 0.5) {
$scope.results = [{id: 1}, {id: 2}];
}
//$scope.results = Result.query({main: $scope.radioption, branch: $scope.selection[0], });
$scope.buttonClicked = true;
$scope.searching = false;
}
};
});
angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form name="testForm" ng-controller="TestController" ng-submit="fetchResults()" role="form" novalidate="">
<div class="form-group" ng-controller="TestController">
<label class="radio-inline">
<input name="sampleinlineradio" value="3" type="radio" ng-model="radioption" ng-required="true"> MAIN 1</label>
<label class="radio-inline">
<input name="sampleinlineradio" value="1" type="radio" ng-model="radioption" ng-required="true" >
Main 2</label>
<div ng-show="isFieldInvalid('sampleinlineradio')">Please select one.</div>
</div>
<div class="form-group">
<label ng-repeat="branch in branches">
<input type="checkbox" name="selectedBranches[]" value="{{branch.value}}"
ng-model="branch.selected" ng-required="isOptionsRequired()" >
{{branch.name}}</label>
<div ng-show="isOptionsRequired() && buttonClicked">Please select one.</div>
</div>
<input type="button" value="submit" ng-click="fetchResults()" >
<div ng-show="buttonClicked && !searching">
<table> <thead></thead>
<tbody>
<tr ng-show="results.length!=0" ng-repeat="r in results">
<td>{{r.id}}</td></tbody></table>
</div>
<div ng-show="buttonClicked && !searching">
<span ng-show="results.length==0 ">No results.</span>
</div>
</form>

HTML form action on part of form

I'm making a form and want something to happen when just a certain part of the form has been completed. I've got some checkboxes, a dropdown menu, and three read-only text fields. I need something to pop up when the checkboxes and dropdown fields have been populated, but have no idea how to do this. I tried putting a form within a form, but after that failed and I later read up on the matter, I found that to be impractical. Anyhow, here's my code for the form:
<form action="http://siedb1.sys.virginia.edu/~jhr3ct/Code/Reserve%20Confirmation.php">
Facility: <input type="checkbox" name="facility" value="AFC">AFC
<input type="checkbox" name="facility" value="Memorial Gym">Memorial Gym
<input type="checkbox" name="facility" value="Slaughter">Slaughter
<input type="checkbox" name="facility" value="North Grounds">North Grounds<br>
Type of Room/Court:
<select>
<option value="default">Choose room...</option>
<option value="squash">Squash</option>
<option value="handball">Handball</option>
<option value="racquetball">Racquetball</option>
<option value="multipurpose">Multipurpose</option>
</select><br>
Room: <input type="text" name="start" readonly="readonly"><br>
Start Time: <input type="text" name="start" readonly="readonly"><br>
End Time: <input type="text" name="end" readonly="readonly"><br><br>
<input id="submit" type="submit" value="Submit">
</form>
Thanks for the help!
You might be interested in learning basic javascript form events. There is many tutorials on internet. I suggest you this one: http://www.javascriptkit.com/jsref/select.shtml
If you need to show a popup after all check boxes are checked and the dropdown is changed add this kind of a function to the onclick events of all the check boxes and onchange event of the dropdown box.
function func() {
var inputTags = document.getElementsByTagName('input');
var dropdowns = document.getElementsByTagName('SELECT');
for (var i = 0; i < inputTags.length; i++) {
if (inputTags[i].type == 'checkbox') {
var aCheckBox = inputTags[i];
if(!aCheckBox.checked) {
return;
}
}
}
if(dropdowns[0].value == 'default') {
return;
}
alert("All checkboxes and dropdowns are filled.");
}
<form action="../Confirmation.php">
<input onclick="func()" type="checkbox" name="facility" value="AFC">AFC
<input onclick="func()" type="checkbox" name="facility" value="Slaughter">Slaughter
<select onchange="func()" id="ss">
</form>
Just to point you in the right direction: You will have to use javascript to check your form inputs values, and to show a pop-up window.
You could use jQuery to do that easily, and make a listener for the form submit() action, where you could check if your checkboxes and dropdown are selected.
The jQuery doc is here: http://api.jquery.com/submit/

Linking radio buttons and text inputs

I am trying to associate a radio input with a specified text input. As you can see in the picture, there are two options. I know I can use for="" to associate the label to the radio input, but how can I also associate it to the text input underneath, and vise versa so when I focus on the text input, if focuses the correct radio button?
NOTE: The amount entered will be inserted into the database, so that's the most important part of this form. Currently if I click on $Off, I can still enter a number in %Off. I don't want this to happen, so the user does not get confused.
My markup:
<div class="row-fluid control-group">
<div class="span7 pull-left">
<label class="radio" for="discount-dollars">
<input type="radio" name="discount" id="discount-dollars" value="dollars" checked="checked">
$ Off
</label>
<div class="input-append">
<input type="text" name="discount-dollars-amount" id="discount-dollars-amount" class="input-small dollars" placeholder="enter amount">
<span class="add-on">.00</span>
</div>
</div><!-- .span7 .pull-left -->
<div class="span5">
<label class="radio" for="discount-percent">
<input type="radio" name="discount" id="discount-percent" value="percent">
% Off
</label>
<input type="text" name="discount-percent-amount" id="discount-percent-amount" class="input-small percent" placeholder="enter amount" disabled="disabled">
</div>
</div><!-- .row-fluid .control-group -->
<script type="text/javascript">
$(function (){
$("form input[type=radio]").click(function (){
// get the value of this radio button ("dollars" or "percent")
var value = $(this).val();
// find all text fields...
$(this).closest("form").find("input[type=text]")
// ...and disable them...
.attr("disabled", "disabled")
// ...then find the text field whose class name matches
// the value of this radio button ("dollars" or "percent")...
.end().find("." + value)
// ...and enable that text field
.removeAttr("disabled")
.end();
});
});
</script>
You can't use a single <label> element to label two separate inputs. I would suggest associating the labels to the radio buttons, since the radio button is such a small click target and the label expands that target.
Choose one of the radios to be selected by default, perhaps "$ Off". Disable the other text field by default:
<div class="row-fluid control-group">
<div class="span7 pull-left">
<label class="radio" for="discount-dollars">
<input type="radio" name="discount" id="discount-dollars" value="dollars" checked="checked">
$ Off
</label>
<div class="input-append">
<input type="text" name="discount-dollars-amount" id="discount-dollars-amount" class="input-small dollars" placeholder="enter amount">
<span class="add-on">.00</span>
</div>
</div><!-- .span7 .pull-left -->
<div class="span5">
<label class="radio" for="discount-percent">
<input type="radio" name="discount" id="discount-percent" value="percent">
% Off
</label>
<input type="text" name="discount-percent-amount" id="discount-percent-amount" class="input-small percent" placeholder="enter amount" disabled="disabled">
</div>
</div><!-- .row-fluid .control-group -->
Then use jQuery to do something like this:
$(function (){
$("#discount-dollars, #discount-percent").click(function (){
// get the value of this radio button ("dollars" or "percent")
var value = $(this).val();
// find all text fields...
$(this).closest(".control-group").find("input[type=text]")
// ...and disable them...
.attr("disabled", "disabled")
// ...then find the text field whose class name matches
// the value of this radio button ("dollars" or "percent")...
.end().find("." + value)
// ...and enable that text field
.removeAttr("disabled")
.end();
});
});
Basically, this listens for click events on both radio buttons. When you click one radio, it enables its associated text field (i.e., the text field with a CSS class name matching the value of the radio button) and disables the other text field. That way, you can't enter text into either text field unless its associated radio button is checked.
use image radio button with 2 states, selected and not selected, when you click the radio image just set focus to the textbox and swap to your selected radio image, and vice versa.
You cannot focus on two elements, it will be either the input text field or the radio button.
But you should use JavaScript or jQuery, when you click on the radio button to focus on the field below, or when you enter value in the field below to check the radio button above.
This can help you if you want to use jquery : http://api.jquery.com/val/ and http://api.jquery.com/focus/
This is a VERY rough sketch to help you out, but you could do something like this (giving you follow a certain naming convention):
<input type="radio" name="rGroup" id="radioDollarOff" onclick="changeMe(this);"/> <input type="text" name="textDollarOff" id="textDollarOff" onclick="changeMe(this);"/>
<br />
<input type="radio" name="rGroup" id="radioPctOff" onclick="changeMe(this);"/> <input type="text" name="textPctOff" id="textPctOff" onclick="changeMe(this);"/>
<script>
function changeMe(inField) {
var fieldId = inField.id;
var type = fieldId.substring(0, 4);
if(type == 'text') {
var name = fieldId.substring(4);
var radioButton = document.getElementById("radio" + name);
radioButton.checked = true;
}else {
var name = fieldId.substring(5);
var textField = document.getElementById("text" + name);
textField.focus();
}
}
</script>
jQuery is what you want. Assuming your elements had IDs as follows:
$ radio button: money-radio
$ text box: money-text
% radio button: percent-radio
% text box: percent-text
...the code might look something like this. This will take care of disabling text boxes and focusing input properly.
<form>
<table>
<tr>
<td>
<input type="radio" id="money-radio" name="unit" value="money" />
<label for="money-radio">$ Off</label>
</td>
<td>
<input type="radio" id="percent-radio" name="unit" value="percent" />
<label for="percent-radio">% Off</label>
</td>
</tr>
<tr>
<td>
<input type="text" id="money-text" name="money-off" />
</td>
<td>
<input type="text" id="percent-text" name="percent-off" />
</td>
</tr>
</table>
</form>
<script type="text/javascript">
$(function() {
$('#percent-radio, #money-radio').change(function() {
if ($('#percent-radio').val() == true) {
$('#percent-text').removeAttr('disabled').focus();
} else {
$('#percent-text').attr('disabled', 'disabled');
}
if ($('#money-radio').val() == true) {
$('#money-text').removeAttr('disabled').focus();
} else {
$('#money-text').attr('disabled', 'disabled');
}
}).change();
});
</script>

How can I prevent a user from selecting multiple checkboxes in HTML?

How can I prevent a user from selecting multiple checkboxes in HTML?
you should change it to radio button instead of check box!
<input type="radio" name="group1" id="item1" value="Milk">
<label for="item1">Milk</label>
<br/>
<input type="radio" name="group1" id="item2" value="Butter" checked>
<label for="item2">Butter</label>
<br/>
<input type="radio" name="group1" id="item3" value="Cheese">
<label for="item13">Cheese</label>
I had a use case where I needed use checkboxes--which, unlike radio buttons, allows a user to UNcheck... Here's an example of something I pieced together from another stackoverflow user:
<head>
<meta charset=utf-8 />
<title>and-or checkboxes</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<label for="checkbox1"><input type="checkbox" id="checkbox1" name="checkbox1" value="and" </label><span id="span_and">checkbox1</span><br>
<label for="checkbox2"> <input type="checkbox" id="checkbox2" name="checkbox2" value="or" </label><span id="span_or">checkbox2</span>
<script>
$(document).ready(function(){
$('#checkbox1').click(function() {
var checkedBox = $(this).attr("checked");
if (checkedBox === true) {
$("#checkbox2").attr('checked', false);
} else {
$("#checkbox2").removeAttr('checked');
}
});
});
$(document).ready(function(){
$('#checkbox2').click(function() {
var checkedBox = $(this).attr("checked");
if (checkedBox === true) {
$("#checkbox1").attr('checked', false);
} else {
$("#checkbox1").removeAttr('checked');
}
});
});
</script>
</body>
With a little work, you can combine the either/or two scripts into a single script. You probably don't need this now but I wanted to post it because it was very useful to me.
If you want that only one checkbox get selected at a time then its better to use radiobutton instead.
If you mean that you don't want multiple checkboxes from a same "logical group" to be checked at one time, you should use radio buttons instead of checkboxes.
<form>
<input type="radio" name="aGroup" value="choice1" /> Choice #1<br />
<input type="radio" name="aGroup" value="choice2" /> Choice #2
</form>
By using this, only 1 option can be checked at one time
Use Radio, and they must have the same name="".