How to change button name that depends on if some inputs are empty or not
Example: if input1 and input2 is not empty but input3 is empty - button name will be "Test".
This is my code, but i doesn't work
<div ng-app="myApp">
<form action="lab2.php" method="POST" ng-controller="controller">
<label>ID</label>
<input type="number" name="id" ng-model="id" name="id"/>
{{id}}
<label>Name:</label>
<input name="name" ng-model="name" type="text"/>
<label>City:</label>
<input name="country" ng-model="country" type="text"/>
<button ng-bind="but" type="submit">{{getName()}}</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('controller', function($scope) {
$scope.but="Operation";
$scope.id=0;
$scope.country="";
$scope.name="";
$scope.getName = function(){
if($scope.id==0 && $scope.name!=="" && $scope.country!=="")
{
return "INSERT";
}
if($scope.id!==0 && $scope.name=="" && $scope.country=="")
{
return "DELETE";
}
if($scope.id!==0 && $scope.name!=="" && $scope.country!=="")
{
return "UPDATE";
}
}
});
</script>
var app = angular.module("app",[]);
app.controller("MyCtrl" , function($scope){
$scope.name1 = "Test";
$scope.name2 = "";
$scope.name3 = "Test3";
$scope.getName = function(){
if( $scope.name1 == "" && $scope.name2 == "" & $scope.name3 !== "")
return "Test";
return "Other";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<input type="text" ng-model="name1">
<input type="text" ng-model="name2">
<input type="text" ng-model="name3">
<input type="button" name="{{getName()}}" value="{{getName()}}">
</div>
Try this:
<input ng-model="vm.input1" name="input1" type="text"/>
<input ng-model="vm.input2" name="input2" type="text"/>
<input ng-model="vm.input3" name="input3" type="text"/>
<button> {{(vm.input1 && vm.input2 && !vm.input3) ? 'Test' : 'Something Else' }} </button>
Something on these lines would work ...
jsfiddle: http://jsfiddle.net/0jeantca/3/
Hope this helps ...
By name do you mean the name attribute or the display text? The code below works for both.
In your template, you can write
<button name={{setName()}}>{{setName()}}</button>
and in your controller, you can write
$scope.setName = function()
{
// you can use switch here
var buttonName = "";
if($scope.input1 && $scope.input2 && !$scope.input3)
buttonName = 'Foo';
else
buttonName = 'Bar';
return buttonName;
}
Caution: As the input's change every time, the button text changes, it should be fine. But if you intend to change name attribute, then, it will cause a problem for the one who reads your code.
Related
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.
I am looking to display the addition of four values entered in the input boxes
<td><input type="text" value="22" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="one"></td>
<td><input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="two"></td>
<td><input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="three"></td>
<td><input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="four"></td>
And this is my js
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.getkeys = function (event) {
if($scope.one==='' || $scope.two==='' || $scope.three==='' || $scope.four==="" )
{
$scope.one=parseInt("0");
$scope.two=parseInt("0");
$scope.three=parseInt("0")
$scope.four=parseInt("0")
}
$scope.keyval = parseInt($scope.one)+parseInt($scope.two)+parseInt($scope.three)+parseInt($scope.four);
console.log($scope.keyval);
}
});
what i want is as soon as someone enters the value in the input boxes ,sum of all the four gets displayed ,the problem is if firstly user enters value in any box it display NaN ,until all the four values are entered any idea how to achieve it?
And how to know which ng-model value has been entered ,just like this.value in js
This is because the other fields are empty & trying to parseInt & add an empty field value will result in NaN.Alternatively you can pass 0 if field is empty
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.getkeys = function(event) {
if ($scope.one === '' || $scope.two === '' || $scope.three === '' || $scope.four === "") {
$scope.one = parseInt("0");
$scope.two = parseInt("0");
$scope.three = parseInt("0")
$scope.four = parseInt("0")
}
$scope.keyval = parseInt(($scope.one) || 0, 10) + parseInt($scope.two || 0, 10) + parseInt($scope.three || 0, 10) + parseInt($scope.four || 0, 10);
console.log($scope.keyval);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" value="22" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="one">
<input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="two">
<input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="three">
<input type="text" style="width:60px;margin:6px;" ng-keyup="getkeys($event)" ng-model="four"></div>
</div>
You don't need to bind a keyUp event, angularjs does that work for us.
Initialize the model one within the controller.
Create a function, i.e getTotal()
Use the object Number to convert the entered values to numbers.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.getTotal = function() {
return Number($scope.one) +
Number($scope.two) +
Number($scope.three) +
Number($scope.four)
};
$scope.one = 22;
$scope.two = 0;
$scope.three = 0;
$scope.four = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" style="width:60px;margin:6px;" ng-model="one">
<input type="text" style="width:60px;margin:6px;" ng-model="two">
<input type="text" style="width:60px;margin:6px;" ng-model="three">
<input type="text" style="width:60px;margin:6px;" ng-model="four">
<p>Total</p>
<span>{{getTotal()}}</span>
</div>
Minior modification on #Ele code.
Change the input type from text to number to facilitate the key up event and disable characters to be entered
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.getTotal = function() {
return Number($scope.one) +
Number($scope.two) +
Number($scope.three) +
Number($scope.four)
};
$scope.one = 22;
$scope.two = 0;
$scope.three = 0;
$scope.four = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" style="width:60px;margin:6px;" ng-model="one">
<input type="number" style="width:60px;margin:6px;" ng-model="two">
<input type="number" style="width:60px;margin:6px;" ng-model="three">
<input type="number" style="width:60px;margin:6px;" ng-model="four">
<p>Total</p>
<span>{{getTotal()}}</span>
</div>
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/
I wrote the below code for changing the text of div that called active yes, based on value of each input with type hidden.
i want to change the text of this div if input with id enable to "Enable List" and if input with classname delete has value changes the div text to "Deleted list" and if both of them was null show "list".
my code does not work correctly.
what is my problem?
here is my snippet :
$(document).ready(function() {
tmpval = $('#enable').val();
if (tmpval == '') {
$('.activeyes').text('list');
} else {
$('.activeyes').text('Enable List');
}
tmpval2 = $('#delete').val();
if (tmpval2 == '') {
$('.activeyes').text('List');
} else {
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
You are overwriting effect of the first check by the second check; you need to check the 2 inputs value together. Still, it is unclear what will happen if both are non-empty.
$(document).ready(function() {
tmpval = $('#enable').val();
tmpval2 = $('#delete').val();
if (tmpval == '' && tmpval2 == '') {
$('.activeyes').text('list');
} else if( tmpval!='' ){
$('.activeyes').text('Enable List');
} else if( tmpval2!='' ){
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
what is my problem?
You need to check the value of input when it changes its value, so capture the change event.
$(document).ready(function() {
$('#enable, #delete').change(function() {
var $this = $(this);
var id = $this.attr("id");
var value = $this.val();
if (value.length == 0)
{
$('.activeyes').text('list');
}
else
{
id == "enable" ? $('.activeyes').text('Enable List') : $('.activeyes').text('Deleted List');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.