Validation with javascript from list - javascript

I'm trying to validate a form filed via javascript. The idea is that the form filed has a set list of accepted values and only these values work. So if the field is black it will alert that the ID is incorrect. If the field has input which is not in the list it will display that ID is incorrect. I have gotten close. I just need a little more direction.
Here is my code:
script type="text/javascript">
function validateForm()
{
var x=document.forms["dispatch"]["ID1"].value;
var arr=["CA238", "Pete", "John"];
if x==(.inArray(inputVal, arr) > -1)
{
alert("Correct Dispatcher ID Required");
return false;
}
}
</script>
<form id="form_242533" class="appnitro" name="dispatch" onsubmit="return validateForm()" method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
<li id="li_9" >
<label class="description" for="element_1">Dispatch ID</label>
<div>
<input id="element_1" name="ID1" class="element text medium" type="text" value=""/> Put your assigned dispatcher ID
</div>
</li>
<li class="buttons">
<input type="hidden" name="Submit" value="Submit" />
<input id="submit" class="button_text" type="submit" name="submit" value="Submit" />
<input type="reset" />
</li>
</ul>
</form>

Change this:
if x==(.inArray(inputVal, arr) > -1)
to this:
if ($.inArray(x, arr) == -1)
if you're using jQuery.
If you don't have jQuery on the page, change it to this instead:
if (arr.indexOf(x) == -1)
Note however, that this method won't work in IE < 9. Use the polyfill provided here to add indexOf support to older versions of IE.

Related

Disable or enable only the current button

