Sorry for noobish question, i am new to html/javascript.
Lets say i have a from:
<form id="pass" >
<p>
Password: <input type="password" name="password" >
Username: <input type="text" name="username" value="User">
<input type="submit" value="Send" class=btn> <input type="Reset" class=btn>
</p>
</form>
And when button is pressed. I want to run function in script.js file, that for example clear the body.
What is the right way to do it?
Many thanks!
Add a code in your form tag as onsubmit="javascript: function_name();" example:
<form name="name" id="name" onsubmit="javascript: function_name();">
// your code
</form>
Now in your JS, write:
<script>
function function_name() {
alert("hi");
}
</script>
Download, include and use jQuery.
Give the button an id (for example, DoSomething) in your markup and call it like this:
$('#DoSomething').click(function() {
alert('my button works');
});
Related
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>
I'm trying to pass credentials to fill automatically the inputs login of this website: https://www.pinterest.pt/login/ .
I don't know what are the variables. So I used the inspect of the browser to know what is the id of each input.
I'm using this code but it is not working:
function Test() {
var name = document.getElementById("id").value;
var password= document.getElementById("password").value;
document.forms["registerForm"].submit(); //form submission
}
<!DOCTYPE html>
<html>
<body>
<form id="registerForm" name="registerForm" method="post" target="_top" action="https://www.pinterest.pt/login/">
<input id="email" name="id" type="email" value="examplelogin" />
<input id="password" name="password" type="password" value="examplepassword" />
<input type="button" name="submit" id="btn" value="Submit" onclick="Test()" />
</form>
</body>
</html>
Do you know what I'm doing wrong?
Thank you for your help.
Not so much an answer to your question, but more of a future reference, you don't need to get all elements within a form via a selector. You can simply use the following technique:
function Test() {
let form = document.getElementById('registerForm');
var password = form.elements.password.value;
var email = form.elements.email.value;
form.submit();
}
Notice how accessing form.elements grants direct access to the element you're trying to read out.
I may just be nit-picking, but since this is a form submit, you probably need to use onsubmit and not just have the button click do something. Try this maybe?
<!DOCTYPE html>
<html>
<body>
<form id="formulario" name="formulario" method="post" target="_top" action="https://www.allianz.pt/area-privada" onsubmit="submitFunction()">
<input id="usuario" name="_58_login" type="text" value="examplelogin" />
<input id="password" name="_58_password" type="password" value="examplepassword" />
<button type="submit">Submit</button>
</form>
<script>
function Test() {
// your submit code
}
</script>
</body>
</html>
Forms can be very picky sometimes. Always best to use a working example for exactly what you're doing as a reference.
How do I solve the error cannot read property of 'addEventListener' of null ? when I add this code,document.getElementById("myForm").addEventListener("submit", SaveBookmark) in my JS file
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="button" id="submitBtn">Submit</button>
</form>
First please notice that you're calling DOM is loaded or duplicated formID.
This code is working fine. please change <button type="button"> to be <button type="submit" .../>
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="submit" id="submitBtn">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", SaveBookmark);
function SaveBookmark() {
alert('success');
}
</script>
I'm by no means an expert but to avoid that error your JS should look like this
const myForm = document.getElementById("myForm");
if (myForm) {
myForm.addEventListener("submit", SaveBookmark)
}
This ensures that your form element exists before you add the event listener
Should work easily:
document.getElementById('myForm').addEventListener('submit', function() {
alert("yes!")
})
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="submit" id="submitBtn">Submit</button>
</form>
It does not work because you have a
<button type="button" id="submitBtn">Submit</button>
instead of:
<button type="submit" id="submitBtn">Submit</button>
and you're trying to reach submit event.
Anyway, i recommend you not to add event listeners due to resource wasting. Use it when it's the only option.
I let you another way to reach the same with default click eventlistener:
<form id="myForm">
<input type="text" id="siteName" size="75%" placeholder="Twitter"><tr>
<input type="text" placeholder="Website URL" size="75%" id="siteName"><br>
<button type="submit" id="submitBtn" onclick="saveBookmark()">Submit</button>
</form>
<script type="text/javascript">
function saveBookmark(){
alert ("Bookmark saved");
}
</script>
You'll click on submit button anyway so, use onclick event instead of creating an eventlistener. It works simplest and waste much less resources...
And remember to add action attribute to the form, trying to re-program defined behaviour will only make your software heavy and heavy on codelines and timeloads. Thats why know the language its important.
Hope it help!
I am trying to validate a form, but I can't get any code to execute when my button is clicked. Here's my code:
<div id="vehicle_form">
<form method="post" name="emailForm" action="">
<input class="dField" id="dfEmail" type="email" name="email" value="Email" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<input class="dField" id="dfName" type="text" name="firstname" value="First Name" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<input class="dField" id="dfLast" type="text" name="lastname" value="Last Name" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<button type="button" id="dSubmit">Submit</button>
</form>
</div>
$('#dSubmit').click(function(){
console.log('click');
});
You need to ensure that your jQuery is wrapped in a <script> tag, and ensure that the function is being loaded, perhaps by a $(document).ready() function, as shown below:
<script type='text/javascript'>
$(document).ready(function(){
//Your Click event
$('#dSubmit').click(function(){
console.log('click');
});
});
</script>
Working Demo
Actually the code stays wrong. A form can be often submitted by hitting enter inside of a textfield. If you want to make it right you should use the submit event.
<script>
$(function(){
$('#vehicle_form > form').submit(function(){
console.log('submit');
});
});
</script>
I've been at this for two days and can't seem to get it. Basically, I'm using the JQuery Cookbook modal from scratch. My problem is the form html page loads fine but the code will not recognize my submit button. Here's the relevant parts of the code:
Separate HTML:
<div id="contact">
<form action="" id="register_form" method="post">
<p>First Name <br />
<input type="text" id="firstname" name="firstname" /></p>
<p>Last Name <br />
<input type="text" id="lastname" name="lastname" /></p>
<p>Username: <span class="micro">Must be a valid email address</span></span><br />
<input type="text" id="username" name="username" /></p>
<p><input type="submit" value="Register" id="register" /></p>
</form>
</div>
Here's the relevant parts of the modal code:
// Insert modal at end of </body>.
$('body').append('<div id="modal_wrapper"><!--[if IE 6]><iframe id="modal_iframe" frameborder="0"></iframe><![endif]--><div id="modal_overlay"></div><div id="modal_window"><div id="modal_bar"><strong>Modal window</strong>Close</div><div id="modal_content"><div id="contact"><form><p><input id="firstname" /></p><p><input id="register" /></p></form></div></div></div>');
$('#modal_content').load('mediaKitF.html#contact'.replace('#', ' #'), '', showModal);
$("input[type=text]").focus(function(){
// Select field contents
this.select();
});
$('input #firstname').focus();
$('#register').click(function () {
alert("hello there");
});
$('#modal_content').load() is an asynchronous method, which means that you are trying to attach your click event to the $('#register') element before receiving the new content. You need to either use $('#register').live('click', function() {}) or move the code attaching the click handler into your showModal function.