jQuery on click not returning any value - javascript

What I am trying to do is to get all inputs and data when someone click the submit button.
My code HTML is this:
<form id="form" action="index.php" method="POST" class="register" name="Register">
<label>Patient Name:</label>
<input id="pname" name="pname" placeholder="John Doe" type="text" data-role="justText" value=""><br><br>
<label>Phone Number:</label>
<input id="ptel" type="tel" name="ptel" value=""><br><br>
<label>Email:</label>
<input id="pemail" placeholder="example#gmail.com" type="email" value=""><br><br>
<button id="submit" class="submit" type="submit" name="register">Registrar</button>
</form>
Don't know if it's the best use the button or input tag for submit the form. And the jQuery to handle what I am trying to do is this:
jQuery.fn.extend({
hello: function () {
submitbutton = $(this).find('button').attr('id');
$inputs = $(this).find('input');
knowInputs = function() {
$inputs.each(function () {
console.log( $(this).attr('name') );
});
}
$('#'+submitbutton).on('click', function () {
knowInputs();
})
return this;
}
});
So, I put the form ID and init the function like this:
$(#form).hello();
P.D.: If I put the code knowInputs outside the on(click), it seems to work fine. My problem is when I am trying to gather all when clicking the submit button.
Any help shall be appreciated. Thanks in advance!

Forms have a native Javascript event, submit. jQuery also has a function, $.serialize which will turn a form into an encoded URL string, which is probably the most standard format you'd want it in. You can easily convert this into JSON or a JS Object.
$('#form').submit(function(e){
e.preventDefault();
return $(this).serialize();
});

Related

Required Input Field + Onlick Button request

Currently I am trying to make my input field required.
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<center><button id="process2" type="submit">Continue</button> </center>
</form>
When I have the above portion it works, however I need it to work whenever I have my button containing a onlick event. <button id="process2" type="submit" onclick="move()">Continue</button> how can I go about doing this?
The issue is currently - The onclick request will fire, and it'll prompt the required option, however the onclick request should not fire unless the required option is populated.
Instead of the onclick , you should listen for the form's submit, and call move() inside it
document.querySelector('form').addEventListener('submit', event => {
event.preventDefault();
console.log('submitted');
move();
});
function move() {
console.log('moving ..');
}
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<button id="process2" type="submit">Continue</button>
</form>
Or you can just simply fire the move function but wrap your deserted effect inside if statement that will check if input is empty or not...
function move() {
element = document.getElementById("username").value;
if (element === "") {
console.log("input wasnt populated do something");
}
}
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<center><button id="process2" type="submit" onclick="move()">Continue</button> </center>
</form>
Using jquery you can listen the submit event on form like then call move function to redirect to other page or whatever logic you want
$(document).on('submit','form',function(){
event.preventDefault();
// call move function here , move();
});

How to embed form data in the action link?

I have a form defined:
<form method="post">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
Currently, when this form is submitted I am able to work with the data and add info to the page based on the value of phone_or_uid. However, what I'd like to do is something where the form redirects to the same page but with the value of phone_or_uid appended to the end. So, if the initial page is https://myhost.com/lookup then submitting the form should bring the user to https://myhost.com/lookup/16175431234 if the value of the phone_or_uid input box is 16175431234.
Essentially, my form should then look something like this:
<form action={some code that puts the value of phone_or_uid here}>
...
</form>
Is this possible? And if so, how could I accomplish this? I don't want to create or redirect to any extra files, if possible.
I would use JavaScript. Listen for the submit event and redirect to a custom url.
this is just a really general example:
<form method="post" onsubmit="submitFunction()">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" id="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
<script>
submitFunction = (event) => {
event.preventDefault();
const phoneInfo = document.getElementById('phone_or_uid').value;
fetch('http://myhost.com/lookup/' + phoneInfo, {
method: 'post'
})
.then(response => {
window.location.href = "http://myhost.com/lookup/' + phoneInfo";
});
}
</script>

Multiple form validation with same function

I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})

Is it possible to execute simple javascript statments from an input field in a document?

