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>
Related
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 have pieced together a script that adds the values in text boxes and displays the sums in a span. I have tried a ton of things, but I can not get it to display the sums in a input textbox. Here is a fiddle that I have been working in ..
http://jsfiddle.net/elevationprint/MaK2k/17/
Basically I want to change the spans to input text boxes. If anyone can take a look and let me know what I am missing, I would appreciate it!
The code is this
HTML
Red<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br>
Blue<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br><br>
Total = <span class="qty12lable"></span> x $.95<br>
Total = <span class="qty24lable"></span> x $1.40<br>
SCRIPT
$('.qty12').keyup(function(){
var qty12Sum=0;
$('.qty12').each(function(){
if (this.value != "")
qty12Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty12lable").text(qty12Sum);
//console.log(amountSum); });
$('.qty24').keyup(function(){
var qty24Sum=0;
$('.qty24').each(function(){
if (this.value != "")
qty24Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty24lable").text(qty24Sum);
//console.log(amountSum); });
You can target the input fields like so:
Total = <input class="qty12lable" value=""> x $.95<br>
Total = <input class="qty24lable" value=""> x $1.40<br>
$("input.qty12lable").val(qty12Sum);
$("input.qty24lable").val(qty24Sum);
To set the text (value) of a textbox you have to use .val() not .text(). Like this:
$('.qty12').keyup(function() {
var qty12Sum = 0;
$('.qty12').each(function() {
if (this.value != "")
qty12Sum += parseInt(this.value);
});
$(".qty12lable").val(qty12Sum);
});
$('.qty24').keyup(function() {
var qty24Sum = 0;
$('.qty24').each(function() {
if (this.value != "")
qty24Sum += parseInt(this.value);
});
$(".qty24lable").val(qty24Sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Red
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>Blue
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>
<br>Total = <input class="qty12lable"/> x $.95
<br>Total = <input class="qty24lable"/> x $1.40
<br>
This snippet has some logic about how you can attach event listeners on input fields and how you can get their values. It's not perfect and has quite a few bugs from production level perspective but this will give a hint about how you can listen and manipulate DOM using Jquery. Which is what Jquery is all about.
$( "input" )
.change(function () {
var prevVal = ($('#total').html() !== '') ? $('#total').html() : 0;
if(parseInt($(this).val()) === NaN) {
return;
}
$('#total').html(parseInt($(this).val()) + parseInt(prevVal));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="1"></input><br>
<input type="text" id="2"></input><br>
<hr>
Total = <span id="total" class="qty12lable"></span> <br>
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;
Firstly I apologies, I've just starting out with JavaScript
I have a problem with a form. I have two groups of Radio buttons on the form (age and bmi)
Everytime the 'Calculate' button is clicked, I want add the values of each checked Radio button and alert this to the screen.
It works in Chrome, but ALL other browsers give an NAN error.
Can anyone help?
<br>
<input type="radio" name="age" class="myradioButton" value = "1"/>
<input type="radio" name="bmi" class="myradioButton" value = "3"/>
<input type="button" name="Calculate" id="calculate"onclick="calculatehealth()" value="Calculate"/>
<br>
<script>
function calculatehealth() {
var valueAge = document.forms['myForm'].elements["age"].value;
var valueint = parseInt(valueAge);
var valueBmi = document.forms['myForm'].elements["bmi"].value;
var Bmiint = parseInt(valueBmi);
var total = Bmiint + valueint;
alert(total);
}
Demo: http://jsfiddle.net/z4RKx/
HTML
<form id="myForm">
<input type="radio" name="age" class="myradioButton" value="1" />
<input type="radio" name="bmi" class="myradioButton" value="3" />
<input type="button" name="Calculate" value="Calculate" onclick='calculatehealth()' />
</form>
JS
function calculatehealth() {
var valueint = 0;
if (document.forms['myForm'].elements["age"].checked) {
valueint += parseInt(document.forms['myForm'].elements["age"].value);
}
if (document.forms['myForm'].elements["bmi"].checked) {
valueint += parseInt(document.forms['myForm'].elements["bmi"].value);
}
alert(valueint);
}
And if you have many elements this might be a good alternative:
function calculatehealth() {
var valueint = 0;
for(i = 0; i < document.forms['myForm'].elements.length; i++) {
if (document.forms['myForm'].elements[i].checked) {
valueint += parseInt(document.forms['myForm'].elements[i].value);
}
}
alert(valueint);
}
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';
}
}