Detect when html input required true is working - javascript

I have a form
<form id="newRecord">
<input type="text" required/>
</form>
<button form="newRecord" type="submit">Submit</button>
http://codepen.io/anon/pen/EZwRjK
When the field is empty, and you click the button, you get a "Please fill out this field." pop up next to the field. Is there a way to detect if that pop up appears with JavaScript?

In HTML5, the pseudo-class :invalid is applied to any input that triggers the "This field is required" dialog box.
If you put the listener on your button, you could find out if the dialog box appeared or not by checking to see if there were any inputs marked :invalid...
$("#newRecord input[type=submit]").click(function() {
if ($("#newRecord input:invalid").length) {
//The popup appeared
} else {
//The popup did not appear
}
});
JSFiddle demo

In fact you can. You can use checkValidity() method. It returns true if the element contains a valid data.
$(function() {
$("#submit-button").click(function () {
// using jquery
console.log($("#input-text")[0].checkValidity());
// using javascript
var input = document.getElementById("input-text");
console.log(input.checkValidity());
});
});
Fiddle
Update
Seems the pop up is not showing when using type="button".
A work around I found is to use $("input").on("blur", function () { instead.
So it should be now:
$(function() {
$("input").on("blur", function () {
console.log($("#input-text")[0].checkValidity());
var input = document.getElementById("input-text");
console.log(input.checkValidity());
// checking as a whole
console.log("Form - ", $("#newRecord")[0].checkValidity());
});
});
Fiddle

REACT / NEXT.JS
In my case, it was because the 'input' tags were required and were not in the viewport (not visible) when submitting on my form.
The form was hidden when a useState was false const [isOpen, setIsOpen] = useState(false), then it was necessary to change the state to true so that the form would appear and the "fill these fields" message.
Solution was with onInvalid() property
<input onInvalid={() => setIsOpen(true)} type='radio' required />

Related

How to manually reset the input validation state in IE after form reset?

It appears as though Internet Explorer does not reset the validation state (both .checkValidity() and validity.valid) after a default form reset. This does work as expected in Chrome and Edge.
Does anyone have any insight into this issue, and how to get around it - perhaps how to reset the validation state in IE manually?
I have not seen any documentation referencing this issue - caniuse claims limited support for HTML5 validation in IE10 and IE11, but does not reference this property specifically.
See the following example - the expected behavior:
No radio buttons checked; click submit = input invalid (form invalid does not trigger because of default HTML5 controls - it never gets to the handler, and that is ok)
1 radio button checked; click submit = valid input, valid form
Click reset = invalid input, invalid form
This is where IE deviates - it retains that the form and input are still valid, even though the input is blank.
(function() {
$("form")
.on("submit", function(e) {
var v = formValidCheck();
if (!v) {
e.preventDefault();
}
radioValidCheck(false);
return false; // don't go anywhere
})
.on("reset", function(e) {
// Push onto event stack, so it refreshes after the form fields have been reset
setTimeout(function() {
$('input').change();
formValidCheck();
radioValidCheck(false);
}, 0);
});
$('input').on('invalid', function(e) {
e.preventDefault();
radioValidCheck(true);
});
$('input').on('change', function(e) {
formValidCheck();
radioValidCheck(false);
});
function formValidCheck() {
var v = $('form').get(0).checkValidity();
$("#test").text(v);
return v;
}
function radioValidCheck(clearFormValid) {
if (clearFormValid) {
$('#test').text('');
}
$("#testradio").text($("#radio1").get(0).validity.valid);
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Form is valid? <span id="test"></span></p>
<p>Radio is valid? <span id="testradio"></span></p>
<form>
<input type="radio" required id="radio1" name="testradios">
<label for="radio1">1</label>
<input type="radio" required id="radio2" name="testradios">
<label for="radio2">2</label>
<input type="radio" required id="radio3" name="testradios">
<label for="radio3">3</label>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
I have tried a couple things, like triggering a change on the input, and pushing it onto the event stack so it accesses it after it has applied the changes to the input, as seen in the snippet, but still no luck.
I haven't found a bug or any mention of this elsewhere

onBlur event on composed component (input + Button)

I am trying to make a "composed component" which consists of an input field and a button.
I have the following jsfiddle as example:
http://jsfiddle.net/stt0waj0/
<div id="myComponent">
<input type="text" onBlur="this.style.border='1px solid red';">
<button type="button" onClick="alert('Hello World');">ClickMe</button>
</div>
The behavior I want is that when I leave the input field without writing any content, I get a validation error (red border in this case). This already works in the fiddle (content validation is not the scope of the question).
However, when I leave the input field by pressing the button, I will open a dialog which allows to select values for the input field, so in that case, I don't want the validation to run.
So, the concrete question about the fiddle: Can I click the input field, and then click the button and not have a red border? But, if I click the input field, and then click somewhere else, I want the red border (any onBlur except when button was clicked).
Is this possible without dirty tricks?
Things I want to avoid:
Set a timer on the first event to wait for the second (Reason: performance)
Make the onClick event always reset the red border on the text field (Reason: gui glitches)
Just to make it clear on what I'm looking for and why this question is interesting: the onBlur event is fired before the onClick event. However, I normally would need the onBlur to know that the onClick comes next, which is not possible. That's the point of the question.
Imagine a date picker which validates on empty field, when the field has focus and you press the calendar, you will get a validation error even though you're selecting a date. I want to know if there is an elegant way to handle such cases.
To make this work, you can postpone your validation function if user pressed the button.
Below is sample code and fiddle to show what i mean.
* Updated the fiddle to use select dropdown instead of a button *
Fiddle Demo
input.error {color: red; border: 1px solid red;}
<div id="myComponent">
<input id="btn" type="text" onBlur="inputBlur()">
<select type="button" data-btn="btn" onclick="inputButtonClick()" onchange="selectChange()" onblur="selectBlur()">
<option value="">choose</option>
<option value="item1">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
</select>
</div>
window.validate = function(input) {
//do your validation
var val;
console.log("Validating");
val = input.val();
if ( !val || !val.length) {
input.addClass("error");
console.log("Something is invalid");
} else {
//all good
console.log("All valid");
}
//clear error after x time to retry
setTimeout(function() {
$(".error").removeClass("error");
$("input").removeAttr("data-btn-active") ;
}, 3000);
}
window.selectBlur = function() {
var input = $("#" + $(event.target).attr("data-btn"));
validate(input);
}
window.selectChange = function() {
var input = $("#" + $(event.target).attr("data-btn"));
console.log("change", $(event.target).val() );
input.val( $(event.target).val() );
validate(input);
}
window.inputButtonClick = function() {
var input = $("#" + $(event.target).attr("data-btn"));
input.attr("data-btn-active", "true");
console.log("inputButtonClick",input );
}
window.inputBlur = function() {
var input = $(event.target);
//give a bit of time for user to click on the button
setTimeout(function() {
if (!input.attr("data-btn-active" ) ) {validate(input);}
}, 100);
}
$(document).ready(function() {
});

Failing to get value of an html input field

I've got a html dialog window, with a simple input field, and two buttons (OK and Cancel).
The user will be prompted to enter text into the input field and then select OK, then I want to take the contents of the input (type text) field and use it. However, I cant seem to get the contents of the input field.
Here is the code I have:
Html dialog contents:
<div id="DescriptionDialog" title="Update Settings" style="display: none;">
<p>Please enter the reason for this update: </p>
<input id="StateDescription" name="StateDescription" class="longer" type="text" placeholder="enter description of change"/>
</div>
The javascript function - the function is triggered by another button on the main page - to open the dialog:
function DialogFunction() {
$('#DescriptionDialog').show();
$('#DescriptionDialog').dialog({
open: function () { $('.ui-dialog :button').blur(); },
width: 500,
modal: true,
resizable: false,
buttons: {
"OK": function () {
alert('OK');
var description = $('#StateDescription').val();
alert(description);
//This is where i will make an ajax call to use the description entered.
$('#StateDescription').val("");
$('#DescriptionDialog').hide();
$(this).dialog('close');
},
"Cancel": function () {// get rid of the dialog and reset the form
$(this).dialog('close');
$('#StateDescription').val("");
$('#DescriptionDialog').hide();
}
}
});
}
For some reason when i select OK, the alert to show "OK" appears, then no matter what i have entered in the input field, the alert for the description is always blank or if i set a value in the html then it is that.
Any ideas?
are you sure that you don't have another input with the Id "StateDescription"? because your code are pretty good, and when I try to run this on jsfiddle after the "OK" alert I can see the value for the input:
Look it here: http://jsfiddle.net/paqrL/
This are ok dude!
var description = $('#StateDescription').val();
alert(description);

Check with textbox

I have this question. I have a input type text and a button. Like this html:
<form id="browser-form">
<div class="filebrowser">
<input type="text" id="browser-filepath">
</div>
<div class="upload submit">
Uploaden
</div>
</form>
But the question is. When the input type is empty. Je can not click on the button. When the input type is fil. Than you can click on the button. How can i fix that?
Thanks!
Assuming I've understood your question correctly, I think you want to prevent the link from doing anything unless the input has a value. If that's correct, then you can do this:
$("#browser-submit").click(function(e) {
if(!$("#browser-filepath").val()) {
e.preventDefault();
}
});
preventDefault is a method of the event object which, as the name suggests, prevents the default action of an event (in this case, following the link).
Here's a working example of the above.
function UpdateSubmitButton() {
var oTextBox = document.getElementById("browser-filepath");
var oButton = document.getElementById("browser-submit");
if(oTextBox.value == "") {
oButton.disabled = true;
}
else {
oButton.disabled = false;
}
}
Add an onchange="UpdateSubmitButton()" section to your text box, and you might want to add onload="UpdateSubmitButton()" to your document body.
This should do the trick.

jquery: event for simulating live typing

Part 1:
Is there any event I can use to get a callback when the user 'change' the input field. My definition of change is to simulate the following effect. say, I want to update a label while the user typing in the input box. I tried jquery "change" event. It works, but doesn't have the live effect. Once the input field is updated, I have to click on somewhere in the screen to update the label.
Part 2:
well, if this is not a good idea, I may prevent the form being submitted on enter key. Not sure about a good way to do it either. Quick search found this answer.
<form action="" method="post" onsubmit="return false;">
not tested yet, but hopefully the submit button may still works.
EDIT: tested, and onsubmit="return false;" prevents even the submit button.
thanks,
bsr.
This should do it:
input.bind('keydown keypress', function() {
setTimeout(function() {
label.text(input.val());
}, 0);
});
Live demo: http://jsfiddle.net/simevidas/qTBxv/
Part 1
You can just update it every keyUp, but I would suggest you at least wait 1 second after the user finishes typing.
var timer;
var changeTxt = function(){
// Change label text here.
};
$("#myInput").keyup(function(){
clearTimeout(timer);
timer = setTimeout(changeTxt, 1000);
});
Part 2
That example you posted stops a form from submitting. Is that your goal?
EDIT:
I think you are trying to control the form's submission?
$("#myForm").submit(function(){
if(/* Your condition here */){
return false;
//Only if your condition is true, stop form submission
}
});
Did you try out the keydown or keypress event?
I would prefer a combination of both, form and field validation:
Find working sample here: http://jsfiddle.net/ezmilhouse/9mNc4/1/
your html:
<form method="post" action="post.php">
<input type="text" name="" value="" />
<label>Name</label>
<div></div>
</form>
your js:
// prevent form from being posted empty
$('form').live('submit', function(evt){
if ( $('input', this).val() === "" ) {
evt.preventDefault();
alert('Field is required!');
}
});
// validate form field on the fly
var min = 3;
$('input').live('keyup change', function(){
if ($(this).val().length < min) {
$('div').html('<span class="invalid">min. 3 characters.</span>');
} else {
$('div').html('<span class="valid">ok!</span>');
}
});
there is something called oninput that you can use.
<form oninput="xx.value=aa.value">
<input type="text" name="aa" value="">
<output name="xx" for="aa"> </output>
</form>

Categories