How to validate JQuery forms that have multiple name[] arrays? - javascript

These fields are created with JQuery.
How do I validate the array of "aname[]" fields (you have to fill them in before going to the next step)?
JQuery to HTML:
input ="<input name='aname[]' id='1' placeholder='yourname1' type='text' required />";
input +="<input name='aname[]' id='2' placeholder='yourname2' type='text' required />";
input +="<input name='aname[]' id='3' placeholder='yourname3' type='text' required />";
$(".placeholder").append(input);
JQuery command to try and get input
$(document).ready(function() {
var items = $('input[name="items[]"]').text();
if(items == ""){
alert("fill this field");
}
});

Two issues:
text() retrieves the text of an element (like a span or div), not the value of an input. To get the value of an input, use val. (Or if just working with the DOM element, the value property.)
You need to run the check in response to an event, not just on page load.
If you change text() to val() in that code, you'll only be checking the value of the first one (text() is a bit odd and works differently to val() and most other jQuery getters).
So if you want to check that all of them are filled in, you'll need an event handler and a loop of some kind:
$(document).ready(function() {
$("selector-for-the-form").on("submit", function(e) {
$(this).find('input[name="items[]"]').each(function() {
if (this.value == "") {
this.focus(); // So the user knows which field...
alert("fill this field"); // ...although this may mess that up
e.preventDefault(); // Prevent form submission
return false; // Stop looping
}
});
});
});
Of course, alert isn't usually the greatest user experience for this sort of thing. It's usually more pleasant if you do proactive validation and a notification that doesn't jar the user and interrupt what they're doing until you have to (like changing the color of the border of the input and/or showing an inline message). (There are also lots of plugins available to help you with doing that.)

Related

After AJAX callback, onblur goes back to original (or updated) field

I have an AJAX callback:
HTML:
<a onCLick="loadXMLDoc(id1,id2)">(Add)</a>
This calls an AJAX function that calls back a basic html input field in place of the above "(Add)"
onChange in this input field performs another AJAX callback that loads user input into a database.
What I am trying to do is once the field is filled out (or not filled out) and the field is blurred, it either goes back to the original or the newly updated value (but not any longer an input field).
I have searched around for a while and have come up with nothing. I am also new to javascript and AJAX. If it helps, I am using PHP mainly in this application.
Thanks
ADDITION
This is what I am trying to achieve:
The page lists different entries in table format.
There is a specific field that either has an id (stored in the database), or if field is null (in database) that field will display a button to add the id.
When pressed, the button calls a function which calls back an input field, the this replaces the previous "add" button. The AJAX callback places the input field in place of the "add" button.
This is where I need the help: After the user inputs the ID (or decides not to) and once the field no longer has focus, it changes from an input field back to what it was or the newly enter id. I am trying to do all this without refreshing the page.
I still don't follow exactly, but hopefully this will show you a means of creating/changing DOM elements in response to events like you've mentioned:
$(document).ready(function() {
$("#container").on("blur", ".name", function(e) {
var val = $(this).val();
if (!val) {
$(this).closest(".row").html("<button class='add'>Add</button>");
} else {
$(this).closest(".row").html("<span class='label'>Name: </span><span>" + val + "</span>");
}
});
$("#container").on("click", ".add", function(e) {
var html = "<span class='label'>New Name: </span><input class='name' type='text' />";
var row = $(this).closest(".row").html(html);
row.find("input").focus();
});
});
Working demo: http://jsfiddle.net/jfriend00/01ajd0y9/

Radio button REQUIRED if input field has content

I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.

html catch event when user is typing into a text input

Im just wondering how I go about catching the event when the user is typing into a text input field on my web application.
Scenario is, I have a contacts listing grid. At the top of the form the user can type the name of the contact they are trying to find. Once there is more than 1 character in the text input I want to start searching for contacts in the system which contain those characters entered by the user. As they keep typing the data changes.
All it is really is a simple type ahead type functionality (or autocomplete) but I want to fire off data in a different control.
I can get the text out of the input once the input has lost focus fine, but this doesnt fit the situation.
Any ideas?
Thanks
Use the keyup event to capture the value as the user types, and do whatever it is you do to search for that value :
$('input').on('keyup', function() {
if (this.value.length > 1) {
// do search for this.value here
}
});
Another option would be the input event, that catches any input, from keys, pasting etc.
Why not use the HTML oninput event?
<input type="text" oninput="searchContacts()">
I would use the 'input' and 'propertychange' events. They fire on cut and paste via the mouse as well.
Also, consider debouncing your event handler so that fast typists are not penalized by many DOM refreshes.
see my try:
you should put .combo after every .input classes.
.input is a textbox and .combo is a div
$(".input").keyup(function(){
var val = this.value;
if (val.length > 1) {
//you search method...
}
if (data) $(this).next(".combo").html(data).fadeIn(); else $(this).next(".combo").hide().html("");
});
$(".input").blur(function(){
$(this).next(".combo").hide();
});

How do I use jQuery to disable a form's submit button until every required field has been filled?