With a PHP for each cycle, I'm bringing articles from the database. In those articles, we have a comment section with a form. I want to check with jQuery if there is something written on the input before the comment is sent.
As the articles are being brought with a PHP cycle, I want to check only the article in which it is being written a comment, but jQuery checks all the articles and only enables or disables the first or top result being brought from the database. I want jQuery to check only on the article with a written comment.
Here's what I'm doing:
$(document).ready(function() {
$(".comment-submit").attr("disabled", true);
$("#group-post-comment-input").keyup(function() {
if ($(this).val().length != 0) {
$(".comment-submit").attr("disabled", false);
} else {
$(".comment-submit").attr("disabled", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
As you can see on the snippet above, the buttons only get enabled when text is written on the first input only. I want the buttons to get enabled when text is written on their dependent input. If input 2 has text on it, enable button 2, and so on and so on.
How can I do that?
Since IDs must be unique to the DOM tree, you might consider using a class instead.
$(function() {
$(".group-post-comment-input").on('keyup', function() {
let $button = $(this).next('.comment-submit');
let disabled = !this.value;
$button.prop('disabled', disabled);
});
});
form {
margin: 0 0 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
In my demonstration, I use jQuery's next() to traverse from the input on which the "keyup" event is fired to its associated button.
.next( [selector ] )
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Another method is to traverse up to the form element with closest() and back down to the button with find(). This might be useful if you expect your HTML structure to change in a way that could break the next() traversal.
let $button = $(this).closest('form').find('.comment-submit');
I also recommend using prop() instead of attr() to enable and disable inputs.
ID must be unique,
but you need to use a name for sending information to your PHP server
document.querySelectorAll('button.comment-submit').forEach( bt => bt.disabled = true )
document.querySelectorAll('input[name="group-post-comment-input"]').forEach( inEl =>
inEl.oninput = e =>inEl.nextElementSibling.disabled = (inEl.value.trim().length === 0) )
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>

Issue with form validation Javascript

I am using Bootstrap and I have two identical forms. I am trying to add form submission to Google Search results and it works but when I include two of the same form it doesn't work because of the id being the same on both. How can I fix this? The ID needs to be the same because google looks for the "G". The reason I have two forms is because I have it displayed differently on mobile. Using media queries. Below is my code thanks.
<form name="globalSearch" class="navbar-form" role="search" form action="" onsubmit="return validateSearch()">
<div class="input-group add-on">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="cof" value="FORID:11;NB:1" />
<input type="hidden" name="ie" value="UTF-8" />
<input class="form-control" placeholder="Search entire site..." id="q" name="q" type="text">
<div class="input-group-btn">
<button class="btn btn-default btnSubmit" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
function validateSearch() {
if (globalSearch.q.value.length == 0) {
document.getElementById("q").value = "Enter a Value";
document.getElementById("q").style.color = "red";
return false;
}
}
You probably want to change the placeholder, so the user don't have to delete the text than type in a query. Please view updated function.
function validateSearch() {
var q = document.getElementById('q');
if (q.value.length == 0) {
q.setAttribute('placeholder', 'Enter search term')
q.style.borderColor = "red";
return false;
}
}
Two elements can not share same ID.
Either use CSS styling to make different looks in mobile, either hide one of forms from webserver (PHP/etc) side either dont use getElementById - instead, use jQuery:
<form name="globalSearch" ... >
<input name="q" data-input-type="desktop" id="q">
..
</form>
<script>
function validateSearch() {
var field = $("input[data-input-type="desktop"]');
field.val("Enter value here...");
field.css("color","red");
}
</script>

How to get a specific form elements using jQuery

I have a multiple forms in a page and i would like to get the elements of a specific form. For example:
<form class="form" id="1">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
<form class="form" id="2">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
How to get the value of message of form id=2...... Thanks in advance
Just use attribute selectors
$('form[id=2]') // get the form with id = 2
.find('input[name=message]') // locate the input element with attribute name = message
.attr("value"); // get the attribute = value
You really shouldn't use raw numbers for ids, let's rename those to form_1 and form_2, then your jquery selector would be:
$("#form_2 [name='message']").val();
Simply query the input from the id of the form you'd like
console.log($('#2 input').val());
//more specific
console.log($('#2 input[name="message"]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form" id="1">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
<form class="form" id="2">
<input type="text" name="message" value="message">
<button type="submit" value="submit">Submit</button>
</form>
You can use jQuery, or you can use basic JavaScript to return the message value. With basic JS, you would have to give your form a name, but then could return the message value.
Code:
function getValue() {
var message = document.forms["form_name"]["message"].value;
}
You would then have to return the function when the form is submitted
<form class="form" name="form_name" onsubmit="return getValue()">

jQuery get number of child elements with specific parameters

I have the following piece of code, that is being executed on submit of a form. Yet the following logic is incorrect as the intent was to develop a universal function that would work for all the forms in my DOM. After failing over and over I ended up creating this function, specific to a this form, that verifies if the values of input fields in my form are the same as their custom defVal attribute, if so the form will stop submitting and an error message will pop up.
My question consists on the following: how can i check if any child elements of my form meet specific parameters, like for example being an input field and have their .val() == .attr('defVal')?
I've already tried using .find(), .children() and .childNode functionalities. Could somebody please suggest me a good solution and if possible explain your code
HTML:
<div class="login" align="center">
<div class="formWrapper">
<form action="index.php?r=backoffice" method="post">
<input type="text" name="USERNAME" required value="username" defval="username" maxlength="16">
<input type="password" name="PASSWORD" required value="password" defval="password" maxlength="16">
<input type="reset" value="reset">
<input type="submit" value="submit">
<hr/>
Can't log in?
</form>
</div>
<div class="infoWrapper">
<div class="info">
</div>
</div>
jQuery:
$('div.login').ready(function(){
$('div.login form').submit(function(e){
if( $('div.login form input').val()==$('div.login form input').attr('defVal') ){
var numMsgs=$('div.login form').children();
if( numMsgs.length<=6 ){
var formHtml=$('div.login form').html();
$('div.login form').html('<a class="sysMsg" href="#">error::invalid username/password</a>'+formHtml);
$('div.login form a.sysMsg').addClass('errFatal').fadeIn(300).delay(5000).fadeOut(300);
}
e.preventDefault();
}
});
});
Try (this pattern)
$(function () {
var elems = $(".login input[defval]");
console.log(elems.length);
$.each(elems, function (i, el) {
if ($(el).val() === $(el).attr("defval")) {
// do stuff
console.log(i, $(el).val() === $(el).attr("defval"), $(el));
};
});
});
jsfiddle http://jsfiddle.net/guest271314/9578v/
After sleeping over the subject I ended up managing to do the task. I've changed the html a bit. Anyway thank you for your suggestion as it was quite useful and actualy toaught me something.
HTML:
<div class="login" align="center">
<div class="formWrapper">
<form action="index.php?r=backoffice" method="post">
<p class="jQueryErr">
<?php
if( !empty($_POST['USERNAME']) && !empty($_POST['PASSWORD']) ){
phpClass::USER_login($_POST['USERNAME'],'username',$_POST['PASSWORD'],'password');
}
?>
</p>
<input type="text" name="USERNAME" value="username" defval="username" maxlength="16">
<input type="password" name="PASSWORD" value="password" defval="password" maxlength="16">
<input type="reset" value="reset">
<input type="submit" value="submit">
<hr/>
Can't log in?
</form>
</div>
jQuery:
$('form').submit(function(e){
var elems=$(this).find('input[defval]');
var errWrapper=$(this).find('p.jQueryErr');
for( var i=0; i<elems.length; i++ ){
if( $(elems[i]).val()==$(elems[i]).attr('defVal') ){
$(errWrapper[0]).html('<a class="sysMsg errWarning" href="#">error:: invalid username/password</a>');
var formSysMsg=$('p.jQueryErr a.sysMsg');
$(formSysMsg[0]).fadeIn(300).delay(5000).fadeOut(300);
e.preventDefault();
break;
}else if( $(elems[i]).val().length<8 ){
$(errWrapper[0]).html('<a class="sysMsg errWarning" href="#">error::'+ $(elems[i]).attr('defVal') +'::is too short!</a>');
var formSysMsg=$('p.jQueryErr a.sysMsg');
$(formSysMsg[0]).fadeIn(300).delay(5000).fadeOut(300);
e.preventDefault();
break;
}
}
});

jquery find input before button

I have a single form on the page and I have some jQuery to make sure that the inputs have been completed before the submit.
But now I need to have multiple similar forms repeated on the page and I need to change the jQuery to only check the two inputs in the form that the button was clicked and not check any other form on the page.
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
The jQuery that I have used previously to check on form using ID
// validate signup form on keyup and submit
jQuery('#submitDates').click(function () {
var found = false;
jQuery("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && jQuery(name).val()=='') {
alert ('Please choose your arrival and departure dates!')
found = true;
} ;
});
return !found;
});
.prev( [selector ] )
Returns: jQuery
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
This is quite short and will target any input displayed just before a button :
$("button").prev("input")
jsFiddled here
you can try like this:
CODE
jQuery('.submitDates').click(function () {
var found = false;
jQuery(this).siblings("input").each(function (i, name) {
// Check if field is empty or not
if (!found && jQuery(name).val() == '') {
alert('Please choose your arrival and departure dates!')
found = true;
};
});
return !found;
});
assuming your inputs are siblings for the button. Note I also changed button's id into class.
FIDDLE http://jsfiddle.net/FY9P9/
Closest and Find do it as well, wherever the input are for the button :
HTML:
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
JS:
$(".button").each(function () {
$(this).click(function () {
if (($(this).closest(".form").find(".toDate").val() == "") || ($(this).closest(".form").find(".fromDate").val() == "")) {
alert("Please fill in arrival and departure Date");
}
})
})
http://jsfiddle.net/GuqJF/1/

Categories