In the example below I've attached a function main to an input field. the function contains instructions to send an alert with a variable message (whatever the user enters into the field).
<form>
<input type="text" onsubmit="main()" />
<input type="submit" />
</form>
<script>
function main (param) {
alert(param)
}
//main();
</script>
It doesn't work, but I believe that's because I've made some noob error that I'm failing to recognize. The result of a functioning version of this code would be the ability to submit "hello world" and produce an alert box stating 'hello world' (without quotes).
But, further than this, I'd like to be able to pass the likes of main("hello world"); or just alert('hello world'); to the input field to produce the same result.
The problem I think I'm running into is that the page is refreshed every time I submit. There are a few questions on here with similar problems where people have suggested the use of onsubmit="main(); return false;", but in fact this does not seem to work.
Looks like you want to eval() the value of the input.
Use with caution, has security impact...
Returning false from a handler stops the regular action so you have no redirect after submitting:
<form onsubmit="main(); return false;">
<input id="eval-input" type="text" />
<input type="submit" />
</form>
<script>
function main () {
eval(document.getElementById('eval-input').value);
}
</script>
Here's how you can detect a form submission:
<form onsubmit="foo()">
<input type="text">
<input type="submit">
</form>
<script>
function foo(){
alert("function called");
}
</script>
I however advise you do this (preference), if you desire to manage the form data through a function:
<form id="myform">
<input type="text">
<input type="submit">
</form>
<script>
document.getElementById("myform").onsubmit=function(event){
alert("function called");
//manage form submission here, such as AJAX and validation
event.preventDefault(); //prevents a normal/double submission
return false; //also prevents normal/double a double submission
};
</script>
EDIT:
use eval() to execute a string as JavaScript.
jQuery way:
You create event listener which will be triggered when user click 'submit'.
<form>
<input type="text" id="text"/>
<input type="submit" />
</form>
<script>
$( "form" ).submit(function( event ) {
event.preventDefault();
alert( $('#text').val() );
});
</script>
To prevent page reloading - you should use event.preventDefault();
Pure JavaScript:
<form>
<input type="text" id="text"/>
<input type="submit" id="submit" />
</form>
<script>
var button = document.getElementById("submit");
var text = document.getElementById("text");
button.addEventListener("click",function(e){
alert(text.value);
},false);
</script>
If I understand what you want to do, you can call the function like this, and writing params[0].value you can access the input value:
function main(params) {
//dosomething;
document.write(params[0].value);
}
<form onsubmit="main(this)">
<input type="text">
<input type="submit">
</form>
Try something like this
onchange="main()"
onmouseenter, onMouseOver, onmouseleave ...
<input type="text" onmouseenter="main()" />

Trigger html form submit as if you clicked on button (but without a button)?

If you have a <form> and a <button type='submit'> and you click on the submit button, it will do the default form validation, such as checking whether an <input> is required or not. It would normally say Please fill out this field.
However, if I programmatically submit the form through $("form").submit() for example, it would submit it without performing any checks.
Is there a simpler way to perform the default form validations using native JavaScript? There seems to be only checkValidity() on the form element which return true or false. And if I call the same native function on the input itself, it doesn't really do anything.
Here is a demo code of what I mean:
http://jsfiddle.net/totszwai/yb7arnda/
For those still struggling:
You can use the Constraint validation API - https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
<div id="app">
<form>
<input type="text" required placeholder="name">
<input type="text" required placeholder="email">
</form>
<button id="save">Submit</button>
</div>
const form = document.querySelector("form");
document.getElementById("save").addEventListener("click", e => {
e.preventDefault();
if (form.checkValidity()) {
console.log("submit ...");
} else {
form.reportValidity();
}
});
Check out and play here: https://stackblitz.com/edit/js-t1vhdn?file=index.js
I hope it helps or gives you ideas. :)
I think this might be the answer you are looking for :
JavaScript :
document
.getElementById('button')
.addEventListener("click",function(e) {
document.getElementById('myForm').validate();
});
HTML :
<form id="myForm" >
First name: <input type="text" name="FirstName" required><br>
Last name: <input type="text" name="LastName" required><br>
<button id="button">Trigger Form Submit</button>
</form>
Demo : http://jsfiddle.net/2ahLcd4d/2/

Categories

Resources