I have a form with multiple inputs, select boxes, and a textarea. I would like to have the submit button be disabled until all of the fields that I designate as required are filled with a value. And after they are all filled, should a field that WAS field get erased by the user, I would like the submit button to turn back to disabled again.
How can I accomplish this with jQuery?
Guess my first instinct would be to run a function whenever the user starts modifying any of the inputs. Something like this:
$('#submitBtn').prop('disabled', true);
$('.requiredInput').change(function() {
inspectAllInputFields();
});
We then would have a function that checks every input and if they're validated then enable the submit button...
function inspectAllInputFields(){
var count = 0;
$('.requiredInput').each(function(i){
if( $(this).val() === '') {
//show a warning?
count++;
}
if(count == 0){
$('#submitBtn').prop('disabled', false);
}else {
$('#submitBtn').prop('disabled', true);
}
});
}
You may also want to add a call to the inspect function on page-load that way if the input values are stored or your other code is populating the data it will still work correctly.
inspectAllInputFields();
Hope this helps,
~Matt
Here's something comprehensive, just because:
$(document).ready(function() {
$form = $('#formid'); // cache
$form.find(':input[type="submit"]').prop('disabled', true); // disable submit btn
$form.find(':input').change(function() { // monitor all inputs for changes
var disable = false;
$form.find(':input').not('[type="submit"]').each(function(i, el) { // test all inputs for values
if ($.trim(el.value) === '') {
disable = true; // disable submit if any of them are still blank
}
});
$form.find(':input[type="submit"]').prop('disabled', disable);
});
});
http://jsfiddle.net/mblase75/xtPhk/1/
Set the disabled attribute on the submit button. Like:
$('input:submit').attr('disabled', 'disabled');
And use the .change() event on your form fields.
Start with the button disabled (obviously). Bind an onkeyup event to each required text input, and an onchange or onclick to the select boxes (and any radio buttons/checkboxes), and when it fires, check whether all required inputs are filled. If so, enable the button. If not, disable it.
There is one loophole here, though. Users can delete the value of a text field without triggering the onkeyup event by using the mouse to "cut" the text out, or by holding down the delete/backspace key once they have deleted it all, and clicking the button before deleting it.
You can get around the second by either
disabling the button with onkeydown and checking if it is ok on onkeyup
checking for validity when the button is clicked
An idea from me:
Define a variable -with global scope- and add the value true- Write a submit function within your check the value above varibale. Evalue the the submit event only, if the value is true.
Write a function which ckecks all value from input fields and select fields. Checking the length of value to zero. if the value length of one field zero then change the value of the global variable to false.
After that, add to all input fields the event 'onKeydown' or 'onKeyUp' and to all select boxes the event 'onChange'.
I recommend taking a slightly different approach and using jquery's validation http://docs.jquery.com/Plugins/validation. The tactic you are suggesting is prone to security holes. The user could easily using firebug enable that button and then submit the form.
Using jquery validation is clean and it allows you to show error messages under the required fields if so desired on submit.

Disable an input field if second input field is filled

totally a newbie...
I just want to know how to dynamically disable an input field when the second input field is filled
eg:
<td><input type="text" name="num-input1" id="dis_rm" value=""></input></td>
<td><input type="text" name="num-input2" id="dis_per" value="" ></input></td>
pls... any links and hints will do...
You simply need to give it a disabled property:
document.getElementById("dis_rm").disabled = true;
document.getElementById("dis_per").disabled = true;
you can use the on change event to see if one of them is filled:
var dis1 = document.getElementById("dis_rm");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("dis_per").disabled = true;
}
}
so if the first one is filled, the second one will be disabled
$('#dis_per').blur(function(){
if($(this).val().length != 0){
$('#dis_rm').attr('disabled', 'disabled');
}
});
http://jsfiddle.net/jasongennaro/D7p6U/
Explanation:
when the second input loses focus... .blur()
check to see if it has something inside it. Do this by making sure its length is not zero !=0
if it has something in it, add the attribute disabled and set it to disabled
$('#secondinput').live('blur',function(){
$('#firstinput').attr('disabled', true);
});
tihs works when you filled the second input field and click else where ..........
Just ad this to your 2nd text box:
onblur="document.getElementById('dis_rm').disabled = (''!=this.value);"
http://jsfiddle.net/vbKjx/
Set the disabled flag on the field you want to disable when the OnBlur event fires (for exiting the field) or when the OnChanged event fires (with, of course, validation on the change).
We can ommit some steps, refering to the form as object.
document.form1.num-input2.onchange = function() {
if ( this.value != "" || this.value.length > 0 ) {
document.form1.num-input1.disabled = true;
}
}
I like this answer, using Jquery:
$('#seconddiv').live('focus',function(){
$('#firstdiv').attr('disabled', true);
});
I have a search bar that gives search results with every key press, if it returns no results then the user is presented with a form to ask for help. But if they fill out the "ask form" then type in the search bar again it will erase everything they entered in the ask form. So to solve this, I gave all the inputs in the ask form an id of "second div" and the search field id="firstdiv". Now, if they click or tab to one of the input fields of the ask form it will disable to search bar so their data will never be over written.
I will also add a button that will re-enable the search form if they change their mind.
And for the newbies - I put the code in the head of the document like this:
<html>
<head>
<script type="text/javascript">
$('#seconddiv').live('focus',function(){
$('#firstdiv').attr('disabled', true);
});
</script>
</head>
<body>
....

Categories