Make invalid form immediately after loading - javascript

I have a simple form written in AngularJS.
I would like to make the form invalid immediately after loading. Unfortunately $scope.myForm.$valid = false; doesn't want work. Do you have any other technique to do it? It is important for me as I want to let user click the button only when he/she choose at least on checkbox. Now you can submit the form always after loading the form.
<form name="myForm" ng-submit="myForm.$valid">
<input type="checkbox" ng-model="obj.first" ng-change="onChange()" /> First <br />
<input type="checkbox" ng-model="obj.second" ng-change="onChange()"/>Second <br />
<input type="checkbox" ng-model="obj.third" ng-change="onChange()"/> Third <br>
<button type="submit" ng-disabled="!myForm.$valid" ng-click="click()">test</button> <br>
</form>
$scope.myForm = {};
$scope.myForm.$valid = false;
$scope.click=function () {
console.log('-------------2', $scope.myForm);
};
$scope.onChange=function () {
console.log('before:', $scope.myForm);
var isValid = false;
angular.forEach($scope.obj, function(value, key) {
if(value == true){
isValid=true;
}
console.log(key + ': ' + value);
});
if(!isValid){
$scope.myForm.$valid = false;
$scope.myForm.$error.checkBoxes = {
isChecked: false
};
}
console.log('after:', $scope.myForm);
}

So this is my final solution, the form in the scope has a function called $setValidity() where we can change the validity state, and notify the form. Refer here, so I check if any of the checkboxes are having true value, then I set the value for one checkbox alone as true, if not then one of the checkboxes with name one is set to $valid = false, thus the entire form will be invalid, please go through my code for the implementation of the solution!
JSFiddle Demo
JS:
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.onChange = function() {
if ($scope.obj) {
if ($scope.obj.first || $scope.obj.second || $scope.obj.third) {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", true);
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
}
});

Try this in your submit button. hope it works
data-ng-disabled="myForm.$submitted || myForm.$invalid && !myForm.$pristine"

Related

Validation on input field using javascript

I wants to check, if entered field's value is valid or not using onchange before submitting the page. I have written like below.It validates well.But how to activate 'NEXT' button when there is no error on input entries.
<div><input type="text" name="your_name" id="your_name" onchange = "validate_Name(this,1,4)" />
<span id="your_name-error" class="signup-error">*</span>
</div>
<div><input type="text" name="your_addr" id="your_addr" onchange = "validate_Name(this,1,4)" />
<span id="your_addr-error" class="signup-error">*</span>
</div>
<input class="btnAction" type="button" name="next" id="next" value="Next" style="display:none;">
<script type="text/javascript" src="../inc/validate_js.js"></script>
<script>
$(document).ready(function() {
$("#next").click(function() {
var output = validate(); //return true if no error
if (output) {
var current = $(".active"); //activating NEXT button
} else {
alert("Please correct the fields.");
}
});
}
function validate() {
//What should write here?I want to analyse the validate_js.js value here.
}
</script>
Inside validate_js.js
function validate_Name(inputVal, minLeng, maxLeng) {
if (inputVal.value.length > maxLeng) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Max Characters:" + maxLeng;
} else if (!(tBox.value.match(letters))) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Use only a-zA-Z0-9_ ";
} else {
inputVal.style.background = "white";
inputVal.nextElementSibling.innerHTML = "";
}
}
If by "activating" you want to make it visible, you can call $('#next').show().
However if you want to simulate a click on it, with jQuery you can simply call $('#next').click() or $('#next').trigger('click') as described here. Also, you might want to put everything in a form and programmatically submit the form when the input passes validation.
You could possibly trigger the change event for each field so it validates each one again.
eg.
function validate() {
$("#your_name").trigger('change');
$("#your_addr").trigger('change');
}

Checkbox check event is not getting prevented

I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function () {
return this.value;
}).get();
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
alert(checkedReportValues);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created HTML.
//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above
var Reports = " User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#ReportRow').on('click', 'input[type="checkbox"]',function(){
$('#ReportRow input[type="checkbox"]').not(this).prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReportRow">
<input type="checkbox">one
<input type="checkbox">Two
<input type="checkbox">Three
<input type="checkbox">Four
</div>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var curCheckBox = this;
$('#ReportRow').find('input[type="checkbox"]').each(function() {
if(this === curCheckBox)
$(this).attr("checked",true);
else
$(this).attr("checked",false);
});
alert(checkedReportValues);
});

Get value from textbox based on checkbox on change event

I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">

Not returning a value for some reason

Basically I have a script the function "hola ()" that should return the value of 1 if the radio button value is 1. But for some reason when I try to get the return value in another function i never get it.
The form works perfectly.. the only issue is that it doesnt return the value
Can anyone tell me what i did wrong?? thanks
$(document).ready(function(){
function hola() {
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
return 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
})
}
$("#iForm").submit( function(event){
event.preventDefault();
var user = $("input[name=username]").val();
var password = $("input[name=password]").val();
var dbName = $("input[name=dbName]").val();
var server = $("input[name=server]").val();
$.get("1.php",
{username: user, password: password, dbName: dbName, server: server },
function(data){
if (data == "The table PAGE exists" || data == "The table SUBJECTS exists" || data == "The table USERS exists" ) {
// CALLING THE hola () function and expecting a return
var opt = hola();
$("p").html(data + opt);
}
}
)
})
})
HTML
<!-- Yes or No form -->
<form name="yN" style= "display: none; margin-left: auto; margin-right: auto; width: 6em">
<input type="radio" name="yN" value="1">yes</input>
<input type="radio" name="yN" value="0">no</input>
<button id=1 >click me!</button>
</form>
<!-- Login Form -->
<form id="iForm" style= "display: show">
<label id="username" >Username</label>
<input id="username" name="username"/>
<label id="password">Password</label>
<input id="password" name="password" />
<label id="server" >Server</label>
<input id="server" name="server"/>
<label id="dbName" >dbName</label>
<input id="dbName" name="dbName"/>
<input type="submit" value="submit" />
</form>
<p> </p>
Event handlers cannot return values because they're called asynchronously*.
Your existing hola() function will return immediately and the return statements in the click handlers are only called much later, i.e. when the button is clicked.
My approach would be this, using jQuery deferred objects (jQuery 1.6+):
function hola() {
var def = $.Deferred();
// show the popup confirm form
...
$('input[type=radio]').click(function() {
// determine return value
...
// send it back to anything waiting for it
def.resolve(retval);
});
// return a _promise_ to send back a value some time later
return def.promise();
}
$.get("1.php", { ... }).done(function(data) {
if (...) {
hola().done(function(opt)) { // will be called when the promise is resolved
$("p").html(data + opt);
});
}
});
If you prefer, instead of returning the opt value you could use def.reject() to indicate "non-acceptance" and then use a .fail handler to register a handler to be called for that condition.
You return 1 only in the click function of the radiobutton.
If you want to have a function "hola" that returns 1 if the radiobutton is checked, you simply need something like this:
function hola() {
return $("input:radio[name='yN']:checked").val();
}
hola does not even have a return statement. That's the reason for its not returning anything (more precisely: returning undefined always).
A JavaScript function that does not contain a return statement at all or whose all return statements are within nested functions will never return anything but undefined.
Your are tring to return the value from withing the click callback function. Move the return outside that:
function hola() {
var result;
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
result = 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
});
return result;
}

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Categories