I'm experiencing a weird issue, or maybe it's something that i simply don't know
i am using an input type text to capture and update a value using ajax.
<input type="text" onchange="functionx(this);" style="width:80px; margin-top: 5px;" name="stock" id="stock" />
if i put any alphanumeric value on the field the javascript function get fired correctly, even if i put the plus sign and some numbers (+123456) but if i use the minus sign it doesn't work (-123456) what am i missing or doing wrong?
Thanks in advance.
UPDATE
function functionx(obj){
alert("function is being called");
}
I ran into a similar issue, while working on a project.
My answer does not exactly address the OP, but might help people running into the similar issue, due to a different reason.
I had an input field, which needed only Natural numbers as input. Therefore inside the onChange handler, I would run a validation, as shown in below code snippet.
<input
...
// AREA OF FOCUS
type="number"
// AREA OF FOCUS
onChange={(event) => {
const isValid = validateNumberValue(event.target.value, 'REGEX FOR NATURAL NUMBER');
if (isValid) {
handleFormInputChange();
}
}}
...
/>
It would work perfectly for the most part, however it would also accept input such as --, ++. Upon investigation, I figured it was due to the onChange handler not triggering when + or - was entered as input.
This was because, the type attribute of the input HTML tag was "number". It would only trigger when a numeric value was entered. I changed the type field to text, and everything started working as expected.
<input
...
// AREA OF FOCUS
type="text"
onChange={(event) => { ... }}
...
/>
Hope it helps. Thanks.
Validate in your JS that you are comparing with a NULL or undefined value and not with a value who is bigger than 0, i tested this on jsFiddle and its working fine.
Something in your validation could be causing this issue.
function functionx(obj){
var objval = obj.value;
if(objval != ""){
alert(objval);
}
}
Check this fiddle
Related
I am using Reactive form in Angular 6. For input type text I want it to be uppercase. I tried the solution
(input)="form.patchValue({name: $event.target.value.toUpperCase()})"
The solution works fine, but the only problem when I move cursor to middle and type a character, the cursor moves at the end.
Is there any other approach or any better solution?
why don't you just use CSS to do the job?
.uppercase{
text-transform: uppercase;
}
<input class="uppercase" type="text" placeholder="type here">
You can try this:
const yourControl = this.form.get('yourControlName');
yourControl.valueChanges.subscribe(() => {
yourControl.patchValue(yourControl.value.toUpperCase(), {emitEvent: false});
});
I know this is reeeeally late, but...
You could hook on to the (change) event instead of the (input) event. Your case changes won't execute until after the user leaves the field, but it will prevent the cursor from jumping.
You case changes will still execute if the user submits the form by pressing Enter while in the field.
document.getElementById(frmObj.id).value="";
document.getElementById(frmObj.id).autofocus;
document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
In the above code the value of the form object is perfectly setting to "" but there is no cursor in the text box. I want a cursor to be there. focus() only focuses that input box but does not actually set the cursor.
In JavaScript first focus on the control and then select the control to display the cursor on texbox...
document.getElementById(frmObj.id).focus();
document.getElementById(frmObj.id).select();
or by using jQuery
$("#textboxID").focus();
I realize that this is quite and old question, but I have a 'stupid' solution to a similar problem which maybe could help someone.
I experienced the same problem with a text box which shown as selected (by the Focus method in JQuery), but did not take the cursor in.
The fact is that I had the Debugger window open to see what is happening and THAT window was stealing the focus. The solution is banally simple: just close the Debugger and everything is fine...1 hour spent in testing!
Sometimes you do get focus but no cursor in a text field. In this case you would do this:
document.getElementById(frmObj.id).select();
One of the things that can bite you is if you are using .onmousedown as your user interaction; when you do that, and then an attempt is immediately made to select a field, it won't happen, because the mouse is being held down on something else. So change to .onmouseup and viola, now focus() works, because the mouse is in an un-clicked state when the attempt to change focus is made.
This way sets the focus and cursor to the end of your input:
div.getElementsByTagName("input")[0].focus();
div.getElementsByTagName("input")[0].setSelectionRange(div.getElementsByTagName("input")[0].value.length,div.getElementsByTagName("input")[0].value.length,"forward");
Inside the input tag you can add autoFocus={true} for anyone using jsx/react.
<input
type="email"
name="email"
onChange={e => setEmail(e.target.value)}
value={email}
placeholder={"Email..."}
autoFocus={true}
/>
You have not provided enough code to help
You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.
Here is the canonical plain javascript method of validating a form
It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point:
function validate(formObj) {
document.getElementById("errorMsg").innerHTML = "";
var quantity = formObj.quantity;
if (isNaN(quantity)) {
quantity.value = "";
quantity.focus();
document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
return false;
}
return true; // allow submit
}
#errorMsg { color:red }
<form onsubmit="return validate(this)">
<input type="text" name="quantity" value="" />
<input type="submit" />
</form>
<span id="errorMsg"></span>
In my experience
document.getElementById(frmObj.id).focus();
is good on a browser running on a PC.
But on mobile if you want the keyboard to show up so the user can input directly then you also need:
document.getElementById(frmObj.id).select();
Im working on a script which takes a form input and calculates a total including VAT.
I am attempting to validate the user input making sure he&she only uses whole numbers.
My problem is that when I type in the first number ie. 1 it throws my alert. And when continuing to add numbers it works fine. When typing in letters it works as supposed and return the alert.
I have a faint idea that this happens because I am using onkeydown event for activating the evaluation function. Since consoleLog show me that the value 100 is parsed as 10, 1000 as 100.
If I change them around so I now use onkeyup the calculator function will show me that the value 100 is parsed as 10, 1000 as 100. But if the field is empty the form is rendered unuseless because of the alert box keeps popping up. Evaluation works though if you get a chance to type anything in.
I will now post my code HTML first and JS after
<input type="text" id="price" name="price" onkeyup="checkIfWholeNo();" onkeydown="calculate();" />
function checkIfWholeNo() {
var price = document.getElementById('price').value;
if(/^\d+$/.test(parseInt(price))){}
else {alert("not a number"); return false;}
}
}
Question A:
Is there something wrong with my evaluation function that makes this happen?
Question B:
If it has to do with the event handlers how do I fix it so I get the effect of onkeyup on both the functions?
refer following links..
http://www.roseindia.net/javascript/form-validation-regular-expressions.shtml
http://www.designchemical.com/blog/index.php/jquery/form-validation-using-jquery-and-regular-expressions/
http://www.codeproject.com/Articles/17923/Form-Validation-with-Regular-Expression-Short-Vers
http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html
I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.
In my example below I'm using a dijit.form.DateTextBox:
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying The value entered is not valid.. Even if I remove the constraints="{datePattern:'MM/dd/yyyy'}" it still validates.
Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.
Try overriding the validate method in your markup.
This will work (just tested):
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to keep the dojoType and not have it validate. Unless you create your own type that has you logic in it.
I had a similar problem, where the ValidationTextBox met all my needs but it was necessary to disable the validation routines until after the user had first pressed Submit.
My solution was to clone this into a ValidationConditionalTextBox with a couple new methods:
enableValidator:function() {
this.validatorOn = true;
},
disableValidator: function() {
this.validatorOn = false;
},
Then -- in the validator:function() I added a single check:
if (this.validatorOn)
{ ... }
Fairly straightforward, my default value for validatorOn is false (this appears right at the top of the javascript). When my form submits, simply call enableValidator(). You can view the full JavaScript here:
http://lilawnsprinklers.com/js/dijit/form/ValidationTextBox.js