Materalize already supports validation for input fields such as email, but I would like to validate input fields such as passwords on the fly. Basically this means adding the error or success label through javacript.
My success so far has been poor. When I call the change() JS function and try to addClass('valid') for example, nothing happens and from what I can see, the class doesn't even appear in the HTML. I know the function is working because if I add a nonsense class like 'test', it does display in the HTML.
Is it not as simple as adding 'valid' or 'invalid' - do I need to meet other criteria before the label will appear?
Any help will be much appreciated.
My solution was to include the error labels as below:
<div class="input-field col s9 offset-s1">
<i class="material-icons prefix">perm_identity</i>
<input id="register_user" name ="register_user" type="text">
<label id="reg-user-error" style="display:none" for="register_user" data-error="short" data-success="good">Username</label>
<label for="register_user">Username</label>
</div>
But making sure to hide the label by default. Then I only had to modify the classes with javascript and show the label. If you don't hide by default, any input automatically validates the label. My JS is:
$('#register_user').on('change',function()
{
if($('#register_user').val().length > 7)
{
if($('#register_user').hasClass('invalid'))
{
$('#register_user').removeClass('invalid');
}
$('#register_user').addClass('valid');
$('#reg-user-error').addClass('active');
$('#reg-user-error').show();
}
else if($('#register_user').val().length < 8)
{
if($('#register_user').hasClass('valid'))
{
$('#register_user').removeClass('valid');
}
$('#register_user').addClass('invalid');
$('#reg-user-error').addClass('active');
$('#reg-user-error').show();
}
});
Related
I am working on a bootstrap environnement with classic asp.
I have a dynamically generated input fields
<input type="number" size="5" name="montantafacturer_<%=irs("INSPECTIONID")%>">
<button onclick="_EVENTSPARAM('events_ajouteralafacturation','<%=irs("INSPECTIONID")%>');">add</button>
There can be up to 100 dynamically generated fields on one page.
The basics are that i should fill the field montantafacturer_<%=irs("INSPECTIONID")%> with a numeric value and click on add to insert value in the database in a postback method
I am wondering if i can insert a javascript code to check if my field is filled rather than getting the field empty error from postback response... to gain time
ie :
<input type="number" size="5" name="montantafacturer_<%=irs("INSPECTIONID")%>">
<button onclick="**IF montantafacturer_<%=irs("INSPECTIONID")%>" IS NOT EMPTY THEN** _EVENTSPARAM('events_ajouteralafacturation','<%=irs("INSPECTIONID")%>');">add</button>
I wonder if this can be done via inline javascript.
Please advise how.
iid = irs("INSPECTIONID")
if iid <> "" then %>
<input type="number" size="5" name="montantafacturer_<%=iid%>">
<button onclick="_EVENTSPARAM('events_ajouteralafacturation','<%=iid%>');">add</button>
<$ end if %>
That way if your recordset is empty, no HTML is output. If you move the IF/THEN to just before the Button tag, then no button will be created for an empty value.
First of all, welcome to StackOverflow
Secondly ... It's been a very long while when I stopped using Classic ASP (more than 15 years ago), it's nice to see that he still has a small place out there :)
Last, but not the least... your question
as you have input and buttons, I'm sure you have a for loop and outside I will assume you have a <form> tag wrapping all inputs and buttons
To accomplish what you're trying to do, and making use of better code techniques, I would most likely end up with something as (and assuming that you can use jQuery to lift a bit of the javascript... let me know if you can't, and I'll re-write without it)
<form action="/yourpage.asp" method="POST">
<table class="table">
<tbody>
<% For ... %>
<tr class="tr-<%=irs("INSPECTIONID")%>">
<td>
<input
type="number"
size="5"
id="montantafacturer_<%=irs("INSPECTIONID")%>"
name="montantafacturer_<%=irs("INSPECTIONID")%>">
</td>
<td>
<button
class="btn"
data-event="events_ajouteralafacturation"
data-input="<%=irs("INSPECTIONID")%>"
>add</button>
</td>
</tr>
<% Next %>
</tbody>
</table>
</form>
<script>
$(function() {
// for every button with class "btn", fire "onButtonClick" fn upon click
$(".btn").on("click", onButtonClick);
});
function onButtonClick(evt) {
evt.preventDefault();
var btn = $(evt.currentTarget); // the clicked button
var btnEvent = btn.data("event");
var btnInput = btn.data("input");
// your logic
var input = $("#montantafacturer_" + btnInput).val();
if(input.length === 0) {
// show the error in any way you prefer
return;
}
// if we reach here, we have data in the input
_EVENTSPARAM(btnEvent, btnInput);
// you can now fire some code to submit the form
// or just this value, or even disable the button while it
// is being used to send the data (prevent double click), etc.
}
</script>
the <tr class="tr-<%=irs("INSPECTIONID")%>"> was a technique that I used back then so I could add a class that would mark that row with another color, to give some feedback to the user that something was happening with that row data, for example
$(".tr-" + btnInput).addClass("updating");
I've also added id to the input to use $("#...") instead of search by name
Small rant on using JS inline
Why would you ever use inline JS? It really isn't practical or readable - highly recommend moving that into an external source.
How to use JS inline (pls don't)
But if there is absolutely no way around for you, you can always just throw all your normal JS code inside an inline event like onclick.
<button onclick="
// this makes me sad
const allInputs = document.querySelectorAll('[name^=montantafacturer_]');
allInputs.forEach(input => {
if (input.value.length > 0 && !isNaN(input.value)) {
// number
} else {
// empty / Not a Number
}
});
">
add
</button>
This is about what you are looking for.
Mentions
Really, don't use inline JS
As pointed out by another user - you may want to use the HTML property required
I managed to make all fields are required and validated. But when I try to make a field not required it does not remove CSS.
HTML:
<div class="form-group"><label for="">Your email addresss<span class=""></span></label><input type="email" class="form-control"><small style="display: none"></small></div>
JS Code:
var removeError = function (element, siblings) {
$(element).removeClass("text-error");
siblings.each(function (index, sib) {
if (sib.tagName == "SMALL") {
sib.innerText = ""
$(sib).removeClass("text-danger");
$(sib).removeClass("font-weight-bold");
$(sib).hide();
}
})
};
I tried to experiment by removing CSS class="text-danger" even comment out the below line my function checks for that
<!-- <small style="display: none"></small> -->
Why the above change does not work?
How can I make this utility or configured work for none required field as well,
I am struggling is there any way I can set not required field, I don't want to use a third-party library (such as jQuery Validate plugin) for now as it is not working on my system. Because of most of them use "Form" tag, and could not be managed to use it without form tag.
Demo Code pen: https://codepen.io/dunya/pen/KYdQPd
First of all, I am really sorry that I could not give specific title about the issue. I have a .net 4.6.1 view page.
I want to create this feature.
Depending on the DepositType, the DefaultDeposit should display either a £ sign or %.
One of the logic, I already tried was to create another property called DefaultDepositPercent. Create a Input Box which is hidden underneath and use Jquery to display or hide this Input Box. Then in my service layer, pass the value inputted in the DefaultDepositPercent to DefaultDeposit.
However, there was an inconvenience that the mvc form also passes the DefaultDeposit value as 0. And there is also an issue of someone fiddling with the Javascript.
I have googled but could not find any answers. It is likely because I could describe the issue in few words.
Any direction would be helpful. Thanks
In bootstrap we just have to place the span tag above or below the input element to get the Prefix or Postfix effect. More Details Here
So the idea is first not to have this post / prefix span tag initially but add it either on DOM ready event or when the drop down selection changes using Jquery insertBefore and insertAfter. Here is a working sample. Hope this is helpful.
$(function() {
SetUpDepositTextBox(); // set up the input box once when DOM is ready
$('.DepositType').on('change', function() {
SetUpDepositTextBox(); // set up the text box when ever the dropdown changes
});
});
function SetUpDepositTextBox() {
$('#depositDefaultWrapper span').remove();
var $this = $('.DepositType');
if ($this.val() == "Amount") {
$('<span class="input-group-addon">£</span>').insertBefore('#depositDefaultWrapper input');
} else {
$('<span class="input-group-addon">%</span>').insertAfter('#depositDefaultWrapper input');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
Deposit Type
<select class="DepositType form-control">
<option value="Amount">Amount</option>
<option value="Percentage">Percentage</option>
</select>
Default Deposit
<div id="depositDefaultWrapper" class="input-group">
<input type="text" class="form-control" value="10">
</div>
I am working with jQuery 2.1.4 and javascript to do a simple Bootstrap form validation.
I found 3 strange things.
I am sure my jQuery code is working in the onblur and onfocus event of <input> elements (as you can try in my fiddle), but I cannot see .has-error class style. I have introduced boostrap.css etc. in my <head> part, of course.
<form-group> is indenting my paragraph to very end of left side of screen and it hides part of it, I must be using it wrongly but I don't know why.
Cancelar button is not working. I have tried <s:url value="/listaReservas.jsp" /> and plain url like in fiddle, no avail. FF complains about cancelar not defined.
Am I allowed to define a pure Javascript function like I did (mixing Javascript with jQuery), or I must bind it like this: $('#xxxId').click(function(){});???
Thanks all.
.has-error works but you need to make some changes. First, the class should be added to parent node form-group and second, your <input> field should have the class form-control. The HTML looks something like this:
<div class="form-group has-error">
<label class="control-label" for="tarjetaId">No. Tarjeta:</label>
<div class="controls">
<input class="input-xlarge form-control" id="tarjetaId" name="usuarioCompra.numeroTarjeta" value="" />
</div>
</div>
And the JavaScript
$("#tarjetaId").blur(function(){
var cuenta = $("#tarjetaId");
if (cuenta.val().length != 20){
cuenta.closest('.form-group').addClass("has-error");
$("#comprarButtonId").prop('disabled', true);
} else {
cuenta.closest('.form-group').removeClass("has-error");
}
});
As for .form-group giving your layout a negative margin. You are using .row as its parent, which also has negative margin. So you are actually applying two layers of negative margins. Having <div class="row"> is redundant.
Lastly, declare
function cancelar() {
window.location = "/listaReservas.jsp";
};
in the global scope, which means outside of $(document).ready(). The HTML for the submit button should have onclick="cancelar()" instead of onclick="cancelar"
I have two sets of data: "heat" and "cold", which are retrieved from another provider. This data is quite unorganized and I have removed lots of stuff in the code just to show the essential part of my problem. "Heat" and "cold" both contain properties that the user has to fill in. This property however is dynamic and the amount of properties is not fixed (hence it is in a loop as shown in the code).
My goal is to hide/disable the submit button, which is located all the way down, whenever one single input field in the list in either sets of data is empty. This should also preferably work on Internet Explorer 9, where the 'required' tag is not supported.
I have tried:
Adding the required tag. This unfortunately does not work in IE9 and I have some issues even in Google Chrome because it is still submitting my form. (I added the form tags too)
Adding Ng-show on the submit form. I checked whether the userInput is empty, but this still does not work.
Now you may ask, why wouldn't I just check in my controller whether these properties are empty in my submit method? While it is a good point, I can not access this dynamic data very easily in my controller. Hence, I need a solution that will hopefully fix this problem with no/mimimal effort in the controller.
Code:
<!--Start wrapper!-->
<div class="wrapper">
<div ng-repeat="(code, program) in data.old.heat">
<div class="row" ng-repeat="(componentId, component) in program">
<div class="inputForm">
<!--This field may not be left empty!-->
<input type="text" class="form" ng-model="component.userInput">
</div>
</div>
</div>
<div ng-repeat="(code, program) in data.old.cold">
<div class="row" ng-repeat="(componentId, component) in program">
<div class="inputForm">
<!--This field may not be left empty!-->
<input type="text" class="form" ng-model="component.userInput">
</div>
</div>
</div>
</div>
<!--End of wrapper !-->
<div class="submitPanel">
<button ng-click="submit()">Submit</button>
</div>
Here ya go : https://jsfiddle.net/DIRTY_SMITH/zxbe5rt0/
function validate(){
var text1 = document.getElementById('text').value;
if (text1.length > 0){
alert("went through");
return true;
}
alert("did not go through");
return false;
}
Not specific to angular, but you could check if it has characters via jQuery.
Html
<div class="submitPanel">
<button class="submit-btn" ng-click="submit()">Submit</button>
</div>
jQuery
$('#form input').blur(function()
{
if( $(this).val().length === 0 ) {
$(this).parents('.submit-btn').addClass('hide');
}
});
CSS
.hide{
display:none;
}
I have two options for you, but they both include ng-disabled (https://docs.angularjs.org/api/ng/directive/ngDisabled).
You can put this attribute on the button and you can either call a function on the scope in that attribute and check if all values are given.
So like: ng-disabled="checkInputs()".
Or
You wrap a form around all your inputs, give the form a name like name=form and set the required attribute on all inputs. (EDIT: you could use ng-required="true" for IE9.)
Then you could say ng-disabled="!form.$valid".