Issue with form validation Javascript - 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>

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>

JavaScript Form validation not working; something wrong with onsubmit() attribute?

I cannot work out what is wrong with my code, and why the form validation simply is not firing. The code is an HTML form for inserting books into a database. I removed the PHP and CSS for simplicity's sake, but I can edit it back in if necessary.
function validateNewBook() {
var isbn = document.forms['addNewBook']['isbn'].value;
var title = document.forms['addNewBook']['title'].value;
if (title == ""){
alert("Please enter the book's title.");
return false;
}
return true;
}
<form name="addNewBook" action='#' onsubmit="return validateNewBook()" method="post">
<section id="controls">
<input class="button" type="submit" name="save_new_book" value="Save Book"/>
<input class="button" type="submit" name="browse_books" value="Browse"/>
</section>
<section id="input">
<span>* required field</span>
<span class="flex-input">
<label>ISBN</label><input type="text" name="isbn" id="isbn" size=20 value="" /> <span class="errorMessage">*</span>
</span>
<span class="flex-input">
<label>Title</label><input type="text" name="title" size=50 id="title" value="" />
<span class='errorMessage'>*</span>
</span>
</section>
</form>
However, when I run this code in my fuller program, the form still enters the new book into the database, even when the Title field is empty. What is happening?
It may be the case that user have input blank space on inputbox. So are required to filter that inputbox with trim function.For example.
title.trim();
You need to do before you mention any expresion.

Issue with javascript retrieve form data for url

I am kind of new to javascript however I have created a submit form that I want to redirect me to a url based on form input. Here is my current code...
The issue I'm running into however is that the form is sending me the initial value rather than the updated form value (It is using "whatevs" no matter what).
HTML
<form id="Search-Form" onClick="genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Javascript
function genURL() {
var searchSubmit = document.getElementById("searchSubmit").value;
window.location = "randomsite/view" + searchSubmit;
}
Add return and use onsubmit:
<form id="Search-Form" onsubmit="return genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Revise function like so:
function genURL()
{
location.href = "randomsite/view" + document.getElementById("search").value;
return false;
}
If you were to use onclick, it would go on the button, not the form.

Text field to Hidden field value - value not being set

I'm having an issue with passing hidden values. I have a search field that onclick calls my javascript function with the intention of setting a hidden fields value further down the page.
<div class="search">
<input type="text" name="username" class="mySearch" value="">
<input type="button" class="myButton" value="" onclick="setSearch();">
</div>
My javascript, i is set outside of the function.
setSearch(){
if(i == 0){
$('input:hidden[name="search1"]').val($(".mySearch").val());
}
else if(i == 1)
{
$('input:hidden[name="search2"]').val($(".mySearch").val());
}
i++;
}
and then the field I'm try to set
<div class="sendallHolder">
<form method="post" action="getTweets.php">
<input type="hidden" name="fromTest" id="fromTest"/>
<input type="hidden" name="untilTest" id="untilTest"/>
<input type="hidden" name="latTest" id="latTest"/>
<input type="hidden" name="longTest" id="longTest"/>
<input type="hidden" name="search1" id="search1" />
<input type="hidden" name="search2" id="search2" />
<input type="submit" class="sendAll" value="Gather News!">
</form>
</div>
It runs through the loop twice but each time its not setting the values properly in my hidden fields. the dev tools in chrome tell me that the 'value' is popping up but no value is being set. I'm not entirely sure what I'm doing wrong.
Any ideas?
The :hidden selector doesn't do what you think. It matches elements that have been hidden using CSS, it doesn't match type="hidden" inputs. Just use
$("#search1")
since you have an id on the elements.
Use hidden input ID like this :
$('#search1').val($(".mySearch").val())
$(".mySearch").keyup(addhjc);
function addhjc(){
$('#search2').val($(".mySearch").val());
}
or
$('.myButton').click(function(){
$('#search2').val($(".mySearch").val());
});
also
function setSearch(){
if(i === 0){........
and define i var

HTML form with two submit buttons and two "target" attributes

I have one HTML <form>.
The form has only one action="" attribute.
However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note: This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="submit" formaction="firsttarget.php" value="Submit to first" />
<input type="submit" formaction="secondtarget.php" value="Submit to second" />
</form>
</body>
</html>
This works for me:
<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />
<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila.
Very "fancy", three word JavaScript!
Here's a quick example script that displays a form that changes the target type:
<script type="text/javascript">
function myTarget(form) {
for (i = 0; i < form.target_type.length; i++) {
if (form.target_type[i].checked)
val = form.target_type[i].value;
}
form.target = val;
return true;
}
</script>
<form action="" onSubmit="return myTarget(this);">
<input type="radio" name="target_type" value="_self" checked /> Self <br/>
<input type="radio" name="target_type" value="_blank" /> Blank <br/>
<input type="submit">
</form>
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
http://jsfiddle.net/arzo/unhc3/
<form id='myForm'>
<input type="button" name="first_btn" id="first_btn">
<input type="button" name="second_btn" id="second_btn">
</form>
<script>
$('#first_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "https://foo.com";
form.submit();
});
$('#second_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "http://bar.com";
form.submit();
});
</script>
It is do-able on the server side.
<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin" action="/facebook_login">Facebook</button>
and in my node server side script
app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
function(email_login) {...}
}
if(req.body.signin == "fb_signin"){
function(fb_login) {...}
}
});
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.
<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>
Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not
function v(){
var check = document.getElementsByTagName("input");
for (var i=0; i < check.length; i++) {
if (check[i].type == 'checkbox') {
if (check[i].checked == true) {
x[i]=check[i].value
}
}
}
console.log(x);
}
This might help someone:
Use the formtarget attribute
<html>
<body>
<form>
<!--submit on a new window-->
<input type="submit" formatarget="_blank" value="Submit to first" />
<!--submit on the same window-->
<input type="submit" formaction="_self" value="Submit to second" />
</form>
</body>
</html>
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
e.submitEvent.originalEvent.submitter.value
if you use event of form

Categories