I know nothing about Angular but I was asked to create a validation for the new google map input. All I want to do is have the #lugar_continuar button stay disabled until the input #ciudad is filled in, but the button isn't disabled for some reason.
index.php, input to validate
<div class="">
<input id="ciudad" name="ciudad" class="ciudad" type="text"
placeholder="Ciudad" value="" required ng-model="ciudadSet">
<div id="map"></div>
<input type="hidden" id="distance" size="31" value="31">
</div>
Input type button that should stay disabled
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && ciudadSet" ng-click="from_precio = true" >
Using ng-model doesn't work. I also tried with JS, in main.js:
var ReservasApp = angular.module('Reservas',['rzModule']);
ReservasApp.controller('ReservasController',function($scope){
$scope.ciudad = "";
$scope.validacionCiudad = function() {
var disabled = false;
if( $scope.ciudad != null && $scope.ciudad != "" )
{
disabled = false;
}
else
{
disabled = true;
}
}
}
index.php
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && validacionCiudad()" ng-click="from_precio = true" >
I also tried using only JS:
var validacionCiudad = function() {
var ciudad = document.getElementById('ciudad');
var btn = document.getElementById('lugar_continuar');
if (ciudad.value == "") {
btn.setAttribute("disabled", "disabled");
} else {
btn.removeAttribute("disabled");
}
}
validacionCiudad();
I have tried many ways to achieve this but nothing is working!
you can try this: ng-disabled = "ciudadSet == ''", since ng-disabled is valid when the expression equals true. If you must call function validacionCiudad to judge this, you have to return bool value in your function. May this will help.
Change $scope.ciudad ="" to $scope.ciudad = undefined;
change your ng-model to:
ng-model="ciudad"
and your ng-disabled to:
ng-disabled="!ciudad"
that shall work
You can validate it like this.
<div ng-controller="MyCtrl">
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<input name="name" ng-model="name" type="text" required >
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Enviar</button>
</form>
</div>
https://jsfiddle.net/ivanm07/y2t88817/
Related
I'm writing a simple html code that does enable and disable some textboxes on button clicks. Below is my code.
function myFunction1() {
document.querySelector('#myText0').disabled = true;
document.querySelector('#myText1').disabled = true;
document.querySelector('#myText2').disabled = false;
document.querySelector('#myText3').disabled = false;
document.querySelector('#myText4').disabled = false;
}
function myFunction2() {
document.querySelector('#myText0').disabled = false;
document.querySelector('#myText1').disabled = false;
document.querySelector('#myText2').disabled = true;
document.querySelector('#myText3').disabled = true;
document.querySelector('#myText4').disabled = true;
}
function myFunction3() {
document.querySelectorAll("input").disabled = true;
document.querySelector('#myText2').disabled = false;
document.querySelector('#myText3').disabled = false;
document.querySelector('#myText4').disabled = false;
}
function myFunction4() {
document.querySelector("input").disabled = true;
document.querySelector('#myText0').disabled = false;
document.querySelector('#myText1').disabled = false;
}
input{
display:block;
margin:0.85em
}
<input type="text" id="myText0" label="myText0" disabled>
<input type="text" id="myText1" label="myText1" disabled>
<input type="text" id="myText2" label="myText2" disabled>
<input type="text" id="myText3" label="myText3" disabled>
<input type="text" id="myText4" label="myText4" disabled>
<h2>
Manually Enabling text boxes
</h2>
<button onclick="myFunction1()">Disable 0,1 field</button>
<button onclick="myFunction2()">Disable Rest field other than 0,1</button>
<br/>
<h2>
Disabling All initially and then enabling the required text boxes
</h2>
<button onclick="myFunction3()">Disable 0,1 field</button>
<button onclick="myFunction4()">Disable Rest field other than 0,1</button>
I've got a total of 120 textboxes so I'm looking for a better way to do this. In my above code, the buttons under Manually Enabling text boxes are working as expected. Whereas, the other approach that I thought of under Disabling All initially and then enabling the required text boxes is not working as expected.
Also Please let me know if there is a better approach than what I've used as there are 120 textboxes and my approach is the most time-taking as I'm checking manually and my 2nd approach is saving 25% of the total time (considering 120 textboxes and the number of them to be disabled that were provided as part of my SRS).
Thanks
You can make simple common methods that will 'cascade' the logic for you rather than defining each operation repeatedly. Take a look at the attached fiddle (and its code snippet)
function myFunc1() {
enableAll();
disableTextbox('#myText0');
disableTextbox('#myText1');
}
function myFunc2() {
disableAll();
enableTextbox('#myText0');
enableTextbox('#myText1');
}
/* Common functions */
function disableAll() {
disableTextbox('#myText0');
disableTextbox('#myText1');
disableTextbox('#myText2');
disableTextbox('#myText3');
disableTextbox('#myText4');
}
function enableAll() {
enableTextbox('#myText0');
enableTextbox('#myText1');
enableTextbox('#myText2');
enableTextbox('#myText3');
enableTextbox('#myText4');
}
function disableTextbox(textboxName) {
document.querySelector(textboxName).disabled = true;
}
function enableTextbox(textboxName) {
document.querySelector(textboxName).disabled = false;
}
/* Common functions */
input{
display:block;
margin:0.85em
}
<input type="text" id="myText0" label="myText0" disabled>
<input type="text" id="myText1" label="myText1" disabled>
<input type="text" id="myText2" label="myText2" disabled>
<input type="text" id="myText3" label="myText3" disabled>
<input type="text" id="myText4" label="myText4" disabled>
<h1>Proper way to do it</h1>
<button onclick="myFunc1()">Disable 0,1 field</button>
<button onclick="myFunc2()">Disable Rest field other than 0,1</button>
you can use for, and for each "input type" or "class":
function myFunction1() {
//var inputs = document.querySelectorAll('input[type=text]'); //use this or below
var inputs = document.querySelectorAll('input[class=ttt]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false; // or true
//inputs[i].style.display = 'none';
}
}
function myFunction2() {
//var inputs = document.querySelectorAll('input[type=text]'); //use this or below
var inputs = document.querySelectorAll('input[class=ttt]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true; // or false
//inputs[i].style.display = 'none';
}
}
input{
display:block;
margin: 0.85em
}
<input type="text" id="myText0" class="ttt" label="myText0" disabled>
<input type="text" id="myText1" class="ttt" label="myText1" disabled>
<input type="text" id="myText2" class="ttt" label="myText2" disabled>
<input type="text" id="myText3" class="ttt" label="myText3" disabled>
<input type="text" id="myText4" class="ttt" label="myText4" disabled>
<h2>
Manually Enabling text boxes
</h2>
<button onclick="myFunction1()">enable all field</button>
<button onclick="myFunction2()">disable all field</button>
I think the best way to do this is to specify the reason for disabling in a class or even a data attribute. For simplicity let's use a class. So for example an input should be disabled because of any reason you give it a class (or data attr) with the value of the name of that reason. This will make your code very readable even without reading over the javascript files. And you will not write much of javascript at all.
That would make your elements that should be enabled together, together, and vice versa.
I would suggest this solution:
function disable(className) {
for (const element of document.getElementsByClassName(className)) {
element.disabled = true;
}
}
function enable(className) {
for (const element of document.getElementsByClassName(className)) {
element.disabled = false;
}
}
input{
display:block;
margin:0.85em
}
<input type="text" class="reason1" label="myText0" disabled>
<input type="text" class="reason1" label="myText1" disabled>
<input type="text" class="reason2" label="myText2" disabled>
<input type="text" class="reason2" label="myText3" disabled>
<input type="text" class="reason2" label="myText4" disabled>
<h2>
Manually Enabling text boxes
</h2>
<button onclick="disable('reason1'); enable('reason2')">Disable 0,1 field</button>
<button onclick="disable('reason2'); enable('reason1')">Disable Rest field other than 0,1</button>
<br />
<h2>
Disabling All initially and then enabling the required text boxes
</h2>
<button onclick="disable('reason1'); enable('reason2')">Disable 0,1 field</button>
<button onclick="enable('reason1'); disable('reason2')">Disable Rest field other than 0,1</button>
I am working on angularjs and bootstrap application. I'm trying to validate the simple form, when user click on submit button all the fields in the from should have a value.
Please find the demo : https://plnkr.co/edit/aHtODbTTFZfpIRO3BWhf?p=preview
In the demo above, when user click on submit button with out selecting the checkbox , an error message is shown 'Please Select the Color..' , after the error message is shown select the checkbox and click on submit button still the error message is displayed. Any inputs on this?
html code:
<form name="myForm" ng-controller="ExampleController">
<div>Select Color : </div>
<label name="color" ng-repeat="color in colorNames" class="checkbox-inline">
<input ng-required="selectedColor.length === 0" oninvalid="this.setCustomValidity('Please select the color..')" type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> <!--<input type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> {{color}}-->
{{color}} <br> </label>
<div class="">
<div style="color: black;">Username : </div>
<input type="text" name="user" value="" required>
<div ng-show="myForm.$submitted || myForm.user.$touched">
<p class="error-mesg" ng-show="myForm.user.$error.required">The Username is required</p>
</div>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm)">Submit</button>
</form>
First
I have declared an array for all of the checkbox value:
$scope.selectedColor = [false,false,false];
Second
I added a method for check box validation check:
$scope.someSelected = function () {
for(var i = 0; i < $scope.selectedColor.length; i++) {
if($scope.selectedColor[i]) return true;
}
return false;
};
Third
I use ng-model and update the HTML code, ng-model is used for two-way data binding, and change to bind value will reflected in view and controller:
<input ng-required="!someSelected()" ng-model = "selectedColor[$index]" type="checkbox" name="color" value="{{color}}">
Forth
The user input box also do not have the ng-model so the change in view not be updated in controller. To solve this ng-model is added.
<input type="text" ng-model = "user" name ="user" value="" required>
Fifth
Updated the submit form validation:
$scope.submitForm = function(){
if ($scope.someSelected() && $scope.user != "" && $scope.user != undefined) {
alert("all fields are entered");
}else{
}
}
Thats all!
Please check the working code snippet:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-checkbox-input-directive-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="checkboxExample">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colorNames = ['RED', 'BLUE', 'BLACK'];
$scope.selectedColor = [false,false,false];
$scope.userSelection = function userSelection(team) {
var idx = $scope.selectedColor.indexOf(team);
if (idx > -1) {
$scope.selectedColor.splice(idx, 1);
}
else {
$scope.selectedColor.push(team);
}
};
$scope.submitForm = function(){
if ($scope.someSelected() && $scope.user != "" && $scope.user != undefined) {
alert("all fields are entered");
}else{
}
}
$scope.someSelected = function () {
for(var i = 0; i < $scope.selectedColor.length; i++) {
if($scope.selectedColor[i]) return true;
}
return false;
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<div>Select Color : </div>
<label name="color" ng-repeat="color in colorNames" class="checkbox-inline">
<input ng-required="!someSelected()" ng-model = "selectedColor[$index]" type="checkbox" name="color" value="{{color}}"> <!--<input type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> {{color}}-->
{{color}} <br> </label>
<div class="">
<div style="color: black;">Username : </div>
<input type="text" ng-model = "user" name ="user" value="" required>
<div ng-show="myForm.$submitted || myForm.user.$touched">
<p class="error-mesg" ng-show="myForm.user.$error.required">The Username is required</p>
</div>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm)">Submit</button>
</form>
</body>
</html>
<!--
Copyright 2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
Solution is to update your (1) input field for colors, (2) input field for user and (3) submitForm method
<input ng-required="selectedColor.length === 0" onchange="this.setCustomValidity(!validity.valueMissing && '')" oninvalid="this.setCustomValidity(validity.valueMissing ? 'Please select the color..' : '')"type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)">
<input type="text" name="user" value="" ng-model="user" required>
$scope.submitForm = function(form){
if ($scope.selectedColor.length > 0 && $scope.user != "") {
console.log('fields are all entered');
} else{
}
}
(1) You need to set the false condition to handle the checkbox when it is selected.
(2) For your user input field, you need to set ng-model=user to link the $scope.user object to the input.
(3) For the submitForm method, you want to know that the selectedColor array has at least one item, and that user is not empty.
As an ending point, please format your code using proper linting and indentation. Otherwise, it is difficult to read at first glance.
Users will only be able to click the submit button if users select a video file and the textbox is not empty. i can disable the submit button but i cant re-enable it
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" />
<br/>
Please enter video title:
<br/>
<input type"text" name="videoTitle" />
<br />
<input type="button" disabled id="Submit" value="Submit" onclick="submit()"/>
</form>
<script>
document.getElementById('submit').disabled = true;
var n=document.getElementById('videoTitle').value;
function submit();
if($('#videofile')[0].files.length != 0) && (n.length > 1)
{
document.getElementById('submit').disabled = false;
}
</script>
Your code had a lot of mistakes. This is your corrected code:
function check() {
if (document.querySelector('#videofile').files.length != 0 && (document.getElementById("videoTitle").value.length > 1)) {
document.getElementById('Submit').disabled = false;
} else {
document.getElementById('Submit').disabled = true;
}
}
Here is the JSFiddle demo
Missing ID added (u added only name attribute, and forgot the ID while still trying to use them)
Changed 'submit' in code to 'Submit'
Remove JQuery $ syntax
Validation on keypress rather than on submit click (which doesn't makes sense since u cant click the button while its disabled)
Else code added to re-disable the button if conditions are not valid
onclick event over submit button does not make sense here. You must listen change event of the file input and keyup event of the text input and apply conditions accordingly. You have not assigned id attribute as well(videoTitle)
Also note that click handler will not be invoked if the button is disabled
Try this:
var submitBtn = document.getElementById('Submit');
function enableDisable() {
var elem = document.getElementById('videofile');
var n = document.getElementById('videoTitle').value;
if (elem.files.length && n) {
submitBtn.disabled = false;
} else {
submitBtn.disabled = true;
}
}
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" onchange='enableDisable()' />
<br/> Please enter video title:
<br/>
<input type="text" name="videoTitle" id='videoTitle' onkeyup='enableDisable()' />
<br />
<input type="button" disabled id="Submit" value="Submit" />
</form>
Can you try to make your submit function do something?
function submit() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
}
};
you should use change event for text and videofile elements. So that whenever you modify something, change event is triggered and ur condition is checked inside it. Submit button is enable according to it.
Se the below code for reference!
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" />
<br/>
Please enter video title:
<br/>
<input type"text" name="videoTitle" id="videoText"/>
<br />
<input type="button" disabled id="Submit" value="Submit" onclick="submit()"/>
</form>
<script>
document.getElementById('submit').disabled = true;
var n=document.getElementById('videoTitle').value;
function submit();
$('#videofile').change(function() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
});
$('#videoText').change(function() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
});
</script>
I feel this is a bit simpler way to achieve this
<script>
document.getElementById("submit").style.pointerEvents = "none"; //Disable
var n=document.getElementById('videoTitle').value;
function submit();
if($('#videofile')[0].files.length != 0) && (n.length > 1)
{
document.getElementById("submit").style.pointerEvents = "all"; //Enable
}
</script>
Just replace your script with this one & try..
Hope this works for you..
My form is loaded with different input fields like radio button , text field ,numeric field which are generated dynamically while iterating through a list.
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="number" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" id ="reason<c:out value='[${status.index}]'/>" value="" maxlength="255" >
<br><br>
<input type="submit" value="submit" id="submit" />
</c:forEach>
The numeric fields will be validated against minimum and maximum values.if any of the numeric fields fails in the validation , submit button needs to be disabled .
JSFIDDLE
Any ways to achieve this using jquery or javascript?
Thanks for your valuable time and suggestions
Give IDs to your inputs and then use jQuery's .change() function.
Example:
HTML
<input id="test" type="number"/>
<input id="test2" type="number"/>
<input id="submit" type="submit" value="Submit"/>
JS
var testVal = $('#test'),
testVal2 = $('#test2'),
submit = $('#submit'),
minVal = 22,
maxVal = 33;
testVal.change(function() {
if((testVal.val() > maxVal || testVal.val() < minVal) ||
(testVal2.val() > maxVal || testVal.val() < minVal)) {
submit.prop('disabled', true);
} else {
submit.prop('disabled', false);
}
});
jsfiddle
So, you could do something like below.
var flag = true;
if (nameVal > maxVal) {
alert(id + ' Enter the reason before proceeding');
//var reason = nameList[index].Reason;
document.getElementbyId("reason" + index).focus();
flag = false;
}
if (itemVal < minVal) {
alert(id + ' Enter the reason before proceeding');
//var reason = nameList[index].Reason;
document.getElementbyId("reason" + index).focus();
flag = false;
}
document.getElementById("submit").disabled = !flag;
return flag;
I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username  
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password  </label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}